Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
eabb65b
WIP nothing worked, just recording the progress
HeartSaVioR Sep 4, 2018
c3076d2
WIP not working yet... lots of implementations needed
HeartSaVioR Sep 6, 2018
9d59c7a
WIP Finished implementing UpdatingSessionIterator
HeartSaVioR Sep 6, 2018
b38f2b9
WIP add verification on precondition "rows in iterator are sorted by …
HeartSaVioR Sep 7, 2018
668c1f5
Rename SymmetricHashJoinStateManager to MultiValuesStateManager
HeartSaVioR Sep 8, 2018
9f63a3c
Move package of UpdatingSessionIterator
HeartSaVioR Sep 8, 2018
5d17ac8
WIP add MergingSortWithMultiValuesStateIterator, now integrating with…
HeartSaVioR Sep 10, 2018
ec33265
WIP the first version of working one! Still have lots of TODOs and FI…
HeartSaVioR Sep 13, 2018
8b210d5
Add more explanations
HeartSaVioR Sep 13, 2018
7255bca
Silly bugfix & block session window for batch query as of now
HeartSaVioR Sep 13, 2018
7b57fe5
More works: majorly split out updating session to individual physical…
HeartSaVioR Sep 13, 2018
969859b
Fix a silly bug and also add check for session window against batch q…
HeartSaVioR Sep 13, 2018
f5ecbdd
WIP Fixed eviction on update mode
HeartSaVioR Sep 13, 2018
b180772
WIP found root reason of broken UT... fixed it
HeartSaVioR Sep 13, 2018
0a2d731
WIP remove printing "explain" on UTs
HeartSaVioR Sep 13, 2018
6ee901e
WIP address session to batch query (+ python) as well... not having t…
HeartSaVioR Sep 13, 2018
395606b
WIP add more test on session batch query
HeartSaVioR Sep 13, 2018
f6bb34d
WIP add UT for sessions with keys overlapped
HeartSaVioR Sep 14, 2018
22fffd2
WIP refactor a bit
HeartSaVioR Sep 14, 2018
847f69e
WIP add more FIXMEs for javadoc, and remove invalid FIXMEs
HeartSaVioR Sep 14, 2018
104df13
WIP Repackage & remove unnecessary field
HeartSaVioR Sep 17, 2018
8108fc5
WIP addressed UPDATE mode, but doesn't look like performant
HeartSaVioR Sep 17, 2018
35c8fef
WIP remove FIXME since it is not relevant
HeartSaVioR Sep 17, 2018
6b1d1e0
WIP update numOutputRows for Append mode
HeartSaVioR Sep 17, 2018
86b3060
WIP apply aggregations when merging sessions
HeartSaVioR Sep 18, 2018
f7c2deb
WIP simplify the code a bit
HeartSaVioR Sep 18, 2018
a81616b
WIP address batch distinct query for sessionization
HeartSaVioR Sep 18, 2018
013785d
WIP remove debug statements for test code
HeartSaVioR Sep 18, 2018
37fffef
WIP remove debug informations
HeartSaVioR Sep 18, 2018
df95e72
WIP port Sessionization example to UT of session window
HeartSaVioR Sep 18, 2018
16d6421
WIP remove unnecessary thing
HeartSaVioR Sep 18, 2018
dc43300
WIP fix all the issues with sessionization example UTs
HeartSaVioR Sep 19, 2018
3637f60
WIP apply merging session in each partition before shuffling
HeartSaVioR Sep 19, 2018
0d53831
Fix scala checkstyle
HeartSaVioR Sep 20, 2018
a781400
Fix python style check
HeartSaVioR Sep 20, 2018
918dad2
WIP add complete mode, fix tricky bugs, apply ExternalAppendOnlyUnsaf…
HeartSaVioR Oct 8, 2018
fd6377b
WIP add "session" function to exclude list for description
HeartSaVioR Oct 8, 2018
e029e12
WIP rename function & column name "session" to "session_window"
HeartSaVioR Oct 10, 2018
a2fc652
WIP reducing unnecessary codegen which seriously harmed performance
HeartSaVioR Oct 15, 2018
2dc413b
WIP reduce codegen once again for MergingSessionsIterator
HeartSaVioR Oct 15, 2018
4dd0e89
WIP optimize a bit more on codegen...
HeartSaVioR Oct 15, 2018
cf52044
WIP make the feature "merge session in local partition" optional
HeartSaVioR Oct 15, 2018
5c74609
WIP add "session_window" to exclude list
HeartSaVioR Oct 17, 2018
fb6c59f
WIP Enable versioning of session window state format
HeartSaVioR Oct 18, 2018
dd29af2
WIP some correction in comment
HeartSaVioR Oct 19, 2018
1f6e496
WIP cover all the cases for session window in UTs
HeartSaVioR Oct 20, 2018
0673b6e
WIP Add Linked List data structure for storing session windows
HeartSaVioR Oct 23, 2018
4698f6d
WIP add SessionWindowLinkedListStateStoreRDD
HeartSaVioR Oct 23, 2018
5c67f72
WIP add more functionalities to SessionWindowLinkedListState
HeartSaVioR Oct 24, 2018
7bb0060
WIP it works but a bit suboptimal
HeartSaVioR Oct 25, 2018
35c9712
WIP optimized!
HeartSaVioR Oct 25, 2018
ede078a
WIP remove requirement on sort, add UT to test linked list state with…
HeartSaVioR Oct 27, 2018
f8e8ff6
WIP add code to print out information when task crashes with dangling…
HeartSaVioR Oct 27, 2018
b05abc7
WIP fixed the issue with benchmark run
HeartSaVioR Oct 29, 2018
17570f2
WIP optimize a bit on storing new sessions
HeartSaVioR Oct 30, 2018
958de31
WIP Fixed critical bug which tasks don't respect preference on state …
HeartSaVioR Oct 31, 2018
ee67bca
WIP Fix critical perf. issue: remove codegen on generating session ro…
HeartSaVioR Nov 1, 2018
8a0331e
WIP Rolling back unnecessary changes
HeartSaVioR Nov 2, 2018
b6ccecd
WIP Apply removing codegen to UpdatingSessionIterator as well
HeartSaVioR Nov 2, 2018
75c7611
WIP remove state version for now: it will be reintroduced when actual…
HeartSaVioR Nov 2, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
WIP it works but a bit suboptimal
  • Loading branch information
HeartSaVioR committed Oct 25, 2018
commit 7bb0060f62331301ad6eaf3a6280fa196828f16c
Original file line number Diff line number Diff line change
@@ -0,0 +1,312 @@
/*
* 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.streaming

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, UnsafeProjection, UnsafeRow}
import org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
import org.apache.spark.sql.catalyst.util.TypeUtils
import org.apache.spark.sql.execution.streaming.state.SessionWindowLinkedListState

// FIXME: javadoc!!
class MergingSortWithSessionWindowLinkedListStateIterator(
iter: Iterator[InternalRow],
state: SessionWindowLinkedListState,
groupWithoutSessionExpressions: Seq[Attribute],
sessionExpression: Attribute,
keysProjection: UnsafeProjection,
sessionProjection: UnsafeProjection,
inputSchema: Seq[Attribute]) extends Iterator[InternalRow] {

def this(
iter: Iterator[InternalRow],
state: SessionWindowLinkedListState,
groupWithoutSessionExpressions: Seq[Attribute],
sessionExpression: Attribute,
inputSchema: Seq[Attribute]) {
this(iter, state, groupWithoutSessionExpressions, sessionExpression,
GenerateUnsafeProjection.generate(groupWithoutSessionExpressions, inputSchema),
GenerateUnsafeProjection.generate(Seq(sessionExpression), inputSchema),
inputSchema)
}

private case class SessionRowInformation(keys: UnsafeRow, sessionStart: Long, sessionEnd: Long,
row: InternalRow)

private object SessionRowInformation {
def of(row: InternalRow): SessionRowInformation = {
val keys = keysProjection(row).copy()
val session = sessionProjection(row).copy()
val sessionRow = session.getStruct(0, 2)
val sessionStart = sessionRow.getLong(0)
val sessionEnd = sessionRow.getLong(1)

SessionRowInformation(keys, sessionStart, sessionEnd, row)
}
}

private def findSessionPointerEnclosingEvent(row: SessionRowInformation,
startPointer: Option[Long])
: Option[(Option[Long], Option[Long])] = {
val startOption = startPointer match {
case None => state.getFirstSessionStart(currentRow.keys)
case _ => startPointer
}

startOption match {
// empty list
case None => None
case Some(start) =>
var currOption: Option[Long] = Some(start)

var enclosingSessions: Option[(Option[Long], Option[Long])] = None
while (enclosingSessions.isEmpty && currOption.isDefined) {
val curr = currOption.get
val newPrev = state.getPrevSessionStart(currentRow.keys, curr)
val newNext = state.getNextSessionStart(currentRow.keys, curr)

val isEventEnclosed = newPrev match {
case Some(prev) =>
prev <= currentRow.sessionStart && currentRow.sessionStart <= curr
case None => currentRow.sessionStart <= curr
}

val willNotBeEnclosed = newPrev match {
case Some(prev) => prev > currentRow.sessionStart
case None => false
}

if (isEventEnclosed) {
enclosingSessions = Some((newPrev, currOption))
} else if (willNotBeEnclosed) {
enclosingSessions = Some((None, None))
} else if (newNext.isEmpty) {
// curr is the last session in state
if (currentRow.sessionStart >= curr) {
enclosingSessions = Some((currOption, None))
} else {
enclosingSessions = Some((None, None))
}
}

currOption = newNext
}

// enclosingSessions should not be None unless list is empty
enclosingSessions
}
}

private def isSessionsOverlap(s1: SessionRowInformation, s2: SessionRowInformation): Boolean = {
(s1.sessionStart >= s2.sessionStart && s1.sessionStart <= s2.sessionEnd) ||
(s2.sessionStart >= s1.sessionStart && s2.sessionStart <= s1.sessionEnd)
}

private var lastKey: UnsafeRow = _
private var currentRow: SessionRowInformation = _

private val stateRowsToEmit: scala.collection.mutable.ListBuffer[SessionRowInformation] =
new scala.collection.mutable.ListBuffer[SessionRowInformation]()
private val stateRowsChecked: scala.collection.mutable.HashSet[SessionRowInformation] =
new scala.collection.mutable.HashSet[SessionRowInformation]()

private var lastEmittedStateSessionKey: UnsafeRow = _
private var lastEmittedStateSessionStartOption: Option[Long] = None
private var stateRowWaitForEmit: SessionRowInformation = _

private val keyOrdering: Ordering[UnsafeRow] = TypeUtils.getInterpretedOrdering(
groupWithoutSessionExpressions.toStructType).asInstanceOf[Ordering[UnsafeRow]]

override def hasNext: Boolean = {
currentRow != null || iter.hasNext || stateRowsToEmit.nonEmpty
}

override def next(): InternalRow = {
if (currentRow == null) {
mayFillCurrentRow()
}

if (currentRow == null && stateRowsToEmit.isEmpty) {
throw new IllegalStateException("No Row to provide in next() which should not happen!")
}

// early return on input rows vs state row waiting for emitting
val returnCurrentRow = if (currentRow == null) {
false
} else if (stateRowsToEmit.isEmpty) {
true
} else {
// compare between current row and state row waiting for emitting
val stateRow = stateRowsToEmit.head
if (!keyOrdering.equiv(currentRow.keys, stateRow.keys)) {
// state row cannot advance to row in input, so state row should be lower
false
} else {
currentRow.sessionStart < stateRow.sessionStart
}
}

// if state row should be emitted, do emit
if (!returnCurrentRow) {
val stateRow = stateRowsToEmit.head
stateRowsToEmit.remove(0)
return stateRow.row
}

if (lastKey == null || !keyOrdering.equiv(lastKey, currentRow.keys)) {
// new key
stateRowsToEmit.clear()
stateRowsChecked.clear()
lastKey = currentRow.keys
}

// FIXME: how to provide start pointer to avoid reiterating?
val stateSessionsEnclosingCurrentRow = findSessionPointerEnclosingEvent(currentRow,
startPointer = None)

stateSessionsEnclosingCurrentRow match {
case None =>
case Some(x) =>
x._1 match {
case Some(prev) =>
val prevSession = SessionRowInformation.of(state.get(currentRow.keys, prev))

if (!stateRowsChecked.contains(prevSession)) {
// based on definition of session window and the fact that events are sorted,
// if the state session is not matched to this event, it will not be matched with
// later events as well
stateRowsChecked += prevSession

if (isSessionsOverlap(currentRow, prevSession)) {
stateRowsToEmit += prevSession
}
}

case None =>
}

x._2 match {
case Some(next) =>
val nextSession = SessionRowInformation.of(state.get(currentRow.keys, next))

if (!stateRowsChecked.contains(nextSession)) {
// next session could be matched to latter events even it doesn't match to
// current event, so unless it is added to rows to emit, don't add to checked set
if (isSessionsOverlap(currentRow, nextSession)) {
stateRowsToEmit += nextSession
stateRowsChecked += nextSession
}
}

case None =>
}
}

if (stateRowsToEmit.isEmpty) {
emitCurrentRow()
} else if (currentRow.sessionStart < stateRowsToEmit.head.sessionStart) {
emitCurrentRow()
} else {
val stateRow = stateRowsToEmit.head
stateRowsToEmit.remove(0)
stateRow.row
}
}

private def emitCurrentRow(): InternalRow = {
val ret = currentRow
currentRow = null
ret.row
}

private def emitStateRowForWaiting(): InternalRow = {
val ret = stateRowWaitForEmit
stateRowWaitForEmit = null
recordStateRowToEmit(ret)
ret.row
}

private def recordStateRowToEmit(stateRow: SessionRowInformation) = {
lastEmittedStateSessionStartOption = Some(stateRow.sessionStart)
lastEmittedStateSessionKey = stateRow.keys
}

private def mayFillCurrentRow(): Unit = {
if (iter.hasNext) {
currentRow = SessionRowInformation.of(iter.next())
}
}

private def currentRowIsSmallerThanWaitingStateRow(): Boolean = {
// compare between current row and state row waiting for emitting
if (!keyOrdering.equiv(currentRow.keys, stateRowWaitForEmit.keys)) {
// state row cannot advance to row in input, so state row should be lower
false
} else {
currentRow.sessionStart < stateRowWaitForEmit.sessionStart
}
}

private def getEnclosingStatesForEvent(row: SessionRowInformation)
: (Option[SessionRowInformation], Option[SessionRowInformation]) = {
// find two state sessions wrapping current row

if (lastEmittedStateSessionKey != null) {
mayInvalidateLastEmittedStateSession()
}

val nextStateSessionStart: Option[Long] = lastEmittedStateSessionStartOption match {
case Some(lastEmittedStateSessionStart) =>
state.findFirstSessionStartEnsurePredicate(currentRow.keys,
_ >= currentRow.sessionEnd, lastEmittedStateSessionStart)
case None =>
state.findFirstSessionStartEnsurePredicate(currentRow.keys,
_ >= currentRow.sessionEnd)
}

val prevStateSessionStart: Option[Long] = nextStateSessionStart match {
case Some(next) => state.getPrevSessionStart(currentRow.keys, next)
case None => state.getLastSessionStart(currentRow.keys)
}

// only return sessions which overlap with current row
val pSession = if (prevStateSessionStart.isDefined) {
Some(SessionRowInformation.of(state.get(currentRow.keys, prevStateSessionStart.get)))
} else {
None
}

val nSession = if (nextStateSessionStart.isDefined) {
Some(SessionRowInformation.of(state.get(currentRow.keys, nextStateSessionStart.get)))
} else {
None
}

(pSession, nSession)
}

private def mayInvalidateLastEmittedStateSession(): Unit = {
// invalidate last emitted state session key as well as session start
// if keys are changed
if (!keyOrdering.equiv(lastEmittedStateSessionKey, currentRow.keys)) {
lastEmittedStateSessionKey = null
lastEmittedStateSessionStartOption = None
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,32 @@ class SessionWindowLinkedListState(
pointers._2
}

// FIXME: cover with test cases
def getFirstSessionStart(key: UnsafeRow): Option[Long] = {
keyToHeadSessionStartStore.get(key)
}

// FIXME: cover with test cases
def getLastSessionStart(key: UnsafeRow): Option[Long] = {
getFirstSessionStart(key) match {
case Some(start) => getLastSessionStart(key, start)
case None => None
}
}

// FIXME: cover with test cases
def getLastSessionStart(key: UnsafeRow, startIndex: Long): Option[Long] = {
val pointers = keyAndSessionStartToPointerStore.get(key, startIndex)
assertValidPointer(pointers)

var lastSessionStart = startIndex
while (getNextSessionStart(key, lastSessionStart).isDefined) {
lastSessionStart = getNextSessionStart(key, lastSessionStart).get
}

Some(lastSessionStart)
}

def remove(key: UnsafeRow, sessionStart: Long): Unit = {
val targetPointer = keyAndSessionStartToPointerStore.get(key, sessionStart)
assertValidPointer(targetPointer)
Expand Down Expand Up @@ -441,7 +467,7 @@ class SessionWindowLinkedListState(

private def assertValidPointer(targetPointer: (Option[Long], Option[Long])): Unit = {
if (targetPointer == null) {
throw new IllegalArgumentException("Update must be against existing session start.")
throw new IllegalArgumentException("Invalid pointer is provided.")
}
}

Expand Down
Loading