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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1514,8 +1514,33 @@ 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 = {
+    lazy val retainJoinEventTime =

Review Comment:
   **Blocking (P1):** This gate is re-derived on every start, but the 
checkpoint records only that the setting was on, so a restart edit that makes 
the plan ineligible changes which columns the join's buffered rows are read as. 
The state schema check compares value schemas by position and type and ignores 
names (`StateSchemaCompatibilityChecker.scala:179-180`, 
`DataType.scala:706-712`), so when the edit's columns take the retained 
timestamp's place with the same types, the restart is accepted with only an 
info log.
   
   By the review's reading of the code: on a new checkpoint, start 
`left.join(right, left("key") === right("key")).select(left("key"))`, where 
`left` is `(key, leftEventTime, leftJoinTime)` watermarked on `leftEventTime` 
and `right` is `(key, rightEventTime)` watermarked on `rightEventTime`. The 
plan qualifies, so the left state stores `[key, leftEventTime]`, and the left 
row with key 1, event time 20s, and join time 200s is buffered as `[1, 20s]`. 
Restart with `.where(left("leftJoinTime") > right("rightEventTime"))` added 
after the join: `PushPredicateThroughJoin` merges it into the join condition, 
this gate turns retention off, and the left input becomes `[key, 
leftJoinTime]`, still an integer and a timestamp, so the restart passes the 
schema check. When the right row `(1, 150s)` arrives, the probe reads the 
buffered `20s` as `leftJoinTime`, `20s > 150s` is false, and `Row(1)` is never 
emitted, although the row's real `leftJoinTime` of 200s matches. On the base 
branch the first run
  stores only `[key]`, so the same restart fails with 
`STATE_STORE_VALUE_SCHEMA_NOT_COMPATIBLE`. The same misread follows when the 
predicate is written in the ON clause or the replacing column is on the right 
input, while the migration note and the PR description tell users that such 
edits fail the schema check.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60068#issuecomment-6958131948).
   
   **Recommended change:** When the offset log records 
spark.sql.streaming.join.preserveEventTimeColumns.enabled as true, have the 
stream-stream join compare each side's stored value schema with the schema the 
restarted plan would store before it runs the existing compatibility check. The 
restart fails with a new, clearly worded error when a stored column that 
carried the event-time watermark marker (the EventTimeWatermark.delayKey field 
metadata) has no column at the same position with either the same name or the 
marker. The error names the join side and the stored column and says that the 
restarted query no longer keeps that column, typically because a join condition 
or a filter that compares both inputs changed whether the join qualifies for 
event-time retention, so the change must be reverted or the query started on a 
new checkpoint. Leave a TODO at the check noting that a restart which also 
moves the watermark onto the replacing column is not detected until the 
checkpoint record
 s which columns the join retained. Add stream-stream join restart tests that 
cover the rejected replacement and the restarts that must keep working.
   
   **Why this works:** Schema files persist each value field's metadata, so the 
stored schema records which column was the watermark column. Comparing that 
record with the restarted schema detects the replacement that a filter or 
join-condition edit produces, a column without the watermark taking the stored 
watermark column's place, which the name-insensitive check accepts, and it 
needs no new persisted state. Checkpoints that recorded false or lack the 
setting never contain a retained column, so skipping the comparison for them 
leaves the base branch's validation unchanged.
   
   **Compatibility:** Checkpoints that recorded false or lack the setting, and 
every restart that keeps each stored watermark column at its position, validate 
exactly as before.
   
   **Risks:** On a new checkpoint, a restart that renames a stored watermark 
column and drops its watermark in the same edit now fails with the new error, 
although the base branch restarts it; the error names the column, and the check 
cannot be switched off for a checkpoint that already recorded true. On a new 
checkpoint, a restart that replaces a watermark column the query selects or 
compares in its join condition with another column of the same type also fails 
now, where the base branch restarts it and then misreads its buffered rows.
   
   **Constraints:** The check reads only the stored state schema and the 
restored setting, and adds no persisted field or format version. It runs before 
the existing compatibility check so that users see its error rather than the 
generic one when a stored watermark column disappears. It does not change 
pruning or the stored layout; it only rejects restarts whose stored watermark 
column would be read as a different column.
   
   **Exclusions:**
   - Pinning whether retention applied, so that restarts which change 
eligibility keep the stored layout, is left to the decision about 
eligibility-changing restarts.
   - A restart that also moves the watermark onto the replacing column still 
passes and misreads buffered rows when the query reads that column, because the 
column then carries the watermark marker; reaching it takes a change to which 
column is watermarked in the same restart as the condition, filter, or 
projection edit.
   
   **Verification:**
   - **Regression:** Start an equality-only stream-stream join on a new 
checkpoint whose left input also carries a second timestamp column, buffer a 
left row, and restart after adding a filter that compares that column with the 
right input's timestamp: the restart fails with the new error naming the left 
side's stored watermark column and emits no rows, under state formats 2 and 4. 
The restart fails the same way when the comparison is written in the join's ON 
clause instead, and when the second timestamp column is on the right input.
   - **Behavior:** Restarting an eligible join unchanged, after adding a 
time-range condition on its own watermark columns, or after changing only its 
watermark delay still succeeds and returns the same late-row results as before 
the change.
   - **Compatibility:** A checkpoint whose offset log lacks the setting or 
records false, restarted after the same filter edit, fails with the existing 
state schema error exactly as on the base branch, so the new check does not run 
for it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1514,8 +1514,33 @@ 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 = {
+    lazy 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) &&

Review Comment:
   **Nit (P3):** This residual check sees the join condition only after 
`PushDownPredicates`, which runs before `ColumnPruning` in the same batch 
(`Optimizer.scala:108`, `Optimizer.scala:115`), and a first ineligible pass 
prunes the timestamps for good. So `l.key === r.key && l.extra > 0` in the ON 
clause qualifies only because the one-input predicate is pushed below the join, 
and `.where(l.extra > r.extra)` after the join is excluded only because it is 
merged into the condition. `ColumnPruningSuite`'s executor runs neither 
rewrite, and the new `StreamingJoinSuite` cases use a USING join, a range 
written in the ON clause, and chained joins. If a later change stopped either 
rewrite or moved `ColumnPruning` ahead of it, the checkpoints these queries 
create today would fail to restart after that upgrade, and no test would fail, 
although the PR makes the set of qualifying plans part of the checkpoint 
contract.
   
   **Verification:**
   - **Behavior:** With the setting on and the full optimizer, an equality join 
whose ON clause also has a predicate on one input keeps both watermarked 
timestamps in the physical join inputs, and an equality join followed by a 
filter that compares non-timestamp columns of both inputs keeps neither.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1514,8 +1514,33 @@ 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 = {
+    lazy 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.
+    // Multiple joins, other stateful operators, CTEs, and joins with extra 
predicates keep legacy
+    // pruning. Eligibility determines the stored join row schema. Changing 
which plans qualify,
+    // including through earlier optimizer rules, requires a separately pinned 
mode or a state
+    // migration.

Review Comment:
   **Nit (P3):** The gate counts stateful operators, and `Join.isStateful` 
requires both inputs to be streaming (`basicLogicalOperators.scala:865`), so 
`Project(key, Join(Join(stream1, staticTable, key), stream2, key))` qualifies 
and its new checkpoints store both watermark columns, although it has two 
joins. Because this comment also says eligibility determines the stored row 
schema, a maintainer who trusts "multiple joins ... keep legacy pruning" could 
change the gate for such plans and break their restarts. Wording that states 
what the gate checks:
   
   ```suggestion
       // Retain event time only when the plan's only stateful operator is a 
stream-stream equality
       // join with unambiguous timestamp watermarks. Plans with several 
stateful operators, CTEs, or
       // join conditions beyond equality keys keep legacy pruning. Eligibility 
determines the stored
       // join row schema. Changing which plans qualify, including through 
earlier optimizer rules,
       // requires a separately pinned mode or a state migration.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60068#issuecomment-6958131948).
   
   See **Shared repair plan 1** in the review body.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,14 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, a new stream-stream equality join with a single stateful 
operator may retain
+  watermarked timestamp columns even when they are not selected. Eligible 
joins drop late input
+  rows and store the timestamps in join state. Existing checkpoints keep their 
previous behavior.
+  To keep the previous behavior for a new query, set
+  `spark.sql.streaming.join.preserveEventTimeColumns.enabled` to `false` 
before starting it.
+  Changing a query so that its join becomes eligible or ineligible on restart 
may change the state
+  schema and cause `STATE_STORE_VALUE_SCHEMA_NOT_COMPATIBLE`.

Review Comment:
   **Nit (P3):** The gate requires the join to be the query's only stateful 
operator and its condition to contain only equalities 
(`Optimizer.scala:1525-1527`). This wording attaches "with a single stateful 
operator" to the join, which is itself a stateful operator, so a user whose 
join feeds a streaming aggregation can read it as covering their query, and 
"equality join" does not tell users that a join with any extra predicate, 
including a filter comparing both inputs that the optimizer merges into the 
condition, keeps the previous behavior. That predicate is also the restart edit 
the last sentence warns about. Suggested wording, whose last sentence assumes 
the restart check for a dropped stored timestamp that this review proposes:
   
   ```suggestion
   - Since Spark 4.4, in a new streaming query whose only stateful operator is 
a stream-stream join
     with only equality conditions, the join may retain watermarked timestamp 
columns even when
     they are not selected, drop late input rows, and store the timestamps in 
join state. Joins with
     other conditions, such as time ranges, keep the previous behavior, as do 
existing checkpoints.
     To keep the previous behavior for a new query, set
     `spark.sql.streaming.join.preserveEventTimeColumns.enabled` to `false` 
before starting it.
     Adding or removing such a condition, or a filter that compares columns of 
both join inputs, when
     restarting a query can change the columns its join stores, and the restart 
then fails.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60068#issuecomment-6958131948).
   
   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