siying commented on code in PR #60068:
URL: https://github.com/apache/spark/pull/60068#discussion_r4575697029


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,8 +273,13 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             prevStateKeyWatermark)
         }
       } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
+        val attributesToFindStateWatermarkFor = if 
(useRetainedEventTimeColumn) {

Review Comment:
   **Eviction is lost when the time condition uses a non-watermark column.** 
With `useRetainedEventTimeColumn`, state-watermark derivation only considers 
the watermark column on that side.
   
   Scenario: left has a watermark on `leftEventTime` and the condition is 
`leftJoinTime > rightEventTime`, with the default version 1. 
`getStateWatermarkPredicates` returns `None` for left where it previously 
returned a predicate. Left state is never evicted, and a left-outer join never 
emits null-padded rows for unmatched left input. The new helper test asserts 
`(None, None)`, which pins this behaviour.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -205,13 +205,31 @@ class MicroBatchExecution(
    * `offsets/` directory during stream startup. Safe to cache: between 
construction
    * and `initializeExecution`, nothing else writes the offset log on the 
query thread.
    */
-  private lazy val initialLatestOffsetSeq: Option[(Long, OffsetSeqBase)] =
-    offsetLog.getLatest()
+  private lazy val initialLatestOffsetSeq: Option[(Long, OffsetSeqBase)] = {
+    val retentionVersion = 
streamMetadata.joinEventTimeColumnRetentionVersion.getOrElse(0)

Review Comment:
   **The metadata-file retention version overrides the legacy default.** The 
value from the `metadata` file unconditionally overwrites the offset-log and 
session values, so the offset-log default of 0 for legacy checkpoints is 
bypassed whenever the metadata file is regenerated.
   
   Scenario: a legacy checkpoint loses its `metadata` file and restarts with 
`STREAMING_CHECKPOINT_VERIFY_METADATA_EXISTS` disabled. 
`StreamingQueryCheckpointMetadata` writes new metadata with the session default 
`Some(1)`, which is injected into the latest offset metadata. `ColumnPruning` 
then keeps the event-time column and the join's state value schema no longer 
matches the stored one.
   
   Separately, a user-set value is silently overwritten here with no warning.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:
##########
@@ -856,7 +873,7 @@ class MicroBatchExecution(
       execCtx: MicroBatchExecutionContext,
       sparkSessionToRunBatches: SparkSession): Unit = {
     execCtx.sinkCommitProgress = None
-    offsetLog.getLatest() match {
+    initialLatestOffsetSeq match {

Review Comment:
   **Real-Time Mode restart ignores the offset-log purge.** 
`populateStartOffsets` now reads the cached `initialLatestOffsetSeq` instead of 
`offsetLog.getLatest()`, so it no longer sees the purge that 
`initializeExecution` performs for RTM just before calling it.
   
   Scenario: an RTM query crashes after writing offset N but before commit N. 
On restart `initializeExecution` runs `offsetLog.purgeAfter(N-1)` and re-reads 
the log into a local variable, but this match still sees cached batch N. It 
sets `batchId = N`, `isCurrentBatchConstructed = true` and the purged end 
offsets, so batch N is replayed and committed with no offset-log entry.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,7 +722,15 @@ class IncrementalExecution(
     }
 
     override def apply(plan: SparkPlan): SparkPlan = {
-      val planWithStateOpId = plan transform composedRule
+      val useRetainedEventTimeColumn =

Review Comment:
   **The physical flag is not tied to what the optimizer actually did.** 
`useRetainedEventTimeColumn` is set from the conf and the join count alone, not 
from whether `ColumnPruning` retained a column.
   
   Scenario: a single-join query runs with `ColumnPruning` in 
`spark.sql.optimizer.excludedRules`, or with a window-struct or ambiguous 
event-time input that `requiredInputReferences` skips. Nothing is retained, yet 
the exec still switches to the new eviction derivation and to 
`useEventTimeIndex = Some(predicate.isDefined)`. The two independently computed 
"exactly one join" gates (logical in `ColumnPruning`, physical here) can also 
drift apart.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1514,8 +1514,14 @@ 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 = {
+    // Multiple stateful joins can emit buffered rows behind their output 
watermark. Retaining
+    // an event-time column at a downstream join would incorrectly classify 
such rows as late.
+    val preserveJoinEventTime =
+      conf.getConf(SQLConf.STREAMING_JOIN_EVENT_TIME_COLUMN_RETENTION_VERSION) 
== 1 &&

Review Comment:
   **This adds a full `plan.collect` to every `ColumnPruning` invocation, 
including batch queries**, because the conf defaults to 1. `ColumnPruning` sits 
in fixed-point batches and runs many times per query. Guarding with 
`plan.isStreaming` or a JOIN tree-pattern check first, or computing the count 
lazily, avoids the traversal for non-streaming plans.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4294,6 +4294,21 @@ object SQLConf {
     .booleanConf
     .createWithDefault(true)
 
+  val STREAMING_JOIN_EVENT_TIME_COLUMN_RETENTION_VERSION =

Review Comment:
   **The PR description does not match the implementation.** The description 
promises an unchanged state layout via a Join-owned annotation and state 
projection; the code stores the timestamp in state behind this conf, which 
defaults to 1. New checkpoints get a different V1-V3 value schema and a 
different V4 index layout, and cannot be read by older binaries (the PR's own 
test comment notes the old binary writes an offset before state-schema 
validation rejects it). The description, the user-facing-change section and the 
test list need updating; the list names a `StreamingJoinColumnPruningSuite` 
that is not in the diff.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -697,7 +698,12 @@ case class StreamingSymmetricHashJoinExec(
       stateFormatVersion = stateFormatVersion,
       skippedNullValueCount = skippedNullValueCount,
       joinStoreGenerator = joinStateManagerStoreGenerator,
-      joinKeyOrdinalForWatermark = joinKeyOrdinalForWatermark)
+      joinKeyOrdinalForWatermark = joinKeyOrdinalForWatermark,
+      useEventTimeIndex = if (useRetainedEventTimeColumn) {

Review Comment:
   **The V4 on-disk layout is recomputed every batch rather than pinned in the 
checkpoint.** It is chosen from `stateWatermarkPredicate.isDefined`, which 
depends on the watermark, the condition and `STATEFUL_OPERATOR_ALLOW_MULTIPLE`.
   
   If predicate definedness changes across a restart (the multiple-event-time 
escape hatch is toggled, or the join condition is edited in a 
state-schema-compatible way), rows written with random-bucket timestamps and no 
index are later looked up or evicted as if indexed. `evictByTimestamp` never 
finds them, so they leak. In legacy mode the layout depended only on the schema.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -260,20 +261,15 @@ class SymmetricHashJoinStateManagerV4(
     // pass the information. The information is in SQLConf.
     allowMultipleEventTimeColumns = false)
 
-  // When there is no event time column in the value and no watermark ordinal 
in the key,
-  // the secondary index (TsWithKey) will never be used for eviction. Skip 
writing to it
-  // to avoid unnecessary RocksDB merge overhead.
-  // TODO(SPARK-56536): This could be further optimized by also considering 
whether the state
-  //   watermark predicate is defined. Even when an event time column exists, 
the secondary index
-  //   is unused if eviction is not possible (e.g., only one side defines a 
watermark in a time
-  //   interval join). That would require propagating the predicate 
information here.
-  private val hasEventTime: Boolean =
-    eventTimeColIdxOpt.isDefined || joinKeyOrdinalForWatermark.isDefined
+  // The execution operator knows whether this side has an eviction predicate. 
Other callers that
+  // do not have that information keep the legacy inference from the available 
event-time fields.
+  private val hasEventTime: Boolean = useEventTimeIndex.getOrElse(

Review Comment:
   **V4 `hasEventTime` depends on an execution-time predicate that other 
callers cannot see.** It now controls both the timestamp in the primary key and 
secondary-index population.
   
   Under version 1, a side with an event-time column but no eviction predicate 
is written with random-bucket timestamps and no `tsWithKey` entries. Callers 
that pass `useEventTimeIndex = None` (state data source, state rewrite or 
repartition tooling) infer `hasEventTime = true` for the same store. Any append 
or evict through such a manager would use real event-time keys and an index the 
streaming writer never maintained. I did not check which of those callers 
write, so this may be read-only in practice.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1514,8 +1514,14 @@ 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 = {
+    // Multiple stateful joins can emit buffered rows behind their output 
watermark. Retaining
+    // an event-time column at a downstream join would incorrectly classify 
such rows as late.
+    val preserveJoinEventTime =

Review Comment:
   **The "exactly one stateful join in the whole plan" gate is fragile.** It is 
a plan-global special case inside a generic rule.
   
   Adding an unrelated second stream-stream join anywhere in the plan, such as 
another union branch, silently returns the first join to legacy pruning and 
reintroduces the late-row bug. The gate is also recomputed on every pass, so 
rules that add or remove joins mid-optimization (for example a left-semi join 
pushed through a Union) can flip retention between passes. A per-join decision, 
based on whether that join's inputs sit below another stateful join, would be 
more robust.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingQueryCheckpointMetadata.scala:
##########
@@ -73,7 +73,10 @@ class StreamingQueryCheckpointMetadata(
             .missingMetadataFile(resolvedCheckpointRoot)
         }
       }
-      val newMetadata = new StreamMetadata(UUID.randomUUID.toString)
+      val newMetadata = StreamMetadata(

Review Comment:
   **The retention version is persisted in two places** (the `metadata` file 
and the offset-log confs), with the metadata file silently winning. Tools that 
read only the offset log, or checkpoints whose offsets and metadata come from 
different origins, see a different version than the engine uses, and 
`initialLatestOffsetSeq` has to rewrite offset metadata in memory to hide the 
difference. Pinning only in the offset log, with a pre-first-batch fallback, 
would remove the override and the new `StreamMetadata` field.



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