spark-test commented on code in PR #60068:
URL: https://github.com/apache/spark/pull/60068#discussion_r4596229562


##########
sql/core/src/main/scala/org/apache/spark/sql/classic/StreamingQueryManager.scala:
##########
@@ -299,7 +302,7 @@ class StreamingQueryManager private[sql] (
       case _: ContinuousTrigger => (sparkSession, dataStreamWritePlan)
       case _ if recoverFromCheckpointLocation &&
           hasPersistentCheckpointLocation &&
-          hasExceptWithStreamingLeft =>
+          (hasExceptWithStreamingLeft || hasStatefulJoin) =>

Review Comment:
   **Non-blocking (P2):** This routes every stateful-join query that recovers 
from a persistent checkpoint through the early read that used to serve only 
streaming EXCEPT, but nothing at this analysis boundary reads 
`spark.sql.streaming.join.preserveEventTimeColumns.enabled`. Its only reader is 
`ColumnPruning`, which does not run in `executePlan(...).analyzed`, and neither 
`ResolveWriteToStream` nor `UnsupportedOperationChecker` consults it. The query 
is then built with the original `sparkSession`, whose stream session gets the 
recorded value from the offset log: `populateStartOffsets` applies it through 
`setSessionConf`, and both `startupConf` helpers through 
`setConfWithoutLogging`.
   
   So every start of such a query now resolves the checkpoint and lists 
`offsets/` inside `start()`. Every restart also reads the latest entry and 
clones the session, which copies session artifacts and re-registers them with 
the SparkContext, without changing the analyzed plan or the value any 
optimization uses. That includes range, chained and legacy-checkpoint joins the 
feature never changes. An unreadable or newer-version latest offset file now 
makes `start()` throw, instead of failing the started query with a 
`StreamingQueryException` and listener events. The rewritten comment ("when 
they affect analysis") also misleads maintainers, and `getOrElse(false)` 
repeats the missing-key default from `relevantSQLConfDefaultValues`. Dropping 
`hasStatefulJoin` and its block, and restoring the EXCEPT-only branch and its 
comment, leaves every recorded value as it is.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60068#issuecomment-6938825273).
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1644,14 +1668,35 @@ object ColumnPruning extends Rule[LogicalPlan] {
     // for all other logical plans that inherits the output from it's children
     // Project over project is handled by the first case, skip it here.
     case p @ Project(_, child) if !child.isInstanceOf[Project] =>
-      val required = child.references ++ p.references
+      val required = requiredInputReferences(child, retainJoinEventTime) ++ 
p.references
       if (!child.inputSet.subsetOf(required)) {
         val newChildren = child.children.map(c => prunedChild(c, required))
         p.copy(child = child.withNewChildren(newChildren))
       } else {
         p
       }
-  })
+    })
+  }
+
+  private def requiredInputReferences(
+      plan: LogicalPlan,
+      retainJoinEventTime: Boolean): AttributeSet = {
+    val eventTimeAttributes = plan match {
+      case join: Join if join.isStateful && retainJoinEventTime =>
+        join.children.flatMap { child =>
+          val eventTimeColumns = child.output.filter(
+            _.metadata.contains(EventTimeWatermark.delayKey))
+          if (eventTimeColumns.map(_.exprId).distinct.size == 1 &&
+              eventTimeColumns.head.dataType == TimestampType) {
+            eventTimeColumns
+          } else {
+            Nil
+          }
+        }
+      case _ => Nil
+    }
+    plan.references ++ AttributeSet(eventTimeAttributes)

Review Comment:
   **Nit (P3):** `AttributeSet.++` always builds a new set, so this copies 
`plan.references` even when `eventTimeAttributes` is empty. The helper now 
backs the generic `Project` case, whose result is unioned with `p.references` 
again, and the left-existence join case, which used to pass the cached 
`j.references`. So every query, batch queries included, pays an extra 
reference-set copy for each such node on every ColumnPruning pass. Separately, 
for any streaming plan with the setting on, `apply` walks the whole plan with 
`plan.exists` and `plan.collect` before the transform even when there is no 
join, for example a streaming aggregation, on every pass of every micro-batch. 
Only optimizer time is affected; optimized plans stay the same. Return 
`plan.references` unchanged unless the node is a stateful join with columns to 
add, and compute the gate lazily, only when the transform reaches a stateful 
join. The gate reads the same input `plan`, so its decision is identical, and 
the extra wo
 rk goes with no trade-off.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60068#discussion_r4575697043).
   
   **Verification:**
   - **Regression:** The retention and legacy-fallback plan comparisons for 
stream-stream, left-semi, batch, stream-static, chained, residual-predicate, 
CTE, ambiguous and window-valued inputs produce the same optimized plans as 
before the change.
   - **Inspection:** The retention gate is evaluated at most once per 
ColumnPruning call and only when the transform meets a stateful join, and a 
reference set is copied only when event-time columns are added to it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1514,8 +1514,32 @@ object PushProjectionThroughUnion extends 
Rule[LogicalPlan] {
  */
 object ColumnPruning extends Rule[LogicalPlan] {
 
-  def apply(plan: LogicalPlan): LogicalPlan = removeProjectBeforeFilter(
-    plan.transformWithPruning(AlwaysProcess.fn, ruleId) {
+  def apply(plan: LogicalPlan): LogicalPlan = {
+    val retainJoinEventTime =
+      conf.getConf(SQLConf.STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS) &&
+        plan.isStreaming &&
+        !plan.exists {
+          case _: WithCTE | _: CTERelationRef => true
+          case _ => false
+        } &&
+        (plan.collect { case p if p.isStateful => p } match {
+          case Seq(join: Join) =>
+            ExtractEquiJoinKeys.unapply(join).exists(_._4.isEmpty) &&
+              join.children.forall { child =>
+                val columns = child.output.filter(
+                  _.metadata.contains(EventTimeWatermark.delayKey))
+                columns.isEmpty ||
+                  (columns.map(_.exprId).distinct.size == 1 &&
+                    columns.head.dataType == TimestampType)
+              }
+          case _ => false
+        })
+
+    // Retain event time only for one equality join with unambiguous timestamp 
watermarks.
+    // Other shapes keep legacy pruning until their watermark and state 
eviction behavior can be

Review Comment:
   **Nit (P3):** This says the excluded shapes keep legacy pruning "until" they 
can be handled, which reads as an invitation to widen the gate later. But a 
recorded `true` does not record which plans qualified. A query whose join feeds 
a streaming aggregation starts on this change, records `true`, and stores join 
rows without the timestamp. If a follow-up widens the gate to such plans under 
the same recorded value, that checkpoint keeps the timestamp on restart, the 
join's value schema gains a column, and the state schema check rejects the 
restart. Narrowing the gate, or an optimizer change that moves predicates into 
or out of the join condition, breaks eligible checkpoints the same way. Please 
add a short warning here: changing which plans qualify, directly or through the 
rules that shape the plan this gate sees, needs a separately pinned mode or 
version, or a state migration.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60068#issuecomment-6938825273).
   
   See **Shared repair plan 2** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4294,6 +4294,19 @@ object SQLConf {
     .booleanConf
     .createWithDefault(true)
 
+  val STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS =
+    buildConf("spark.sql.streaming.join.preserveEventTimeColumns.enabled")
+      .internal()
+      .doc("When true, column pruning preserves an unambiguous watermark 
timestamp in each " +

Review Comment:
   **Nit (P3):** The doc says column pruning preserves the timestamp "in each 
stream-stream join input", but `ColumnPruning` keeps it only for one shape. The 
plan must be streaming with no `WithCTE` or `CTERelationRef` node, its single 
stateful operator must be a stream-stream join that `ExtractEquiJoinKeys` 
splits with no residual condition, and each input must have at most one 
`TimestampType` watermark column. Range joins, chained joins, a join feeding a 
streaming aggregation and a join inside a materialized CTE keep legacy pruning 
under `true`, as this PR's own fallback tests assert, yet every new query 
records `true`. This internal setting is pinned into every checkpoint, so its 
doc is where a reader learns what a recorded `true` means. It should name the 
supported shape and say that other queries record the value but keep the 
previous pruning.
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/OffsetSeqLogSuite.scala:
##########
@@ -38,6 +38,47 @@ import org.apache.spark.util.{SerializableConfiguration, 
Utils}
 class OffsetSeqLogSuite extends SharedSparkSession {
   import testImplicits._
 
+  test("SPARK-60850: old checkpoints disable join event-time retention") {
+    val entry = SQLConf.STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS
+    val (_, offsets) = readFromResource("offset-log-version-2.1.0")
+    val metadata = offsets.metadataOpt.get
+    assert(!metadata.conf.contains(entry.key))
+    val restored = new SQLConf
+    val startup = new SQLConf
+    Seq(restored, startup).foreach(_.setConf(entry, true))
+
+    OffsetSeqMetadata.setSessionConf(metadata, restored)
+    OffsetSeqMetadata.setConfWithoutLogging(metadata, startup)
+
+    assert(!restored.getConf(entry))
+    assert(!startup.getConf(entry))
+  }
+
+  test("SPARK-60850: new checkpoints pin join event-time retention across 
restarts") {

Review Comment:
   **Nit (P3):** This test, like every other new test, sets the value 
explicitly, through `withSQLConf`, `StartStream`'s `additionalConfs`, or 
hand-built metadata. So nothing checks the value a new checkpoint records when 
the session leaves it unset. Changing `createWithDefault(true)` to `false` 
would turn retention off for every new query in the supported shape and still 
pass every test, and the existing join suites pass with either value. Each 
sibling pinned setting has that check in this suite, for example "streaming 
EXCEPT compatibility is disabled for new checkpoints", "SPARK-60632: regex 
pattern cost estimate is version 1 for new checkpoints" and "Row checksum 
disabled by default". A one-line case asserting that `OffsetSeqMetadata(0, 0, 
spark.conf)` records `true` closes the gap.
   
   **Verification:**
   - **Behavior:** Offset-log metadata built from a session that leaves the 
join retention setting unset records true, and the case fails if the setting's 
default changes.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ColumnPruningSuite.scala:
##########
@@ -432,6 +432,195 @@ class ColumnPruningSuite extends PlanTest {
     comparePlans(Optimize.execute(query), expected)
   }
 
+  private def watermarkedJoinInputs(): (LocalRelation, LocalRelation) = {
+    val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey, 
1000L).build()
+    val left = LocalRelation(
+      $"leftKey".int,
+      AttributeReference("leftTime", TimestampType, metadata = metadata)(),
+      $"leftExtra".int).copy(isStreaming = true)
+    val right = LocalRelation(
+      $"rightKey".int,
+      AttributeReference("rightTime", TimestampType, metadata = metadata)(),
+      $"rightExtra".int).copy(isStreaming = true)
+    (left, right)
+  }
+
+  test("SPARK-60850: stream-stream join retains event time during column 
pruning") {
+    val (left, right) = watermarkedJoinInputs()
+    val join = Join(left, right, Inner,
+      Some(left.output.head === right.output.head), JoinHint.NONE)
+    val query = Project(Seq(left.output.head), join)
+
+    Seq(false, true).foreach { enabled =>
+      withSQLConf(SQLConf.STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS.key -> 
enabled.toString) {
+        val kept = if (enabled) 2 else 1
+        val expected = Project(Seq(left.output.head), join.copy(
+          left = Project(left.output.take(kept), left),
+          right = Project(right.output.take(kept), right)))
+        comparePlans(Optimize.execute(query), expected)
+        
assert(!join.references.exists(_.metadata.contains(EventTimeWatermark.delayKey)))
+      }
+    }
+  }
+
+  test("SPARK-60850: left-semi right-input pruning retains event time") {
+    val (left, right) = watermarkedJoinInputs()
+    val join = Join(left, right, LeftSemi,
+      Some(left.output.head === right.output.head), JoinHint.NONE)
+    Seq(false, true).foreach { enabled =>
+      withSQLConf(SQLConf.STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS.key -> 
enabled.toString) {
+        val kept = if (enabled) 2 else 1
+        comparePlans(Optimize.execute(join),
+          join.copy(right = Project(right.output.take(kept), right)))
+      }
+    }
+  }
+
+  test("SPARK-60850: batch and stream-static joins keep their original 
pruning") {
+    val (left, right) = watermarkedJoinInputs()
+    withSQLConf(SQLConf.STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS.key -> 
"true") {
+      Seq((false, false), (true, false), (false, true)).foreach {
+        case (leftStreaming, rightStreaming) =>
+          val leftInput = left.copy(isStreaming = leftStreaming)
+          val rightInput = right.copy(isStreaming = rightStreaming)
+          val join = Join(leftInput, rightInput, Inner,
+            Some(left.output.head === right.output.head), JoinHint.NONE)
+          val query = Project(Seq(left.output.head), join)
+          val expected = Project(Seq(left.output.head), join.copy(
+            left = Project(left.output.take(1), leftInput),
+            right = Project(right.output.take(1), rightInput)))
+          comparePlans(Optimize.execute(query), expected)
+      }
+    }
+  }
+
+  test("SPARK-60850: actual event-time references are retained in either 
mode") {
+    val (left, right) = watermarkedJoinInputs()
+    val equality = left.output.head === right.output.head
+    val condition = equality && (left.output(1) > right.output(1))
+    Seq(false, true).foreach { enabled =>
+      withSQLConf(SQLConf.STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS.key -> 
enabled.toString) {
+        Seq(
+          (Some(condition), Seq(left.output.head)),
+          (Some(equality), Seq(left.output(1), right.output(1)))).foreach {
+          case (joinCondition, output) =>
+            val join = Join(left, right, Inner, joinCondition, JoinHint.NONE)
+            val expected = Project(output, join.copy(
+              left = Project(left.output.take(2), left),
+              right = Project(right.output.take(2), right)))
+            comparePlans(Optimize.execute(Project(output, join)), expected)
+        }
+      }
+    }
+  }
+
+  test("SPARK-60850: event-time aliases survive repeated column pruning") {
+    val (left, right) = watermarkedJoinInputs()
+    val aliased = Project(Seq(left.output.head, Alias(left.output(1), 
"aliasedTime")(),
+      left.output(2)), left)
+    val join = Join(aliased, right, Inner,
+      Some(left.output.head === right.output.head), JoinHint.NONE)
+    withSQLConf(SQLConf.STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS.key -> 
"true") {
+      val optimized = Optimize.execute(Project(Seq(left.output.head), join))
+      val optimizedJoin = optimized.collectFirst { case join: Join => join 
}.get
+      assert(optimizedJoin.left.output.map(_.name) == Seq("leftKey", 
"aliasedTime"))
+      assert(optimizedJoin.right.output.map(_.name) == Seq("rightKey", 
"rightTime"))
+      comparePlans(Optimize.execute(optimized), optimized)
+    }
+  }
+
+  test("SPARK-60850: column pruning does not resurrect explicitly removed 
event time") {
+    val (left, right) = watermarkedJoinInputs()
+    val projected = Project(Seq(left.output.head, left.output(2)), left)
+    val join = Join(projected, right, Inner,
+      Some(left.output.head === right.output.head), JoinHint.NONE)
+    withSQLConf(SQLConf.STREAMING_JOIN_PRESERVE_EVENT_TIME_COLUMNS.key -> 
"true") {
+      val optimized = Optimize.execute(Project(Seq(left.output.head), join))
+      val optimizedJoin = optimized.collectFirst { case join: Join => join 
}.get
+      assert(optimizedJoin.left.output == left.output.take(1))
+      assert(optimizedJoin.right.output == right.output.take(2))
+    }
+  }
+
+  test("SPARK-60850: chained joins keep legacy pruning") {

Review Comment:
   **Nit (P3):** The chained-join cases are the only multi-operator plans these 
tests build, and every stateful operator in them is a `Join`. Suppose the 
gate's `collect` were changed to count only stateful joins. Chained joins would 
still collect two and keep legacy pruning, so every new test would pass. But 
`left.join(right, "key").groupBy("key").count()` in update mode would then keep 
each input's timestamp at the join. Its new checkpoints would drop late rows 
there and store the timestamp, and a later fix would break their restarts. A 
`ColumnPruningSuite` case with a streaming `Aggregate` grouped by the join key 
above the join closes the gap. A `Deduplicate` above the join closes it only if 
one input's watermarked timestamp is among its keys. Otherwise 
`Deduplicate.references` keeps both inputs' watermark columns whatever the gate 
decides.
   
   **Verification:**
   - **Behavior:** With the setting on, a stream-stream equality join below a 
streaming aggregation grouped by the join key, and one below a streaming 
deduplication keyed on the join key and the left input's watermarked timestamp, 
optimize to join inputs without the watermarked timestamps that nothing above 
the join reads, and both cases fail if the gate counts only stateful joins.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -212,6 +212,15 @@ class MicroBatchExecution(
     assert(queryExecutionThread eq Thread.currentThread,
       "logicalPlan must be initialized in QueryExecutionThread " +
         s"but the current thread was ${Thread.currentThread}")
+    val streamConf = sparkSessionForStream.sessionState.conf
+    initialLatestOffsetSeq.foreach { case (_, offsets) =>

Review Comment:
   **Nit (P3):** Before the first resumed batch is optimized, 
`populateStartOffsets` already applies the latest entry's metadata through 
`setSessionConf`, which now covers this key with the `false` default for a 
missing key. The two startup optimizations below, 
`ExternalLookupJoinStartupCheck` and 
`StreamingV2ScanPushDown.columnsAndFiltersOfSources`, clone the conf and apply 
the same metadata through `setConfWithoutLogging`. So this write matters only 
when the batches get no metadata. That happens with a latest entry written 
without metadata, which only continuous processing (which rejects stream-stream 
joins) and pre-2.1 logs do. It also happens with a real-time-mode restart that 
purges every uncommitted entry, but real-time mode rejects stream-stream joins 
through its operator allowlist by default, and such a query has no committed 
batch. No checkpoint with committed join state reaches either case. The comment 
implies the existing restoration comes too late, and `getOrElse(false)` 
 is a second copy of the default in `relevantSQLConfDefaultValues` that a later 
edit can let drift. Removing the block, and keeping `streamConf` where the rest 
of the method uses it, leaves every recorded value as it is.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60068#issuecomment-6938825273).
   
   See **Shared repair plan 1** in the review body.



-- 
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]

Reply via email to