spark-test commented on code in PR #60402:
URL: https://github.com/apache/spark/pull/60402#discussion_r4556582834
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala:
##########
@@ -30,15 +32,53 @@ import
org.apache.spark.sql.connector.expressions.aggregate.{AggregateFunc, Avg,
import org.apache.spark.sql.connector.expressions.filter.{AlwaysFalse,
AlwaysTrue, And => V2And, Not => V2Not, Or => V2Or, Predicate => V2Predicate}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{AnyTimestampNanoType, BooleanType,
DataType, IntegerType,
- StringType}
+ StringType, TimestampNTZNanosType, TimestampNTZType}
import org.apache.spark.unsafe.types.UTF8String
/**
* The builder to generate V2 expressions from catalyst expressions.
*/
class V2ExpressionBuilder(e: Expression, isPredicate: Boolean = false) extends
Logging {
- def build(): Option[V2Expression] = generateExpression(e, isPredicate)
+ // Set when the time-zone guard in generateExpression rejected a
subexpression.
+ private var timeZoneGuardHit = false
+ private var checkTimeZone = true
+
+ def build(): Option[V2Expression] = {
+ timeZoneGuardHit = false
+ checkTimeZone = true
+ val translated = generateExpression(e, isPredicate)
+ if (!timeZoneGuardHit) {
+ translated
+ } else {
+ // The guard dropped a zone-dependent subexpression. Re-translate
ignoring the guard and keep
+ // that legacy translation only when the user opts back into
zone-ignoring push-down.
+ checkTimeZone = false
+ val legacyTranslated = generateExpression(e, isPredicate)
Review Comment:
**Nit (P3):** This second pass runs over the whole expression before the
conf is read on the next line, so one of the two translations is always
discarded: this one under the default `false`, the first under `true`. The
guarded and unguarded walks are identical whenever the guard never fires. So
reading `LEGACY_PUSH_DOWN_DATETIME_IGNORING_TIME_ZONE` first and translating
once with `checkTimeZone = !legacy` returns the same `Option` under both
values, and `timeZoneGuardHit` can go. The cost is bounded driver-side work,
but it repeats for every guarded conjunct, aggregate argument, sort key and DDL
conversion. The flag is also set for casts that no case translates, such as a
non-ANSI TIMESTAMP to DATE cast.
**Verification:**
- **Compatibility:** Translate an hour of a TIMESTAMP and a TIMESTAMP to
DATE ANSI cast carrying a zone with other rules than the JVM default's, and
assert no translation with the legacy conf false and the base branch's V2 form
with it true.
- **Inspection:** Check that build() calls generateExpression exactly once
and that no state remains whose only reader was the second pass.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala:
##########
@@ -30,15 +32,53 @@ import
org.apache.spark.sql.connector.expressions.aggregate.{AggregateFunc, Avg,
import org.apache.spark.sql.connector.expressions.filter.{AlwaysFalse,
AlwaysTrue, And => V2And, Not => V2Not, Or => V2Or, Predicate => V2Predicate}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{AnyTimestampNanoType, BooleanType,
DataType, IntegerType,
- StringType}
+ StringType, TimestampNTZNanosType, TimestampNTZType}
import org.apache.spark.unsafe.types.UTF8String
/**
* The builder to generate V2 expressions from catalyst expressions.
*/
class V2ExpressionBuilder(e: Expression, isPredicate: Boolean = false) extends
Logging {
- def build(): Option[V2Expression] = generateExpression(e, isPredicate)
+ // Set when the time-zone guard in generateExpression rejected a
subexpression.
+ private var timeZoneGuardHit = false
+ private var checkTimeZone = true
+
+ def build(): Option[V2Expression] = {
+ timeZoneGuardHit = false
+ checkTimeZone = true
+ val translated = generateExpression(e, isPredicate)
+ if (!timeZoneGuardHit) {
+ translated
+ } else {
+ // The guard dropped a zone-dependent subexpression. Re-translate
ignoring the guard and keep
+ // that legacy translation only when the user opts back into
zone-ignoring push-down.
+ checkTimeZone = false
+ val legacyTranslated = generateExpression(e, isPredicate)
+ if
(SQLConf.get.getConf(SQLConf.LEGACY_PUSH_DOWN_DATETIME_IGNORING_TIME_ZONE)) {
+ legacyTranslated
+ } else {
+ translated
+ }
+ }
+ }
+
+ // A V2 Cast and Extract carry no time zone, and JDBC exchanges timestamps
in the JVM default
+ // zone, so a zone-dependent expression whose zone has other rules yields
other results remotely.
+ private def pushdownLosesTimeZone(expr: Expression): Boolean = {
+ def zoneOf(e: TimeZoneAwareExpression, input: DataType): Option[String] =
input match {
+ case _: TimestampNTZType | _: TimestampNTZNanosType => None
+ case _ => e.timeZoneId
+ }
+ val timeZoneId = expr match {
+ case c: Cast if c.needsTimeZone => c.timeZoneId
+ case f: GetTimeField => zoneOf(f, f.child.dataType)
+ case _ => None
+ }
+ timeZoneId.exists { tz =>
+ DateTimeUtils.getZoneId(tz).getRules !=
TimeZone.getDefault.toZoneId.getRules
Review Comment:
**Non-blocking (P2):** `TimeZone.getDefault` here is the driver's JVM
default zone, read while planning, but the JDBC exchange this comparison stands
for runs on the executors: `JDBCRDD.compute` builds the query with the pushed
predicates, and `JDBCValueGetter` reads TIMESTAMP columns with
`rs.getTimestamp` in each executor's JVM default zone. Nothing relates the two
zones, and Spark does not require them to match.
Reading the code, take a client-mode driver in America/Los_Angeles,
executors in UTC and the default session zone. `WHERE hour(ts) = 13` on a row
whose wall clock is `2024-01-01 21:30:00` is still pushed, because the guard
compares Los Angeles with Los Angeles. The database then evaluates the hour on
the wall clock and drops a row that Spark's own evaluation keeps, as on the
base branch. With the session zone set to UTC, the executors' zone, the pushed
`hour(ts) = 21` returned Spark's result before, and the guard now refuses it.
Deployments whose driver and executors share a zone are unaffected. Neither
this comment nor the migration note says that the fix assumes they share it.
**Recommended change:** In JDBCScanBuilder, when a pushed predicate,
aggregate, group-by key, sort order or join condition contains a zone-dependent
V2 form, meaning a V2 Cast whose source and target types need a time zone or an
HOUR, MINUTE or SECOND extraction of anything but a TIMESTAMP_NTZ column,
record in the scan the JVM default zone ID the driver planned with; a walker
like the existing CHAR-padding check finds these forms. In JDBCRDD.compute,
when such a zone was recorded and the executor's JVM default zone has other
rules, fail the task with a new error condition that names both zones and says
to give the driver and the executors the same JVM time zone or to set
spark.sql.legacy.dataSource.pushDownDatetimeIgnoringTimeZone to true, and skip
the check when that conf is true. Mention the new error in the migration note's
entry and cover it with JDBC push-down tests. In V2ExpressionBuilder, rewrite
the guard's comment to say that it compares with the driver's JVM default zon
e as a stand-in for the zone JDBC exchanges timestamps in, which the JDBC scan
then checks on each executor, and add a TODO there for the push-down lost when
the session zone matches only the executors' zone.
**Why this works:** A scan that pushed a zone-dependent form now carries the
zone the guard compared against, and the executor, the only process that knows
the zone JDBC exchanges values in, refuses to run it when the two zones' rules
differ, so the silent wrong result in a deployment with mixed JVM time zones
becomes an explicit error, while deployments whose driver and executors share a
zone run as before.
**Scope:** Make JDBC scans that pushed zone-dependent datetime expressions
fail on an executor whose JVM time zone differs from the one the driver planned
with.
**Risks:** Queries in mixed-zone deployments that returned wrong rows
silently now fail; setting the legacy conf to true restores the base branch's
behavior. An extraction whose source type the scan builder cannot resolve
counts as zone-dependent, so in a mixed-zone deployment such a query fails even
when its source is a TIMESTAMP_NTZ expression.
**Constraints:** The recorded zone must be the driver's JVM default zone
read while planning, the one the guard compared against. The check must run
before the query is sent to the database, so that no partial result reaches
Spark. The new error condition needs a SQLSTATE and message parameters for both
zone IDs.
**Exclusions:**
- Recovering push-down for a session zone that equals the executors' but not
the driver's needs the executors' zone while planning; it is left out, with a
TODO at the guard that names it.
- Third-party DSv2 connectors evaluate in zones Spark cannot know, as on the
base branch, and are not covered.
**Success:** In a deployment whose executors' JVM default zone has other
rules than the driver's, a JDBC query that pushed a zone-dependent cast or
extraction fails with an error naming both zones instead of returning rows.
When the zones match, or nothing zone-dependent was pushed, JDBC scans run as
with the PR. With the legacy conf true, no check runs. The guard's comment says
that it compares with the driver's JVM default zone, and a TODO there names the
push-down lost when the session zone matches only the executors' zone.
**Verification:**
- **Regression:** Plan a JDBC query that pushes hour(ts) under one JVM
default zone and run its scan where the JVM default zone has other rules;
assert that the scan fails with the new error naming both zones and returns no
rows.
- **Behavior:** With matching zones, assert that the same scan runs and
returns the pushed result, and that a scan pushing only zone-independent forms
runs whatever the executor's zone.
- **Compatibility:** With the legacy conf true and mismatched zones, assert
that the scan runs as on the base branch.
- **Inspection:** Check that the guard's comment names the driver's JVM
default zone as the zone it compares with and that a TODO there names the
push-down lost when the session zone matches only the executors' zone.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala:
##########
@@ -119,6 +159,9 @@ class V2ExpressionBuilder(e: Expression, isPredicate:
Boolean = false) extends L
} else {
generateExpression(constantExpr, isPredicate)
}
+ case _ if checkTimeZone && pushdownLosesTimeZone(expr) =>
Review Comment:
**Non-blocking (P2):** Because this guard sits in the shared
`generateExpression`, it runs for every builder caller, including the DDL
conversions, not only push-down: `CheckConstraint.toV2Constraint`,
`DefaultValueExpression.toV2`/`toV2CurrentDefault` and
`GeneratedColumnExpression.toV2`. When the DDL session's time zone has other
rules than the driver's JVM default, a CHECK condition, default or generation
expression that holds a translatable zone-dependent cast, or an hour, minute or
second of a TIMESTAMP, now gets a null V2 form. What the catalog stores then
depends on a JVM setting unrelated to its metadata, and `Check.predicate()` is
null in a case its javadoc does not list.
This also changes how Spark enforces such a constraint.
`TableConstraintResolution` uses the stored predicate when it can convert it,
and otherwise re-parses `predicateSql` in the writer's session, which
SPARK-60032 keeps the predicate to avoid. Reading the code, with a Los Angeles
JVM and a UTC session, `CREATE TABLE ... CONSTRAINT c CHECK (ts < TIMESTAMP
'2030-01-01 00:00:00' AND CAST(ts AS DATE) <= d)` now stores no predicate,
because the guard rejects `CAST(ts AS DATE)`. A writer in the JVM's zone
inserting `ts = TIMESTAMP '2029-12-31 20:00:00'` (2030-01-01T04:00Z, past the
bound as defined) is rejected on the base branch. On this PR the bound is
re-read as 2030-01-01T08:00Z and the row is written. A cast in the stored
predicate already ran in the writer's zone before, so the change lies in the
frozen literals and table-qualified names. Push-down, the stated problem, needs
no change to catalog metadata.
**Recommended change:** Give V2ExpressionBuilder a constructor parameter
that says whether a source will evaluate the translation, defaulting to true so
that the push-down and write-condition callers, including the nested aggregate
builders that PushableExpression creates, keep the guard; pass false from
CheckConstraint.toV2Constraint, DefaultValueExpression.toV2 and
toV2CurrentDefault, and GeneratedColumnExpression.toV2, and run the guard only
when the parameter is true. Add CHECK constraint tests and column default and
generated-column tests that create these objects in a session whose time zone
differs from the JVM default.
**Why this works:** With the guard keyed on the caller's role, DDL
conversions translate exactly as on the base branch: catalogs receive the
zone-less V2 forms again, Check.predicate() is null only in its documented
cases, and writes enforce such CHECK constraints from the stored predicate with
the constants of the DDL session, while every translation a source evaluates
keeps the guard and the legacy conf.
**Scope:** Keep the time-zone guard to translations that a data source
evaluates, and convert DDL metadata as on the base branch.
**Compatibility:** Read push-down and DSv2 write-condition translation keep
the guard and the legacy conf exactly as the PR implements them.
**Risks:** Catalogs again receive the zone-less V2 forms for DDL run in a
session whose time zone differs from the JVM default, as on the base branch, so
a connector that evaluates such a form natively in another zone keeps the
exposure the base branch has.
**Constraints:** The nested builders that PushableExpression creates for
aggregate arguments must keep the guard, so the parameter's default must be the
guarded behavior. The legacy conf keeps restoring the base branch's translation
for every caller that runs the guard.
**Exclusions:**
- Connectors that evaluate a zone-less V2 form of a CHECK constraint,
default or generation expression in a zone other than the expression's keep the
exposure the base branch already has; carrying the zone in these forms would be
new connector API outside this fix.
**Success:** In a session whose time zone has other rules than the JVM
default's, CREATE TABLE and ALTER TABLE ADD CONSTRAINT with a CHECK condition
holding a zone-dependent column cast store the same V2 predicate as on the base
branch. A write to such a table enforces the stored predicate, so a typed
TIMESTAMP bound keeps the value it had in the session that created the
constraint. Column defaults and generation expressions holding zone-dependent
casts or extractions get the same V2 forms as on the base branch. Read
push-down and DSv2 DELETE and overwrite conditions keep the guard's behavior
and its legacy conf.
**Verification:**
- **Regression:** With ANSI mode on, in a session whose time zone has other
rules than the JVM default's, create a DSv2 table with a CHECK constraint that
compares a TIMESTAMP column with a typed TIMESTAMP literal and also casts that
column to DATE, such as `ts < TIMESTAMP '2030-01-01 00:00:00' AND CAST(ts AS
DATE) <= d`, once through CREATE TABLE and once through ALTER TABLE ADD
CONSTRAINT; for each, assert that the stored predicate is not null, and that
inserting, from a session in another time zone, a row whose timestamp is past
the bound as the creating session read it but before the bound as the inserting
session reads the literal fails with CHECK_CONSTRAINT_VIOLATION.
- **Behavior:** In a session whose time zone differs from the JVM default,
assert that a column default and a generation expression holding a
zone-dependent cast carry a non-null V2 expression.
- **Compatibility:** In the same session, assert that a filter such as
hour(ts) = 21 on a DSv2 JDBC table is still kept in Spark and that an aggregate
over such an expression is still not pushed, so the source translations keep
the guard.
##########
docs/sql-migration-guide.md:
##########
@@ -25,6 +25,7 @@ license: |
## Upgrading from Spark SQL 4.4 to 5.0
- Since Spark 5.0, the Spark Thrift Server refuses to start when
`hive.server2.enable.doAs` is `true` and `hive.server2.authentication` verifies
user identities (any recognized type other than `NONE`/`NOSASL`). It
impersonates the connecting user for Hive metastore calls and driver-side file
system access, but executor-side data access still runs as the server's own
service identity, so storage-level permissions are checked against the service
principal rather than the connecting user (SPARK-5159). Spark 4.4 logs a
warning for the same configuration. To restore the previous behavior, set
`spark.sql.hive.thriftServer.allowIneffectiveDoAs` to `true`. Setting
`hive.server2.enable.doAs` to `false` also starts the server, but note that it
stops impersonating metastore calls as well, so it is not a no-op.
+- Since Spark 5.0, Data Source V2 push-down no longer pushes
time-zone-dependent casts and datetime field extractions (for example
`hour(ts)` or `dayofmonth(ts)` of a `TIMESTAMP` column) when the session time
zone differs from the JVM default time zone, so Spark evaluates them in the
session time zone instead of the source evaluating them in its own zone. To
restore the previous behavior, set
`spark.sql.legacy.dataSource.pushDownDatetimeIgnoringTimeZone` to `true`.
Review Comment:
**Nit (P3):** This note describes read push-down, but the same builder also
translates DSv2 write conditions, and those commands cannot fall back to
evaluating the condition in Spark. A DELETE on a table without row-level
operations translates every conjunct or fails (`DataSourceV2Strategy`), and an
overwrite by condition (`DataFrameWriterV2.overwrite`, `INSERT INTO ... REPLACE
WHERE`) does the same (`V2Writes`). Reading the code, under a session zone
whose rules differ from the JVM default's, `DELETE FROM t WHERE hour(ts) = 21`
on such a table now fails at planning with `_LEGACY_ERROR_TEMP_1109` ("cannot
translate expression to source filter"), which names neither the time zone nor
this conf. The note says Spark evaluates the expression instead, but it does
not. Failing is the safer outcome, since on the base branch the source received
a zone-less condition and could delete other rows than Spark's semantics
select. But the note and the conf doc should say that these commands fail
and that the legacy conf restores them, and a test should pin the failure.
**Verification:**
- **Behavior:** In a session whose time zone differs from the JVM default,
assert that a DELETE on a DSv2 table without row-level operations, such as one
in the `testv2filter` test catalog, whose condition is an hour of a TIMESTAMP
column fails with _LEGACY_ERROR_TEMP_1109 and deletes no row; and that with the
legacy conf true the condition is translated and handed to the table instead,
which that test table, accepting only column equality and null checks, refuses
with _LEGACY_ERROR_TEMP_1110 listing the EXTRACT(HOUR FROM ts) predicate.
- **Inspection:** Check that the migration note and the conf doc name the
failing DELETE and overwrite commands and the conf that restores them.
##########
sql/core/src/test/scala/org/apache/spark/sql/jdbc/JDBCV2Suite.scala:
##########
@@ -1667,6 +1667,38 @@ class JDBCV2Suite extends SharedSparkSession with
ExplainSuiteHelper {
checkAnswer(df9, Seq(Row("alex")))
}
+ // time1 is midnight in the JVM default zone (America/Los_Angeles in tests),
which is 21:00 of the
+ // previous day in Pacific/Honolulu. A zone-dependent field of a TIMESTAMP
must be evaluated in
+ // the session time zone, not pushed to the source (which evaluates it in
its own zone).
+ private def checkDatetimeFieldsInSessionTimeZone(fixed: Boolean): Unit = {
+ assert(TimeZone.getDefault.getID == "America/Los_Angeles")
+ withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "Pacific/Honolulu") {
+ // hour(time1) is 21 for both rows in Honolulu (midnight LA -> 21:00 of
the previous day).
+ val hour = sql("SELECT name FROM h2.test.datetime WHERE hour(time1) =
21")
+ checkFiltersRemoved(hour, removed = !fixed)
+ checkAnswer(hour, if (fixed) Seq(Row("amy"), Row("alex")) else Seq.empty)
+ // dayofmonth(time1) reads CAST(time1 AS DATE); in Honolulu amy -> 18,
alex -> 17.
+ val day = sql("SELECT name FROM h2.test.datetime WHERE dayofmonth(time1)
= 18")
+ checkFiltersRemoved(day, removed = !fixed)
Review Comment:
**Nit (P3):** This `day` case relies on ANSI mode, which the helper does not
pin. `dayofmonth(time1)` reads the `CAST(time1 AS DATE)` that type coercion
inserts with the session's ANSI setting. TIMESTAMP to DATE is not an up-cast,
so `V2ExpressionBuilder` translates that cast only when it is an ANSI cast. The
scheduled non-ANSI build (`build_non_ansi.yml` sets
`SPARK_ANSI_SQL_MODE=false`, which turns the `spark.sql.ansi.enabled` default
off) runs this suite, and there the predicate is never pushed, whatever the
legacy conf. Reading the code, the gate-off test then fails at this assertion,
and the default test's `day` case passes with or without the guard's handling
of casts, so that handling has no failure signal in that build. Adding
`SQLConf.ANSI_ENABLED.key -> "true"` to the helper's `withSQLConf`, next to the
session time zone, as the suite's ANSI push-down tests do, keeps both tests
meaningful in either mode.
**Verification:**
- **Regression:** Run both session-time-zone tests with
spark.sql.ansi.enabled off by default and assert that they pass, and that the
default test's day case fails when the guard no longer rejects zone-dependent
casts.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala:
##########
@@ -30,15 +32,53 @@ import
org.apache.spark.sql.connector.expressions.aggregate.{AggregateFunc, Avg,
import org.apache.spark.sql.connector.expressions.filter.{AlwaysFalse,
AlwaysTrue, And => V2And, Not => V2Not, Or => V2Or, Predicate => V2Predicate}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{AnyTimestampNanoType, BooleanType,
DataType, IntegerType,
- StringType}
+ StringType, TimestampNTZNanosType, TimestampNTZType}
import org.apache.spark.unsafe.types.UTF8String
/**
* The builder to generate V2 expressions from catalyst expressions.
*/
class V2ExpressionBuilder(e: Expression, isPredicate: Boolean = false) extends
Logging {
- def build(): Option[V2Expression] = generateExpression(e, isPredicate)
+ // Set when the time-zone guard in generateExpression rejected a
subexpression.
+ private var timeZoneGuardHit = false
+ private var checkTimeZone = true
+
+ def build(): Option[V2Expression] = {
+ timeZoneGuardHit = false
+ checkTimeZone = true
+ val translated = generateExpression(e, isPredicate)
+ if (!timeZoneGuardHit) {
+ translated
+ } else {
+ // The guard dropped a zone-dependent subexpression. Re-translate
ignoring the guard and keep
+ // that legacy translation only when the user opts back into
zone-ignoring push-down.
+ checkTimeZone = false
+ val legacyTranslated = generateExpression(e, isPredicate)
+ if
(SQLConf.get.getConf(SQLConf.LEGACY_PUSH_DOWN_DATETIME_IGNORING_TIME_ZONE)) {
+ legacyTranslated
+ } else {
+ translated
+ }
+ }
+ }
+
+ // A V2 Cast and Extract carry no time zone, and JDBC exchanges timestamps
in the JVM default
+ // zone, so a zone-dependent expression whose zone has other rules yields
other results remotely.
+ private def pushdownLosesTimeZone(expr: Expression): Boolean = {
Review Comment:
**Nit (P3):** This function keeps push-down in two deliberate cases under a
differing session zone: `zoneOf` exempts the TIMESTAMP_NTZ family, and the
comparison on line 79 uses zone rules rather than IDs, so a same-rules alias of
the JVM zone keeps push-down. No test reaches either. The new tests use only
`time1` (TIMESTAMP) and `date1` (DATE) with Pacific/Honolulu, and the existing
date-time push-down test runs with the session zone equal to the JVM default
ID. `DataSourceV2StrategySuite` has no zone-carrying `Hour`, `Minute`, `Second`
or `Cast` case. Suppose `zoneOf` returned the zone for NTZ inputs too, or the
comparison became an ID comparison. Push-down that is correct on the base
branch would then silently stop for every DSv2 source, and every test would
still pass. Builder-level cases in `DataSourceV2StrategySuite` would pin both.
**Verification:**
- **Regression:** Translate an hour of a TIMESTAMP_NTZ attribute carrying a
zone with other rules than the JVM default's and assert a V2 extraction;
translate an hour of a TIMESTAMP attribute and a TIMESTAMP to DATE ANSI cast
carrying a same-rules alias of the JVM default zone and assert their V2 forms.
--
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]