pgandhi999 commented on a change in pull request #23778: [SPARK-24935][SQL] : 
Problem with Executing Hive UDF's from Spark 2.2 Onwards
URL: https://github.com/apache/spark/pull/23778#discussion_r263827958
 
 

 ##########
 File path: 
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/interfaces.scala
 ##########
 @@ -524,23 +524,142 @@ abstract class TypedImperativeAggregate[T] extends 
ImperativeAggregate {
   /** De-serializes the serialized format Array[Byte], and produces 
aggregation buffer object T */
   def deserialize(storageFormat: Array[Byte]): T
 
+  override def initialize(buffer: InternalRow): Unit = {
+    buffer(mutableAggBufferOffset) = createAggregationBuffer()
+  }
+
+  override def update(buffer: InternalRow, input: InternalRow): Unit = {
+    buffer(mutableAggBufferOffset) = update(getBufferObject(buffer), input)
+  }
+
+  override def merge(buffer: InternalRow, inputBuffer: InternalRow): Unit = {
+    val bufferObject = getBufferObject(buffer)
+    // The inputBuffer stores serialized aggregation buffer object produced by 
partial aggregate
+    val inputObject = deserialize(inputBuffer.getBinary(inputAggBufferOffset))
+    buffer(mutableAggBufferOffset) = merge(bufferObject, inputObject)
+  }
+
+  override def eval(buffer: InternalRow): Any = {
+    eval(getBufferObject(buffer))
+  }
+
+  private[this] val anyObjectType = ObjectType(classOf[AnyRef])
+  private def getBufferObject(bufferRow: InternalRow): T = {
+    bufferRow.get(mutableAggBufferOffset, anyObjectType).asInstanceOf[T]
+  }
+
+  override lazy val aggBufferAttributes: Seq[AttributeReference] = {
+    // Underlying storage type for the aggregation buffer object
+    Seq(AttributeReference("buf", BinaryType)())
+  }
+
+  override lazy val inputAggBufferAttributes: Seq[AttributeReference] =
+    aggBufferAttributes.map(_.newInstance())
+
+  override def aggBufferSchema: StructType = 
StructType.fromAttributes(aggBufferAttributes)
+
+  /**
+   * In-place replaces the aggregation buffer object stored at buffer's index
+   * `mutableAggBufferOffset`, with SparkSQL internally supported underlying 
storage format
+   * (BinaryType).
+   *
+   * This is only called when doing Partial or PartialMerge mode aggregation, 
before the framework
+   * shuffle out aggregate buffers.
+   */
+  def serializeAggregateBufferInPlace(buffer: InternalRow): Unit = {
+    buffer(mutableAggBufferOffset) = serialize(getBufferObject(buffer))
+  }
+}
+
+/**
+ * Aggregation function which allows **arbitrary** user-defined java object to 
be used as internal
+ * aggregation buffer for Hive.
+ */
+abstract class HiveTypedImperativeAggregate[T] extends 
TypedImperativeAggregate[T] {
+
+  /**
+   * Creates an empty aggregation buffer object for partial 1 mode. This is 
called
+   * before processing each key group(group by key).
+   *
+   * @return an aggregation buffer object
+   */
+  def createAggregationBuffer(): T
+
+  /**
+   * Creates an empty aggregation buffer object for partial 2 mode.
+   *
+   * @return an aggregation buffer object
+   */
+  def createPartial2ModeAggregationBuffer(): T
+
+  var partial2ModeBuffer: InternalRow = _
+
+  /**
+   * Updates the aggregation buffer object with an input row and returns a new 
buffer object. For
+   * performance, the function may do in-place update and return it instead of 
constructing new
+   * buffer object.
+   *
+   * This is typically called when doing Partial or Complete mode aggregation.
+   *
+   * @param buffer The aggregation buffer object.
+   * @param input an input row
+   */
+  def update(buffer: T, input: InternalRow): T
+
+  /**
+   * Merges an input aggregation object into aggregation buffer object and 
returns a new buffer
+   * object. For performance, the function may do in-place merge and return it 
instead of
+   * constructing new buffer object.
+   *
+   * This is typically called when doing PartialMerge or Final mode 
aggregation.
+   *
+   * @param buffer the aggregation buffer object used to store the aggregation 
result.
+   * @param input an input aggregation object. Input aggregation object can be 
produced by
+   *              de-serializing the partial aggregate's output from Mapper 
side.
+   */
+  def merge(buffer: T, input: T): T
+
+  /**
+   * Generates the final aggregation result value for current key group with 
the aggregation buffer
+   * object.
+   *
+   * Developer note: the only return types accepted by Spark are:
+   *   - primitive types
+   *   - InternalRow and subclasses
+   *   - ArrayData
+   *   - MapData
+   *
+   * @param buffer aggregation buffer object.
+   * @return The aggregation result of current key group
+   */
+  def eval(buffer: T): Any
+
+  /** Serializes the aggregation buffer object T to Array[Byte] */
+  def serialize(buffer: T): Array[Byte]
+
+  /** De-serializes the serialized format Array[Byte], and produces 
aggregation buffer object T */
+  def deserialize(storageFormat: Array[Byte]): T
+
   final override def initialize(buffer: InternalRow): Unit = {
+    partial2ModeBuffer = buffer.copy()
+    partial2ModeBuffer(mutableAggBufferOffset) = 
createPartial2ModeAggregationBuffer()
 
 Review comment:
   So I went through Hive docs and asked a couple of people around; officially, 
hive does not mention anything about using two different aggregation buffers, 
the main point is to have some kind of distinction between different phases of 
Hive. 
   
   Consider a classic map-reduce process. There are two phases: map and reduce 
(sometimes an optional combine phase in between). The phases can run on 
different nodes. The state lives within a phase and does not cross the 
boundaries. The map phase corresponds to the "partial1" mode (init + iterate + 
terminate partial). The reduce phase corresponds to the "final" mode (init + 
merge + terminate). The combine phase corresponds to the "partial2" mode (init 
+ merge + terminate partial). The "complete" mode is a special shortcut to run 
the whole thing as a single phase (init + iterate + terminate). The bug here is 
about a state crossing the boundaries between the phases: initialized for one 
phase (mode), but then passed to a different phase. So by using different 
aggregation buffers, I am trying to encapsulate the corresponding state within 
a particular phase. The solution can also be modified to have a single 
aggregation buffer supporting states of different phases. 
   
   In my PR above, the assumption is that the Partial1 aggregation buffer 
supports phases PARTIAL1/COMPLETE and the Partial2 aggregation buffer supports 
phases PARTIAL2/FINAL. 
   
   I shall also paste a link to a good blog that explains the usage of 
aggregation buffers in a generic Hive UDAF : 
https://blog.dataiku.com/2013/05/01/a-complete-guide-to-writing-hive-udf 
   
   As this is also a kind of a design change problem, it is completely open to 
further discussions and improvements. My solution is just one of a kind 
solution and there are multiple solutions to achieve the same thing. However, 
as far as I can say, my solution is relatively cleaner and easier to understand 
and also it does not create a change of any manner in the way with which 
existing aggregation functions work with Spark SQL(does not break 
compatibility).

----------------------------------------------------------------
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:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to