viirya commented on code in PR #60313:
URL: https://github.com/apache/spark/pull/60313#discussion_r4576853190
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -325,9 +332,9 @@ class ExternalLookupJoinEvaluatorFactory(
}
// Only a later batch of the partition reads what this one caches, so the
last batch caches
- // nothing. The partition knows whether input remains once the request is
sent, before its
- // results are read.
- private lazy val cacheWriter = if (!inputRemains()) None else {
+ // nothing. A last batch that stopped full is not known as the last, and
caches what no batch
Review Comment:
This is not limited to an input that happens to end at a full request. For a
connector whose `maxParameterRowsPerRequest` is 1, every batch stops full, so
the last row of every partition takes this path: a cache write that nothing
reads, and for a semi or anti join whose residual reads a lookup column,
reading every row of the key instead of stopping at the first match. It is
bounded and results are unaffected, but the comment and the PR description
should say so.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala:
##########
@@ -253,7 +259,8 @@ class ExternalLookupJoinEvaluatorFactory(
}
}
}
- StreamBatch(rows.toArray, keyEntries.values.toArray,
rowsThatCannotMatch.toArray)
+ val endedInput = !keyChanged && rows.length < maxBatchRows && bytes <
maxBatchBytes
Review Comment:
Nit: this repeats the three loop conditions, and the two must stay in sync.
Something like
```scala
def full = keyChanged || rows.length >= maxBatchRows || bytes >=
maxBatchBytes
while (!full && hasInput) { ... }
... endedInput = !full
```
keeps one copy.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ExternalLookupJoinSuite.scala:
##########
@@ -5137,28 +5744,164 @@ class ExternalLookupJoinRealTimeModeSuite extends
StreamRealTimeModeE2ESuiteBase
}
}
- test("real-time mode rejects external lookup join") {
- SimpleExternalLookupDataSource.resetCounters()
- val input = LowLatencyMemoryStream[Int](2)
- val left = input.toDF().toDF("id")
- val lookup =
spark.read.format(classOf[SimpleExternalLookupDataSource].getName).load()
- val joined = left.join(lookup, left("id") === lookup("id"))
- .select(concat(col("department"), lit("-"),
left("id").cast("string")).as("output"))
+ Seq("inner", "left_outer", "left_semi", "left_anti").foreach { joinType =>
+ test(s"real-time mode emits the output of a lookup join during the batch:
$joinType") {
+ val clock = useManualClock()
+ val input = LowLatencyMemoryStream.singlePartition[Int]
+ val query = startJoin(s"external_lookup_rtm_$joinType", joinType, input,
+ lookupTable(maxBatchSize = 2))
+ try {
+ // A request takes two stream rows, and its output comes once the
request is full, before
+ // the next stream row arrives. Each addition fills a request and
starts the next. Each
+ // full request has a key with lookup rows and one without, so that
every join type emits
+ // rows for it.
+ input.addData(1, 3, 2)
+ awaitOutputs(query, joinOutputs(joinType, 1, 3))
+ input.addData(4, 1)
+ awaitOutputs(query, joinOutputs(joinType, 1, 3, 2, 4))
+ input.addData(3, 5)
+ awaitOutputs(query, joinOutputs(joinType, 1, 3, 2, 4, 1, 3))
+ // The last request is not full, so the join sends it when the batch
ends.
+ endBatch(query, clock)
+ awaitOutputs(query, joinOutputs(joinType, 1, 3, 2, 4, 1, 3, 5))
+ } finally {
+ query.stop()
+ }
+ assert(query.exception.isEmpty)
+ }
+ }
- val query = runStreamingQuery("external_lookup_rtm", joined)
+ test("real-time mode caches lookup results within a batch, and starts each
batch empty") {
+ val clock = useManualClock()
+ val input = LowLatencyMemoryStream.singlePartition[Int]
+ val query = startJoin("external_lookup_rtm_cache", "left_outer", input,
+ lookupTable(maxBatchSize = 2))
+ def requestedKeys: Seq[Int] =
SimpleExternalLookupDataSource.requestedKeys.asScala.toSeq
try {
- eventually(timeout(60.seconds)) {
- checkError(
- exception =
query.exception.get.getCause.asInstanceOf[SparkIllegalArgumentException],
- condition =
"STREAMING_REAL_TIME_MODE.OPERATOR_OR_SINK_NOT_IN_ALLOWLIST",
- parameters = Map(
- "errorType" -> "operator",
- "message" ->
"org.apache.spark.sql.execution.joins.ExternalLookupJoinExec is"))
+ input.addData(1, 2, 3, 4, 1, 2, 5)
+ awaitOutputs(query, joinOutputs("left_outer", 1, 2, 3, 4, 1, 2))
+ // The keys of the third request are served from the cache.
+ assert(requestedKeys === Seq(1, 2, 3, 4))
+ val lookupJoin =
streamExecution(query).lastExecution.executedPlan.collectFirst {
+ case join: ExternalLookupJoinExec => join
+ }.get
+ endBatch(query, clock)
+ assert(requestedKeys === Seq(1, 2, 3, 4, 5))
+ // The metrics reach the driver when the tasks of the batch end.
+ assert(lookupJoin.metrics("numLookupRequests").value === 3)
+ assert(lookupJoin.metrics("numCacheHits").value === 2)
+ // The next batch runs new tasks, whose caches start empty.
+ input.addData(1, 2, 3)
+ awaitOutputs(query, joinOutputs("left_outer", 1, 2, 3, 4, 1, 2, 5, 1, 2))
+ assert(requestedKeys === Seq(1, 2, 3, 4, 5, 1, 2))
+ } finally {
+ query.stop()
+ }
+ assert(query.exception.isEmpty)
+ }
+
+ test("real-time mode runs a streaming aggregation after a lookup join") {
+ withSQLConf(SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+ val clock = useManualClock()
+ val input = LowLatencyMemoryStream.singlePartition[Int]
+ val stream = input.toDF().toDF("id")
+ val lookup = lookupTable(maxBatchSize = 2)
+ val counts = stream.join(lookup, stream("id") === lookup("id"))
+ .groupBy(lookup("department")).count()
+ .select(concat(col("department"), lit(":"),
col("count").cast("string")))
+ val query = runStreamingQuery("external_lookup_rtm_aggregation", counts)
+ try {
+ // The aggregation updates the count of a department for each joined
row.
+ input.addData(1, 2, 1, 2, 1)
+ val duringBatch = Seq("engineering:1", "research:1", "sales:1",
+ "engineering:2", "research:2", "sales:2")
+ awaitOutputs(query, duringBatch)
+ val shuffles =
streamExecution(query).lastExecution.executedPlan.collect {
+ case shuffle: ShuffleExchangeExec => shuffle.pipelined
+ }
+ assert(shuffles === Seq(true))
+ endBatch(query, clock)
+ awaitOutputs(query, duringBatch ++ Seq("engineering:3", "research:3"))
+ } finally {
+ query.stop()
}
+ assert(query.exception.isEmpty)
+ }
+ }
+
+ test("real-time mode runs a lookup join after a shuffle of the stream") {
+ val clock = useManualClock()
+ val input = LowLatencyMemoryStream.singlePartition[Int]
+ val stream = input.toDF().toDF("id").repartition(1, col("id"))
+ val lookup = lookupTable(maxBatchSize = 2)
+ val joined = stream.join(lookup, stream("id") === lookup("id"),
"left_outer")
+ .select(concat(stream("id").cast("string"), lit(":"),
+ coalesce(lookup("department"), lit("null"))))
+ val query = runStreamingQuery("external_lookup_rtm_shuffled_stream",
joined)
+ try {
+ input.addData(1, 2, 3, 4, 5)
+ awaitOutputs(query, joinOutputs("left_outer", 1, 2, 3, 4))
+ val lookupJoin =
streamExecution(query).lastExecution.executedPlan.collectFirst {
+ case join: ExternalLookupJoinExec => join
+ }.get
+ assert(lookupJoin.collect { case shuffle: ShuffleExchangeExec =>
shuffle.pipelined } ===
+ Seq(true))
+ endBatch(query, clock)
+ awaitOutputs(query, joinOutputs("left_outer", 1, 2, 3, 4, 5))
} finally {
query.stop()
}
- assert(SimpleExternalLookupDataSource.readerCount.get() === 0)
+ assert(query.exception.isEmpty)
+ }
+
+ test("stopping a real-time query during a lookup request closes the reader")
{
+ useManualClock()
+ val input = LowLatencyMemoryStream.singlePartition[Int]
+ val query = startJoin("external_lookup_rtm_stop", "inner", input,
+ lookupTable(maxBatchSize = 1, "responseDelayMillis" -> "60000"))
+ try {
+ input.addData(1)
+
awaitQuery(query)(SimpleExternalLookupDataSource.requestStarted.get().getCount
== 0)
+ } finally {
+ query.stop()
+ }
+ assert(query.exception.isEmpty)
+ eventually(timeout(60.seconds)) {
+ assert(SimpleExternalLookupDataSource.closeCount.get() === 1)
+ }
+ assert(SimpleExternalLookupDataSource.readerCount.get() === 1)
+ // The stop interrupted the request before it returned.
+ assert(SimpleExternalLookupDataSource.requestCount.get() === 0)
+ }
+
+ // A known limitation: the join has no time bound on a request. It sends a
request once the
+ // request is full or the batch ends. The output of a full request comes at
once, and the join
+ // closes the request's cursor before it waits for the next stream row.
+ test("real-time mode holds a lookup request that is not full until the batch
ends") {
+ val clock = useManualClock()
+ val input = LowLatencyMemoryStream.singlePartition[Int]
+ val query = startJoin("external_lookup_rtm_partial_request", "left_outer",
input,
+ lookupTable(maxBatchSize = 2))
+ try {
+ input.addData(1, 2)
+ // The request is full, so the join sends it and emits its output with
no further row.
+ awaitOutputs(query, joinOutputs("left_outer", 1, 2))
+ assert(SimpleExternalLookupDataSource.requestCount.get() === 1)
+ // The task then waits for the next stream row, with the request's
cursor closed.
+ awaitTaskWaitingForInput(query)
+ assert(SimpleExternalLookupDataSource.closeEvents.asScala.toSeq ===
Seq("cursor"))
+ input.addData(3)
+ // The request of key 3 is not full, so the join neither sends it nor
emits its row.
+ awaitTaskWaitingForInput(query)
Review Comment:
This wait returns immediately: the task is still parked in `nextWithTimeout`
from the previous wait (it polls every 10 ms), so the two assertions below run
before row 3 is read. I checked by making the join send a non-full request as
soon as its row arrives (cap of one row after the first batch): this test still
passes. So it does not pin the limitation as the description says.
Could it wait until row 3 has actually been consumed before asserting, e.g.
on the source's offset or a consumed-row counter?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]