You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2021/03/29 04:21:15 UTC
[GitHub] [spark] HeartSaVioR opened a new pull request #31987: [WIP][SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
HeartSaVioR opened a new pull request #31987:
URL: https://github.com/apache/spark/pull/31987
Introduction: this PR is a part of SPARK-10816 (`EventTime based sessionization (session window)`). Please refer #31937 to see the overall view of the code change. (Note that code diff could be diverged a bit.)
### What changes were proposed in this pull request?
This PR introduces MergingSessionsIterator, which enables to merge elements belong to the same session directly.
MergingSessionsIterator is a variant of SortAggregateIterator which merges the session windows based on the fact input rows are sorted by "group keys + the start time of session window". When merging windows, MergingSessionsIterator also applies aggregations on merged window, which eliminates the necessity on buffering inputs (which requires copying rows) and update the session spec for each input.
MergingSessionsIterator is quite performant compared to UpdatingSessionsIterator brought by SPARK-34888. Note that MergingSessionsIterator can only apply to the cases aggregation can be applied altogether, so there're still rooms for UpdatingSessionIterator to be used.
This issue also introduces MergingSessionsExec which is the physical node on leveraging MergingSessionsIterator to sort the input rows and aggregate rows according to the session windows.
### Why are the changes needed?
This part is a one of required on implementing SPARK-10816.
### Does this PR introduce _any_ user-facing change?
No.
### How was this patch tested?
WIP (new test suite is expected to be added, or can be skipped if we agree it can be skipped)
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-865983631
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140130/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-865811762
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44657/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r657421745
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsExec.scala
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Ascending, Attribute, AttributeSet, Expression, MutableProjection, NamedExpression, SortOrder, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.physical._
+import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.SQLMetrics
+
+/**
+ * This node is a variant of SortAggregateExec which merges the session windows based on the fact
+ * child node will provide inputs as sorted by group keys + the start time of session window.
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ *
+ * This class receives requiredChildDistribution from caller, to enable merging session in
+ * local partition before shuffling. Specifying both parameters to None won't trigger shuffle,
+ * but sort would still happen per local partition.
+ *
+ * Refer [[MergingSessionsIterator]] for more details.
+ */
+case class MergingSessionsExec(
+ requiredChildDistributionExpressions: Option[Seq[Expression]],
+ requiredChildDistributionOption: Option[Seq[Distribution]],
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ child: SparkPlan) extends UnaryExecNode {
Review comment:
seems okay, the tests were passed.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866722966
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44726/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809954006
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/41272/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-810092318
**[Test build #136690 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/136690/testReport)** for PR 31987 at commit [`4d9c724`](https://github.com/apache/spark/commit/4d9c724a20cb799e229b80133a6bfd8887990d5a).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809947223
Kubernetes integration test unable to build dist.
exiting with code: 1
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/41272/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-810114349
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/136690/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [WIP][SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809087002
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/136627/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-817532375
**[Test build #137191 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/137191/testReport)** for PR 31987 at commit [`57dbee8`](https://github.com/apache/spark/commit/57dbee868719099f66fe491d167509c84b1ec8b8).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809922449
Kubernetes integration test starting
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/41267/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [WIP][SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809058939
**[Test build #136627 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/136627/testReport)** for PR 31987 at commit [`5020827`](https://github.com/apache/spark/commit/5020827a74b7bbe67951057ef64a09061c099d90).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r655987301
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
+ sessionStruct.setLong(1, sessionEnd)
+ }
+
+ private def expandEndOfCurrentSession(sessionEnd: Long): Unit = {
Review comment:
Let's refrain `processCurrentSortedGroup` to deal with session struct directly. It'd be odd if we use functions to get the value but directly set it.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-817437108
**[Test build #137191 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/137191/testReport)** for PR 31987 at commit [`57dbee8`](https://github.com/apache/spark/commit/57dbee868719099f66fe491d167509c84b1ec8b8).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-865722322
**[Test build #140130 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140130/testReport)** for PR 31987 at commit [`235ca5d`](https://github.com/apache/spark/commit/235ca5d5d2e9b724d442231f6dbecd0863c294ba).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r656850924
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
Review comment:
Yea, agree.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866655456
NOTE: I reran GA manually and somewhat the actual verification is gone. Please don't merge relying on GA build, and check the build via https://github.com/HeartSaVioR/spark/actions/runs/963446874 instead.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [WIP][SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809079495
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/41210/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809902693
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/136685/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-865811762
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44657/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
viirya commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-867120759
Thanks @HeartSaVioR and @xuanyuanking! Merging to master.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866828611
**[Test build #140198 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140198/testReport)** for PR 31987 at commit [`ebe4edf`](https://github.com/apache/spark/commit/ebe4edf6b12c3c6b7b2c373747abf9f281bc9bb0).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809901935
**[Test build #136685 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/136685/testReport)** for PR 31987 at commit [`4f13b35`](https://github.com/apache/spark/commit/4f13b35ba740a2438795f877ac98d10b7eb357b2).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya edited a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
viirya edited a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-847599130
<del>Yea, I will review this this week.</del> (sorry for late, I will find some time to review this soon)
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r656886604
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsExec.scala
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Ascending, Attribute, AttributeSet, Expression, MutableProjection, NamedExpression, SortOrder, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.physical._
+import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.SQLMetrics
+
+/**
+ * This node is a variant of SortAggregateExec which merges the session windows based on the fact
+ * child node will provide inputs as sorted by group keys + the start time of session window.
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ *
+ * This class receives requiredChildDistribution from caller, to enable merging session in
+ * local partition before shuffling. Specifying both parameters to None won't trigger shuffle,
+ * but sort would still happen per local partition.
+ *
+ * Refer [[MergingSessionsIterator]] for more details.
+ */
+case class MergingSessionsExec(
+ requiredChildDistributionExpressions: Option[Seq[Expression]],
+ requiredChildDistributionOption: Option[Seq[Distribution]],
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ child: SparkPlan) extends UnaryExecNode {
Review comment:
Let's do it as it doesn't look to break the new tests.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-865807792
Kubernetes integration test unable to build dist.
exiting with code: 1
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44657/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [WIP][SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809079495
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/41210/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r655483515
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
Review comment:
nit: indent
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
Review comment:
Not a big deal and can be addressed later. Duplicated code with `SortBasedAggregationIterator`, I think we can avoid this by adding some abstractions.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
+ sessionStruct.setLong(1, sessionEnd)
+ }
+
+ private def expandEndOfCurrentSession(sessionEnd: Long): Unit = {
Review comment:
seems only used once in `processCurrentSortedGroup`? If so, maybe make it an inner function.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
Review comment:
To distinguish with line 169, maybe comment `we find a new session window for the same grouping key` here?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
Review comment:
only be used once in `expandEndOfCurrentSession`, maybe not necessary to be a function?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
+ sessionStruct.setLong(1, sessionEnd)
+ }
+
+ private def expandEndOfCurrentSession(sessionEnd: Long): Unit = {
+ if (sessionEnd > getSessionEnd(currentSession)) {
+ updateSessionEnd(currentSession, sessionEnd)
+ }
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Iterator's public methods
+ ///////////////////////////////////////////////////////////////////////////
+
+ override final def hasNext: Boolean = {
+ if (errorOnIterator) {
+ throw new IllegalStateException("The iterator is already corrupted.")
+ }
+ sortedInputHasNewGroup
+ }
+
+ override final def next(): UnsafeRow = {
+ if (hasNext) {
+ // Process the current group.
+ processCurrentSortedGroup()
+ // Generate output row for the current group.
+
Review comment:
nit: extra empty line
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
Review comment:
A little bit confuse about the naming `findNextPartition`. Followed by the code, IIUC, the meaning might be `findNewWindow` or `findNextGroup`?
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809902679
**[Test build #136685 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/136685/testReport)** for PR 31987 at commit [`4f13b35`](https://github.com/apache/spark/commit/4f13b35ba740a2438795f877ac98d10b7eb357b2).
* This patch **fails Scala style tests**.
* This patch merges cleanly.
* This patch adds no public classes.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866654176
**[Test build #140198 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140198/testReport)** for PR 31987 at commit [`ebe4edf`](https://github.com/apache/spark/commit/ebe4edf6b12c3c6b7b2c373747abf9f281bc9bb0).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809926265
Kubernetes integration test status failure
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/41267/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866838671
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140198/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-817453304
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/41769/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-817437108
**[Test build #137191 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/137191/testReport)** for PR 31987 at commit [`57dbee8`](https://github.com/apache/spark/commit/57dbee868719099f66fe491d167509c84b1ec8b8).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r656850523
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
+ sessionStruct.setLong(1, sessionEnd)
+ }
+
+ private def expandEndOfCurrentSession(sessionEnd: Long): Unit = {
Review comment:
Make sense.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866654176
**[Test build #140198 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140198/testReport)** for PR 31987 at commit [`ebe4edf`](https://github.com/apache/spark/commit/ebe4edf6b12c3c6b7b2c373747abf9f281bc9bb0).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809925942
**[Test build #136690 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/136690/testReport)** for PR 31987 at commit [`4d9c724`](https://github.com/apache/spark/commit/4d9c724a20cb799e229b80133a6bfd8887990d5a).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809901935
**[Test build #136685 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/136685/testReport)** for PR 31987 at commit [`4f13b35`](https://github.com/apache/spark/commit/4f13b35ba740a2438795f877ac98d10b7eb357b2).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809902693
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/136685/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r656822010
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
Review comment:
We can do duplication later if needed.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,251 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextGroup = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextGroup && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new session window in the same group.
+ findNextGroup = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextGroup = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextGroup) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(
+ currentRow: InternalRow,
+ groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ private def expandEndOfCurrentSession(sessionEnd: Long): Unit = {
+ if (sessionEnd > getSessionEnd(currentSession)) {
+ currentSession.setLong(1, sessionEnd)
+ }
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Iterator's public methods
+ ///////////////////////////////////////////////////////////////////////////
+
+ override final def hasNext: Boolean = {
+ if (errorOnIterator) {
+ throw new IllegalStateException("The iterator is already corrupted.")
+ }
+ sortedInputHasNewGroup
+ }
+
+ override final def next(): UnsafeRow = {
+ if (hasNext) {
+ // Process the current group.
+ processCurrentSortedGroup()
+ // Generate output row for the current group.
+ val groupingKey = generateGroupingKey()
+
+ val outputRow = generateOutput(groupingKey, sortBasedAggregationBuffer)
+ // Initialize buffer values for the next group.
+ initializeBuffer(sortBasedAggregationBuffer)
+ numOutputRows += 1
+ outputRow
+ } else {
+ // no more result
+ throw new NoSuchElementException
+ }
+ }
+
+ private val join = new JoinedRow
+
+ private val groupingKeyProj = GenerateUnsafeProjection.generate(groupingExpressions,
+ groupingWithoutSessionAttributes :+ sessionExpression.toAttribute)
+
+ private def generateGroupingKey(): UnsafeRow = {
+ val newRow = new SpecificInternalRow(Seq(sessionExpression.toAttribute).toStructType)
+ newRow.update(0, currentSession)
Review comment:
newRow -> session or sessionStruct?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsExec.scala
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Ascending, Attribute, AttributeSet, Expression, MutableProjection, NamedExpression, SortOrder, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.plans.physical._
+import org.apache.spark.sql.execution.{SparkPlan, UnaryExecNode}
+import org.apache.spark.sql.execution.metric.SQLMetrics
+
+/**
+ * This node is a variant of SortAggregateExec which merges the session windows based on the fact
+ * child node will provide inputs as sorted by group keys + the start time of session window.
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ *
+ * This class receives requiredChildDistribution from caller, to enable merging session in
+ * local partition before shuffling. Specifying both parameters to None won't trigger shuffle,
+ * but sort would still happen per local partition.
+ *
+ * Refer [[MergingSessionsIterator]] for more details.
+ */
+case class MergingSessionsExec(
+ requiredChildDistributionExpressions: Option[Seq[Expression]],
+ requiredChildDistributionOption: Option[Seq[Distribution]],
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ child: SparkPlan) extends UnaryExecNode {
Review comment:
Do we need to extend `BaseAggregateExec` like `SortAggregateExec`? `producedAttributes`, `aggregateBufferAttributes`look like the same.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809926279
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/41267/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-810114349
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/136690/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r655483515
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
Review comment:
nit: indent
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
Review comment:
Not a big deal and can be addressed later. Duplicated code with `SortBasedAggregationIterator`, I think we can avoid this by adding some abstractions.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
+ sessionStruct.setLong(1, sessionEnd)
+ }
+
+ private def expandEndOfCurrentSession(sessionEnd: Long): Unit = {
Review comment:
seems only used once in `processCurrentSortedGroup`? If so, maybe make it an inner function.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
Review comment:
To distinguish with line 169, maybe comment `we find a new session window for the same grouping key` here?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
Review comment:
only be used once in `expandEndOfCurrentSession`, maybe not necessary to be a function?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
+ sessionStruct.setLong(1, sessionEnd)
+ }
+
+ private def expandEndOfCurrentSession(sessionEnd: Long): Unit = {
+ if (sessionEnd > getSessionEnd(currentSession)) {
+ updateSessionEnd(currentSession, sessionEnd)
+ }
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Iterator's public methods
+ ///////////////////////////////////////////////////////////////////////////
+
+ override final def hasNext: Boolean = {
+ if (errorOnIterator) {
+ throw new IllegalStateException("The iterator is already corrupted.")
+ }
+ sortedInputHasNewGroup
+ }
+
+ override final def next(): UnsafeRow = {
+ if (hasNext) {
+ // Process the current group.
+ processCurrentSortedGroup()
+ // Generate output row for the current group.
+
Review comment:
nit: extra empty line
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
Review comment:
A little bit confuse about the naming `findNextPartition`. Followed by the code, IIUC, the meaning might be `findNewWindow` or `findNextGroup`?
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-817453304
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/41769/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809925942
**[Test build #136690 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/136690/testReport)** for PR 31987 at commit [`4d9c724`](https://github.com/apache/spark/commit/4d9c724a20cb799e229b80133a6bfd8887990d5a).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809954006
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/41272/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-817533873
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/137191/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-865983631
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140130/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-867224779
Thanks all for reviewing and merging!
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866722966
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44726/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-865722322
**[Test build #140130 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140130/testReport)** for PR 31987 at commit [`235ca5d`](https://github.com/apache/spark/commit/235ca5d5d2e9b724d442231f6dbecd0863c294ba).
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
viirya commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-847599130
Yea, I will review this this week.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866697994
Kubernetes integration test status failure
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44726/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [WIP][SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809087002
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/136627/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-817448847
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866616572
Yea, agree on the duplication is a minor issue for now.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-809926279
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/41267/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-817533873
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/137191/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-865958345
**[Test build #140130 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140130/testReport)** for PR 31987 at commit [`235ca5d`](https://github.com/apache/spark/commit/235ca5d5d2e9b724d442231f6dbecd0863c294ba).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #31987:
URL: https://github.com/apache/spark/pull/31987#discussion_r655972086
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
Review comment:
Unfortunately I don't remember clear as the original code is 2.5+ years ago, but I guess I tried to deduplicate with SortBasedAggregationIterator but gave up due to its complexity. If someone has brilliant idea to deduplicate then I'm happy to.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
Review comment:
That was actually followed by SortBasedAggregationIterator, but findNextGroup should be clearer (even for SortBasedAggregationIterator). Let's change the name here for now.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
+ val bufferSchema = aggregateFunctions.flatMap(_.aggBufferAttributes)
+ val bufferRowSize: Int = bufferSchema.length
+
+ val genericMutableBuffer = new GenericInternalRow(bufferRowSize)
+ val useUnsafeBuffer = bufferSchema.map(_.dataType).forall(UnsafeRow.isMutable)
+
+ val buffer = if (useUnsafeBuffer) {
+ val unsafeProjection =
+ UnsafeProjection.create(bufferSchema.map(_.dataType))
+ unsafeProjection.apply(genericMutableBuffer)
+ } else {
+ genericMutableBuffer
+ }
+ initializeBuffer(buffer)
+ buffer
+ }
+
+ ///////////////////////////////////////////////////////////////////////////
+ // Mutable states for sort based aggregation.
+ ///////////////////////////////////////////////////////////////////////////
+
+ // The partition key of the current partition.
+ private[this] var currentGroupingKey: UnsafeRow = _
+
+ private[this] var currentSession: UnsafeRow = _
+
+ // The partition key of next partition.
+ private[this] var nextGroupingKey: UnsafeRow = _
+
+ private[this] var nextGroupingSession: UnsafeRow = _
+
+ // The first row of next partition.
+ private[this] var firstRowInNextGroup: InternalRow = _
+
+ // Indicates if we has new group of rows from the sorted input iterator
+ private[this] var sortedInputHasNewGroup: Boolean = false
+
+ // The aggregation buffer used by the sort-based aggregation.
+ private[this] val sortBasedAggregationBuffer: InternalRow = newBuffer
+
+ private[this] val groupingWithoutSessionProjection: UnsafeProjection =
+ UnsafeProjection.create(groupingWithoutSession, valueAttributes)
+
+ private[this] val sessionProjection: UnsafeProjection =
+ UnsafeProjection.create(Seq(sessionExpression), valueAttributes)
+
+ // The flag indicating there's error on iterator, sort precondition is not fulfilled.
+ private var errorOnIterator: Boolean = false
+
+ protected def initialize(): Unit = {
+ if (inputIterator.hasNext) {
+ initializeBuffer(sortBasedAggregationBuffer)
+ val inputRow = inputIterator.next()
+ nextGroupingKey = groupingWithoutSessionProjection(inputRow).copy()
+ val session = sessionProjection(inputRow)
+ nextGroupingSession = session.getStruct(0, 2).copy()
+ firstRowInNextGroup = inputRow.copy()
+ sortedInputHasNewGroup = true
+ } else {
+ // This inputIter is empty.
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ initialize()
+
+ /** Processes rows in the current group. It will stop when it find a new group. */
+ protected def processCurrentSortedGroup(): Unit = {
+ currentGroupingKey = nextGroupingKey
+ currentSession = nextGroupingSession
+
+ // Now, we will start to find all rows belonging to this group.
+ // We create a variable to track if we see the next group.
+ var findNextPartition = false
+ // firstRowInNextGroup is the first row of this group. We first process it.
+ processRow(sortBasedAggregationBuffer, firstRowInNextGroup)
+
+ // The search will stop when we see the next group or there is no
+ // input row left in the iter.
+ while (!findNextPartition && inputIterator.hasNext) {
+ // Get the grouping key.
+ val currentRow = inputIterator.next()
+ val groupingKey = groupingWithoutSessionProjection(currentRow)
+
+ val session = sessionProjection(currentRow)
+ val sessionStruct = session.getStruct(0, 2)
+ val sessionStart = getSessionStart(sessionStruct)
+ val sessionEnd = getSessionEnd(sessionStruct)
+
+ // Check if the current row belongs the current input row.
+ if (currentGroupingKey == groupingKey) {
+ if (sessionStart < getSessionStart(currentSession)) {
+ errorOnIterator = true
+ throw new IllegalStateException("Input iterator is not sorted based on session!")
+ } else if (sessionStart <= getSessionEnd(currentSession)) {
+ // expanding session length if needed
+ expandEndOfCurrentSession(sessionEnd)
+ processRow(sortBasedAggregationBuffer, currentRow)
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ } else {
+ // We find a new group.
+ findNextPartition = true
+ startNewSession(currentRow, groupingKey, sessionStruct)
+ }
+ }
+
+ // We have not seen a new group. It means that there is no new row in the input
+ // iter. The current group is the last group of the iter.
+ if (!findNextPartition) {
+ sortedInputHasNewGroup = false
+ }
+ }
+
+ private def startNewSession(currentRow: InternalRow, groupingKey: UnsafeRow,
+ sessionStruct: UnsafeRow): Unit = {
+ nextGroupingKey = groupingKey.copy()
+ nextGroupingSession = sessionStruct.copy()
+ firstRowInNextGroup = currentRow.copy()
+ }
+
+ private def getSessionStart(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(0)
+ }
+
+ private def getSessionEnd(sessionStruct: UnsafeRow): Long = {
+ sessionStruct.getLong(1)
+ }
+
+ def updateSessionEnd(sessionStruct: UnsafeRow, sessionEnd: Long): Unit = {
Review comment:
will inline.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/aggregate/MergingSessionsIterator.scala
##########
@@ -0,0 +1,254 @@
+/*
+ * 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.spark.sql.execution.aggregate
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, JoinedRow, MutableProjection, NamedExpression, SpecificInternalRow, UnsafeProjection, UnsafeRow}
+import org.apache.spark.sql.catalyst.expressions.aggregate.AggregateExpression
+import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.execution.metric.SQLMetric
+
+/**
+ * This is a variant of SortAggregateIterator which merges the session windows based on the fact
+ * input rows are sorted by "group keys + the start time of session window".
+ *
+ * When merging windows, it also applies aggregations on merged window, which eliminates the
+ * necessity on buffering inputs (which requires copying rows) and update the session spec
+ * for each input.
+ */
+class MergingSessionsIterator(
+ partIndex: Int,
+ groupingExpressions: Seq[NamedExpression],
+ sessionExpression: NamedExpression,
+ valueAttributes: Seq[Attribute],
+ inputIterator: Iterator[InternalRow],
+ aggregateExpressions: Seq[AggregateExpression],
+ aggregateAttributes: Seq[Attribute],
+ initialInputBufferOffset: Int,
+ resultExpressions: Seq[NamedExpression],
+ newMutableProjection: (Seq[Expression], Seq[Attribute]) => MutableProjection,
+ numOutputRows: SQLMetric)
+ extends AggregationIterator(
+ partIndex,
+ groupingExpressions,
+ valueAttributes,
+ aggregateExpressions,
+ aggregateAttributes,
+ initialInputBufferOffset,
+ resultExpressions,
+ newMutableProjection) {
+
+ val groupingWithoutSession: Seq[NamedExpression] =
+ groupingExpressions.diff(Seq(sessionExpression))
+ val groupingWithoutSessionAttributes: Seq[Attribute] = groupingWithoutSession.map(_.toAttribute)
+
+ /**
+ * Creates a new aggregation buffer and initializes buffer values
+ * for all aggregate functions.
+ */
+ private def newBuffer: InternalRow = {
Review comment:
Unfortunately I don't remember clear as the original code is 2.5+ years ago, but I guess I tried to deduplicate with SortBasedAggregationIterator but gave up due to its complexity. The file is quite a copy and paste of SortBasedAggregationIterator, so you'll find lots of duplicated codes here. If someone has brilliant idea to deduplicate then I'm happy to.
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866692684
Kubernetes integration test starting
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44726/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-866838671
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140198/
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya closed pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
viirya closed pull request #31987:
URL: https://github.com/apache/spark/pull/31987
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on pull request #31987: [SPARK-34889][SS] Introduce MergingSessionsIterator merging elements directly which belong to the same session
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on pull request #31987:
URL: https://github.com/apache/spark/pull/31987#issuecomment-847581635
I forgot I cc.ed no one here. lol
cc. @viirya @xuanyuanking Please take a look. Thanks in advance!
--
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.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org