HeartSaVioR commented on code in PR #60313:
URL: https://github.com/apache/spark/pull/60313#discussion_r4577242114
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
Thanks for checking it with that mutation. Fixed in
[2371eb43300](https://github.com/apache/spark/commit/2371eb43300b95f759efa00ab1931dd7bd7713a8).
The key now goes through a UDF that counts its calls, and the test waits until
row 3 has been read, then until the task waits for input, before it asserts.
Under your mutation it now fails. As no request can stay unfilled at the new
default, the test runs with `maxBatchRows` at 1000 and pins the limitation that
remains when the setting is raised: a request that is not full is held until
the batch ends, while a full request's output comes at once, with its cursor
closed.
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
Agreed. Done in
[2371eb43300](https://github.com/apache/spark/commit/2371eb43300b95f759efa00ab1931dd7bd7713a8).
The comment now says that whenever a batch takes one row, because the source
allows one parameter row or because of the new real-time mode default, every
batch stops full. So every partition's last batch takes this path: it caches
keys that nothing reads, and a semi or anti join whose residual reads a lookup
column reads every row of its key. Both are bounded, and the output is
unchanged. The description says so too.
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5
(`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR.
Done in
[2371eb43300](https://github.com/apache/spark/commit/2371eb43300b95f759efa00ab1931dd7bd7713a8),
as you suggest: `readBatch` computes `full` once, loops while `!full &&
hasInput`, and returns `endedInput = !full`.
--
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]