Repository navigation
[SPARK-60301][SQL] Use the session time zone when printing variant values as strings - #59561
chenhao-db wants to merge 2 commits into
Conversation
|
@cloud-fan could you take a look? Thanks! |
6b72e0f to
488986e
Compare
cloud-fan
left a comment
There was a problem hiding this comment.
Review summary
The change makes nested variants, ToPrettyString (used by Dataset.show()), and HiveResult render variant TIMESTAMP values in the session time zone. The new tests cover struct, array, and map casts and both evaluation paths in UTC and America/Los_Angeles.
One defect: Cast's time-zone classification was not updated to match. A cast to STRING of an array, map, or struct that contains a VARIANT is still treated as zone-independent, so its canonical form drops the zone. A plan cached or reused from a different session time zone can then silently return the other zone's text, and a zone-less cast of this shape now fails when evaluated. Declaring a nested VARIANT zone-dependent in Cast.needsTimeZoneToString, as SPARK-60179 did for nested TIMESTAMP, closes it.
A question about how to roll out the changed output follows under Decision challenges.
Findings
1 total: 0 P0, 1 P1, 0 P2, 0 P3.
Blocking (P1)
- Cast still classifies a nested VARIANT cast to string as zone-independent —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ToStringBase.scala:104— see inline.
PR description suggestions
- Add the SQL component tag to the title: [SPARK-60301][SQL] Use the session time zone when printing variant values as strings. This follows up on an existing discussion.
Decision challenges
Session-zone variant rendering ships with no legacy setting or migration note
After upgrading, users in a non-UTC session get different text for the same variant TIMESTAMP in nested casts to string, Dataset.show(), and spark-sql CLI and Thrift server output, and they have no setting that restores the old text and no upgrade note that explains it.
Spark 4.3.0 renders all three at UTC: its HiveResult.toHiveString uses VariantVal.toString, and its ToStringBase has no VARIANT case. So text that users store, compare, or parse can change across the upgrade. Rows written before and after it no longer compare equal, a streaming aggregation keyed on such a string splits its groups across a restart, and JDBC or ODBC clients of the Thrift server see a new offset. The instant itself is unchanged, because the text carries an explicit offset, and UTC sessions see no change.
The review leans toward adding both a migration note and a legacy setting. When users who rely on the old output could lose it, the change should come with a rollback flag and a migration note, as the quoted Variant path escape change in the same 4.4 migration-guide section does with spark.sql.legacy.variantPathBackslashAsLiteral.
Which do you prefer? Take, with spark.sql.session.timeZone=America/Los_Angeles, CAST(named_struct('a', CAST(TIMESTAMP'2020-01-01 00:00:00Z' AS VARIANT)) AS STRING):
- Keep the change ungated with no note: the query returns
{"2019-12-31 16:00:00-08:00"}, and nothing else changes. - Add only a migration-guide entry: the query returns the same text, and docs/sql-migration-guide.md gains a "Since Spark 4.4" entry under "Upgrading from Spark SQL 4.3 to 4.4" saying that variant TIMESTAMP values in nested casts to string,
Dataset.show(), and spark-sql CLI and Thrift server output now render in the session time zone instead of UTC. - Add the entry and a
spark.sql.legacy.*boolean setting that defaults to false: the query returns the same text by default. With the setting on, the VARIANT arms inToStringBaseandHiveResult.toHiveStringrender with UTC, and the query returns{"2020-01-01 00:00:00+00:00"}as in Spark 4.3.0.
| case TimestampNTZType => | ||
| acceptAny[Long](t => UTF8String.fromString(timestampNTZFormatter.format(t))) | ||
| case VariantType => | ||
| acceptAny[VariantVal](v => UTF8String.fromString(v.toJson(zoneId))) |
There was a problem hiding this comment.
Blocking (P1): This arm makes the string form of a nested VARIANT depend on the cast's time zone, but Cast.needsTimeZoneToString (Cast.scala:456-461) still has no VariantType case. So Cast.needsTimeZone stays false for a cast to STRING of ARRAY<VARIANT>, MAP<_, VARIANT>, or STRUCT<v: VARIANT>. Its ScalaDoc (Cast.scala:451-454) still says a nested VARIANT renders at UTC, and the SPARK-60179 test in CastSuiteBase.scala (lines 2738-2746) still asserts that these casts do not need a time zone.
Because of that, Cast.canonicalized drops the zone, so two casts that differ only in session time zone count as the same result for sameResult. Reading the code, SELECT CAST(array(v) AS STRING) FROM t, cached under UTC and run again after SET spark.sql.session.timeZone=America/Los_Angeles, is served from the cache as ["2020-01-01 00:00:00+00:00"], while the uncached query returns ["2019-12-31 16:00:00-08:00"]. This is the pattern SPARK-60179 fixed for nested TIMESTAMP (CachedTableSuite.scala:2854-2882), and it also covers exchange reuse and sessions that share the cache manager. In addition, Cast.resolved accepts such a cast without a zone, and evaluating one now fails with None.get because this arm reads zoneId.
The new tests cannot catch this: checkEvaluation assigns the session zone before evaluating, and the stale CastSuiteBase assertion keeps passing.
Recommended change: Add a VariantType case returning true to Cast.needsTimeZoneToString in Cast.scala, and rewrite its ScalaDoc so it says that a VARIANT at any depth renders its TIMESTAMP values in the cast's time zone. In the Cast expression tests, move ARRAY, MAP<INT, VARIANT>, and STRUCT<v: VARIANT> from the zone-independent list of the SPARK-60179 needsTimeZone test to its zone-dependent list and correct its comment, and give the complex-to-string resolution test a nested-variant case. In the cached-table tests, cover a column that casts an array containing a variant TIMESTAMP to string across session time zones.
Why this works: With the new case, Cast.needsTimeZone(from, STRING) is true whenever the source contains a VARIANT. Cast.resolved then requires a zone, Cast.canonicalized keeps it, contextIndependentFoldable reports false, and the zone-gated builders attach the session zone. Two such casts in different zones then canonicalize differently, so QueryPlan.sameResult no longer matches them and the cache manager no longer serves text rendered in one zone to a query in another.
Compatibility: The text that ToStringBase, ToPrettyString, and HiveResult produce for variants is unchanged, as is the classification of the top-level VARIANT cast and of every cast whose source contains no VARIANT.
Risks: The classification is per type, so a cast to string of a struct, array, or map containing a VARIANT becomes zone-dependent even when its variants hold no TIMESTAMP value. Such plans are then no longer reused from a cache or exchange computed in another session time zone, and are no longer folded as context-independent constants, for example into a pushed-down Data Source V2 literal. Nested TIMESTAMP columns already work this way, and reverting the one case undoes it. Such casts also count as zone-dependent in the CHECK constraint write-time check and in Hive metastore partition pruning, which then handle them like other zone-dependent casts.
Constraints: Leave every other case of Cast.needsTimeZone unchanged, including the top-level (VariantType, _) arm; only casts to string whose source contains a nested VARIANT change classification. Keep the new case unconditional even if a legacy setting is later added to restore UTC rendering, because declaring a zone-independent cast zone-dependent is safe while the reverse returns wrong results.
Exclusions:
- Whether the new rendering needs a migration-guide entry or a legacy setting is the separate decision about shipping the change ungated and is not part of this repair.
Verification:
- Behavior: Cast.needsTimeZone reports a cast to string as zone-dependent when its array, map, or struct source contains a VARIANT at any depth, and still reports the TIMESTAMP_NTZ, DATE, and TIME controls as zone-independent.
- Behavior: A complex-to-string cast whose source contains a VARIANT is unresolved without a time zone, resolved with one, and not semantically equal when the only difference is UTC versus America/Los_Angeles.
- Regression: Caching a query that casts an array containing a variant TIMESTAMP to string under UTC and rerunning it under America/Los_Angeles returns the -08:00 rendering instead of the cached +00:00 text.
There was a problem hiding this comment.
Thanks. I address the review comments, please take another look.
A nested VARIANT now renders its TIMESTAMP values in the cast's time zone, so Cast.needsTimeZoneToString must report VARIANT. Otherwise the canonical form drops the zone, a cached plan can serve text rendered in another session time zone, and a cast without a zone resolves but fails at runtime. Also add a migration guide entry for the new rendering. Co-authored-by: Isaac <[email protected]>
cloud-fan
left a comment
There was a problem hiding this comment.
Review summary
Since the previous review, the second commit fixes its blocking finding. Cast.needsTimeZoneToString now treats a VARIANT at any depth as time-zone dependent (Cast.scala:455). So a cast to STRING of an array, map, or struct that contains a VARIANT needs a time zone to resolve and keeps that zone in its canonical form. A cached or reused plan is therefore no longer served to a session in another time zone. CastSuiteBase now lists the nested-variant types as zone-dependent and checks their resolution and semantic equality across zones. CachedTableSuite adds an array-of-variant column to its cross-zone cached-plan test. This round raises no defects.
The commit also adds a migration-guide entry for the new rendering (docs/sql-migration-guide.md:104), which answers the previous review's question about the rollout. Shipping the change with that entry and no setting that restores the UTC text is fine: the old UTC text was inconsistent with a top-level CAST(v AS STRING), the new text carries an explicit offset, so it denotes the same instant, and sessions in UTC are not affected.
The review also covered the session-zone rendering in the cast-to-string builder that nested casts and Dataset.show() share, the spark-sql CLI and Thrift server output in HiveResult, and the time-zone classification change in Cast, and has no finding on them.
Findings
0 total: 0 P0, 0 P1, 0 P2, 0 P3.
No findings.
Re-review status
Prior AI findings: 1 no longer raised, 0 still raised; additional unresolved findings in this review: 0.
PR description suggestions
- In "What changes were proposed in this pull request?", add the
Cast.needsTimeZoneToStringchange: a cast to STRING whose source contains a VARIANT at any depth is now time-zone dependent. Such a cast needs a time zone to resolve and keeps the zone in its canonical form, so a cached or reused plan is not served to a session in another time zone. It is also no longer folded as a context-independent constant. - In "How was this patch tested?", also list the updated
CastSuiteBasetests, which classify nested-variant casts as zone-dependent and check their resolution and semantic equality across zones. Also list theCachedTableSuitetest, which reruns a cached array-of-variant cast under another session time zone.
…lues as strings
### What changes were proposed in this pull request?
Make variant-to-string conversion use the session time zone in all paths:
- `ToStringBase`: add a `VariantType` case to the interpreted path and the codegen path. It calls `VariantVal.toJson(zoneId)`. Before, both paths fell through to `VariantVal.toString`, which always uses UTC. This fixes a variant nested in a struct, array, or map under `CAST(... AS STRING)`. It also fixes `ToPrettyString`, which `Dataset.show()` uses.
- `HiveResult`: add the session `zoneId` to `TimeFormatters`, and use it for variants in `toHiveString`. This fixes the spark-sql CLI and Thrift server output.
### Why are the changes needed?
A top-level `cast(v as string)` uses the cast's time zone, through `VariantGet.cast` and `VariantCastArgs`. A nested variant ignores that zone and always prints UTC. So the same value prints with a different offset at top level and when nested. `to_json` already uses the session time zone.
### Does this PR introduce _any_ user-facing change?
Yes. Variant timestamps now print in the session time zone, not in UTC, in these places:
- a variant nested in a struct, array, or map that is cast to string
- `Dataset.show()`
- spark-sql CLI and Thrift server output
The format does not change: it is still JSON with a `+HH:MM` offset. With `spark.sql.session.timeZone=America/Los_Angeles`:
```sql
SELECT cast(named_struct('a', cast(TIMESTAMP'2020-01-01 00:00:00Z' AS VARIANT)) AS STRING);
-- Before: {"2020-01-01 00:00:00+00:00"}
-- After: {"2019-12-31 16:00:00-08:00"}
```
### How was this patch tested?
- New test in `VariantExpressionSuite`. It covers struct, array, and map casts and `ToPrettyString`, in UTC and in `America/Los_Angeles`, with codegen on and off.
- New test in `HiveResultSuite`. It covers a top-level variant and a variant nested in an array.
- Both new tests fail without the fix.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
Closes #59561 from chenhao-db/variant-to-string-session-zone.
Authored-by: chenhao-db <[email protected]>
Signed-off-by: Wenchen Fan <[email protected]>
(cherry picked from commit d157ec9)
Signed-off-by: Wenchen Fan <[email protected]>
…lues as strings
### What changes were proposed in this pull request?
Make variant-to-string conversion use the session time zone in all paths:
- `ToStringBase`: add a `VariantType` case to the interpreted path and the codegen path. It calls `VariantVal.toJson(zoneId)`. Before, both paths fell through to `VariantVal.toString`, which always uses UTC. This fixes a variant nested in a struct, array, or map under `CAST(... AS STRING)`. It also fixes `ToPrettyString`, which `Dataset.show()` uses.
- `HiveResult`: add the session `zoneId` to `TimeFormatters`, and use it for variants in `toHiveString`. This fixes the spark-sql CLI and Thrift server output.
### Why are the changes needed?
A top-level `cast(v as string)` uses the cast's time zone, through `VariantGet.cast` and `VariantCastArgs`. A nested variant ignores that zone and always prints UTC. So the same value prints with a different offset at top level and when nested. `to_json` already uses the session time zone.
### Does this PR introduce _any_ user-facing change?
Yes. Variant timestamps now print in the session time zone, not in UTC, in these places:
- a variant nested in a struct, array, or map that is cast to string
- `Dataset.show()`
- spark-sql CLI and Thrift server output
The format does not change: it is still JSON with a `+HH:MM` offset. With `spark.sql.session.timeZone=America/Los_Angeles`:
```sql
SELECT cast(named_struct('a', cast(TIMESTAMP'2020-01-01 00:00:00Z' AS VARIANT)) AS STRING);
-- Before: {"2020-01-01 00:00:00+00:00"}
-- After: {"2019-12-31 16:00:00-08:00"}
```
### How was this patch tested?
- New test in `VariantExpressionSuite`. It covers struct, array, and map casts and `ToPrettyString`, in UTC and in `America/Los_Angeles`, with codegen on and off.
- New test in `HiveResultSuite`. It covers a top-level variant and a variant nested in an array.
- Both new tests fail without the fix.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
Closes #59561 from chenhao-db/variant-to-string-session-zone.
Authored-by: chenhao-db <[email protected]>
Signed-off-by: Wenchen Fan <[email protected]>
(cherry picked from commit d157ec9)
Signed-off-by: Wenchen Fan <[email protected]>
What changes were proposed in this pull request?
Make variant-to-string conversion use the session time zone in all paths:
ToStringBase: add aVariantTypecase to the interpreted path and the codegen path. It callsVariantVal.toJson(zoneId). Before, both paths fell through toVariantVal.toString, which always uses UTC. This fixes a variant nested in a struct, array, or map underCAST(... AS STRING). It also fixesToPrettyString, whichDataset.show()uses.HiveResult: add the sessionzoneIdtoTimeFormatters, and use it for variants intoHiveString. This fixes the spark-sql CLI and Thrift server output.Why are the changes needed?
A top-level
cast(v as string)uses the cast's time zone, throughVariantGet.castandVariantCastArgs. A nested variant ignores that zone and always prints UTC. So the same value prints with a different offset at top level and when nested.to_jsonalready uses the session time zone.Does this PR introduce any user-facing change?
Yes. Variant timestamps now print in the session time zone, not in UTC, in these places:
Dataset.show()The format does not change: it is still JSON with a
+HH:MMoffset. Withspark.sql.session.timeZone=America/Los_Angeles:How was this patch tested?
VariantExpressionSuite. It covers struct, array, and map casts andToPrettyString, in UTC and inAmerica/Los_Angeles, with codegen on and off.HiveResultSuite. It covers a top-level variant and a variant nested in an array.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5