Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-50964][SQL] Use StaticInvoke to implement VariantGet codegen #49627

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.sql.catalyst.expressions.variant

import scala.util.parsing.combinator.RegexParsers

import org.apache.spark.sql.catalyst.expressions.{Expression, Literal, RuntimeReplaceable, UnaryExpression}
import org.apache.spark.sql.catalyst.expressions.objects.StaticInvoke
import org.apache.spark.sql.errors.QueryExecutionErrors
import org.apache.spark.sql.types.{DataType, ObjectType, StringType}
import org.apache.spark.unsafe.types.UTF8String

case class ToVariantPathSegmentArray(path: Expression, funcName: String)
extends UnaryExpression
with RuntimeReplaceable {

override def foldable: Boolean = path.foldable
override def nullIntolerant: Boolean = true
override def child: Expression = path
override def prettyName: String = "to_variant_path_segment_array"

override def dataType: DataType = ObjectType(classOf[Array[VariantPathSegment]])

override def replacement: Expression =
StaticInvoke(
VariantPathParser.getClass,
dataType,
"parse",
Seq(path, Literal(UTF8String.fromString(funcName), StringType)),
Seq(path.dataType, StringType)
)

override protected def withNewChildInternal(newChild: Expression): Expression =
copy(path = newChild)
}

object VariantPathParser extends RegexParsers {
private def root: Parser[Char] = '$'

// Parse index segment like `[123]`.
private def index: Parser[VariantPathSegment] =
for {
index <- '[' ~> "\\d+".r <~ ']'
} yield {
ArrayExtraction(index.toInt)
}

// Parse key segment like `.name`, `['name']`, or `["name"]`.
private def key: Parser[VariantPathSegment] =
for {
key <- '.' ~> "[^\\.\\[]+".r | "['" ~> "[^\\'\\?]+".r <~ "']" |
"[\"" ~> "[^\\\"\\?]+".r <~ "\"]"
} yield {
ObjectExtraction(key)
}

private val parser: Parser[List[VariantPathSegment]] = phrase(root ~> rep(key | index))

def parse(str: UTF8String, funcName: UTF8String): Array[VariantPathSegment] = {
if (str == null) return null
parseAll(parser, str.toString) match {
case Success(result, _) => result.toArray
case _ => throw QueryExecutionErrors.invalidVariantGetPath(str.toString, funcName.toString)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ package org.apache.spark.sql.catalyst.expressions.variant

import java.time.ZoneId

import scala.util.parsing.combinator.RegexParsers

import org.apache.spark.SparkRuntimeException
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.analysis.{ExpressionBuilder, GeneratorBuilder, TypeCheckResult}
Expand All @@ -32,7 +30,7 @@ import org.apache.spark.sql.catalyst.expressions.codegen.Block._
import org.apache.spark.sql.catalyst.expressions.objects.StaticInvoke
import org.apache.spark.sql.catalyst.json.JsonInferSchema
import org.apache.spark.sql.catalyst.plans.logical.{FunctionSignature, InputParameter}
import org.apache.spark.sql.catalyst.trees.TreePattern.{TreePattern, VARIANT_GET}
import org.apache.spark.sql.catalyst.trees.TreePattern.{RUNTIME_REPLACEABLE, TreePattern, VARIANT_GET}
import org.apache.spark.sql.catalyst.trees.UnaryLike
import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, GenericArrayData, QuotingUtils}
import org.apache.spark.sql.catalyst.util.DateTimeConstants._
Expand Down Expand Up @@ -192,36 +190,6 @@ case class ObjectExtraction(key: String) extends VariantPathSegment

case class ArrayExtraction(index: Int) extends VariantPathSegment

object VariantPathParser extends RegexParsers {
private def root: Parser[Char] = '$'

// Parse index segment like `[123]`.
private def index: Parser[VariantPathSegment] =
for {
index <- '[' ~> "\\d+".r <~ ']'
} yield {
ArrayExtraction(index.toInt)
}

// Parse key segment like `.name`, `['name']`, or `["name"]`.
private def key: Parser[VariantPathSegment] =
for {
key <- '.' ~> "[^\\.\\[]+".r | "['" ~> "[^\\'\\?]+".r <~ "']" |
"[\"" ~> "[^\\\"\\?]+".r <~ "\"]"
} yield {
ObjectExtraction(key)
}

private val parser: Parser[List[VariantPathSegment]] = phrase(root ~> rep(key | index))

def parse(str: String): Option[Array[VariantPathSegment]] = {
this.parseAll(parser, str) match {
case Success(result, _) => Some(result.toArray)
case _ => None
}
}
}

/**
* The implementation for `variant_get` and `try_variant_get` expressions. Extracts a sub-variant
* value according to a path and cast it into a concrete data type.
Expand All @@ -239,40 +207,29 @@ case class VariantGet(
failOnError: Boolean,
timeZoneId: Option[String] = None)
extends BinaryExpression
with TimeZoneAwareExpression
with RuntimeReplaceable
with ExpectsInputTypes
with TimeZoneAwareExpression
with QueryErrorsBase {
override def checkInputDataTypes(): TypeCheckResult = {
val check = super.checkInputDataTypes()
if (check.isFailure) {
check
} else if (!path.foldable) {
DataTypeMismatch(
errorSubClass = "NON_FOLDABLE_INPUT",
messageParameters = Map(
"inputName" -> toSQLId("path"),
"inputType" -> toSQLType(path.dataType),
"inputExpr" -> toSQLExpr(path)))
} else if (!VariantGet.checkDataType(targetType)) {
DataTypeMismatch(
errorSubClass = "CAST_WITHOUT_SUGGESTION",
messageParameters =
Map("srcType" -> toSQLType(VariantType), "targetType" -> toSQLType(targetType)))
messageParameters = Map(
"srcType" -> toSQLType(VariantType),
"targetType" -> toSQLType(targetType)))
} else {
TypeCheckResult.TypeCheckSuccess
}
}

override lazy val dataType: DataType = targetType.asNullable

@transient private lazy val parsedPath = {
val pathValue = path.eval().toString
VariantPathParser.parse(pathValue).getOrElse {
throw QueryExecutionErrors.invalidVariantGetPath(pathValue, prettyName)
}
}

final override def nodePatternsInternal(): Seq[TreePattern] = Seq(VARIANT_GET)
final override def nodePatternsInternal(): Seq[TreePattern] =
Seq(RUNTIME_REPLACEABLE, VARIANT_GET)

override def inputTypes: Seq[AbstractDataType] =
Seq(VariantType, StringTypeWithCollation(supportsTrimCollation = true))
Expand All @@ -282,42 +239,28 @@ case class VariantGet(
override def nullable: Boolean = true
override def nullIntolerant: Boolean = true

private lazy val castArgs = VariantCastArgs(
failOnError,
timeZoneId,
zoneId)

protected override def nullSafeEval(input: Any, path: Any): Any = {
VariantGet.variantGet(input.asInstanceOf[VariantVal], parsedPath, dataType, castArgs)
}

protected override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val childCode = child.genCode(ctx)
val tmp = ctx.freshVariable("tmp", classOf[Object])
val parsedPathArg = ctx.addReferenceObj("parsedPath", parsedPath)
val dataTypeArg = ctx.addReferenceObj("dataType", dataType)
val castArgsArg = ctx.addReferenceObj("castArgs", castArgs)
val code = code"""
${childCode.code}
boolean ${ev.isNull} = ${childCode.isNull};
${CodeGenerator.javaType(dataType)} ${ev.value} = ${CodeGenerator.defaultValue(dataType)};
if (!${ev.isNull}) {
Object $tmp = org.apache.spark.sql.catalyst.expressions.variant.VariantGet.variantGet(
${childCode.value}, $parsedPathArg, $dataTypeArg, $castArgsArg);
if ($tmp == null) {
${ev.isNull} = true;
} else {
${ev.value} = (${CodeGenerator.boxedType(dataType)})$tmp;
}
}
"""
ev.copy(code = code)
}
private lazy val castArgs = VariantCastArgs(failOnError, timeZoneId, zoneId)

override def left: Expression = child

override def right: Expression = path

@transient
private lazy val dataTypeObjectType = ObjectType(classOf[DataType])
@transient
private lazy val variantCastArgsObjectType = ObjectType(classOf[VariantCastArgs])

override def replacement: Expression = {
val parsedPath = ToVariantPathSegmentArray(path, prettyName)
StaticInvoke(
classOf[org.apache.spark.sql.catalyst.expressions.variant.VariantGet],
dataType,
"variantGet",
Seq(child, parsedPath, Literal(dataType, dataTypeObjectType),
Literal(castArgs, variantCastArgsObjectType)),
Seq(child.dataType, parsedPath.dataType, dataTypeObjectType, variantCastArgsObjectType))
}

override protected def withNewChildrenInternal(
newChild: Expression,
newPath: Expression): VariantGet = copy(child = newChild, path = newPath)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
Project [try_variant_get(static_invoke(VariantExpressionEvalUtils.parseJson(g#0, false, true)), $, IntegerType, false, Some(America/Los_Angeles)) AS try_variant_get(parse_json(g), $)#0]
Project [static_invoke(VariantGet.variantGet(static_invoke(VariantExpressionEvalUtils.parseJson(g#0, false, true)), static_invoke(VariantPathParser.parse($, try_variant_get)), IntegerType, VariantCastArgs(false,Some(America/Los_Angeles),America/Los_Angeles))) AS try_variant_get(parse_json(g), $)#0]
+- LocalRelation <empty>, [id#0L, a#0, b#0, d#0, e#0, f#0, g#0]
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
Project [variant_get(static_invoke(VariantExpressionEvalUtils.parseJson(g#0, false, true)), $, IntegerType, true, Some(America/Los_Angeles)) AS variant_get(parse_json(g), $)#0]
Project [static_invoke(VariantGet.variantGet(static_invoke(VariantExpressionEvalUtils.parseJson(g#0, false, true)), static_invoke(VariantPathParser.parse($, variant_get)), IntegerType, VariantCastArgs(true,Some(America/Los_Angeles),America/Los_Angeles))) AS variant_get(parse_json(g), $)#0]
+- LocalRelation <empty>, [id#0L, a#0, b#0, d#0, e#0, f#0, g#0]
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,17 @@ package org.apache.spark.sql.execution.datasources
import scala.collection.mutable.HashMap

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.{Expression, _}
import org.apache.spark.sql.catalyst.expressions.objects.StaticInvoke
import org.apache.spark.sql.catalyst.expressions.variant._
import org.apache.spark.sql.catalyst.planning.PhysicalOperation
import org.apache.spark.sql.catalyst.plans.logical.{Filter, LogicalPlan, Project, Subquery}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.catalyst.util.ResolveDefaultColumns
import org.apache.spark.sql.errors.QueryExecutionErrors
import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.UTF8String

// A metadata class of a struct field. All struct fields in a struct must either all have this
// metadata, or all don't have it.
Expand All @@ -55,10 +56,8 @@ case class VariantMetadata(
).build()

def parsedPath(): Array[VariantPathSegment] = {
VariantPathParser.parse(path).getOrElse {
val name = if (failOnError) "variant_get" else "try_variant_get"
throw QueryExecutionErrors.invalidVariantGetPath(path, name)
}
val name = if (failOnError) "variant_get" else "try_variant_get"
VariantPathParser.parse(UTF8String.fromString(path), UTF8String.fromString(name))
}
}

Expand Down Expand Up @@ -99,6 +98,14 @@ object RequestedVariantField {
RequestedVariantField(
VariantMetadata(v.path.eval().toString, v.failOnError, v.timeZoneId.get), v.dataType)

def apply(
path: Expression,
failOnError: Boolean,
timeZoneId: Option[String],
dataType: DataType): RequestedVariantField =
RequestedVariantField(
VariantMetadata(path.eval().toString, failOnError, timeZoneId.get), dataType)

def apply(c: Cast): RequestedVariantField =
RequestedVariantField(
VariantMetadata("$", c.evalMode != EvalMode.TRY, c.timeZoneId.get), c.dataType)
Expand Down Expand Up @@ -205,6 +212,12 @@ class VariantInRelation {
map.getOrElseUpdate(field, idx)
}

private val variantGetClz = classOf[org.apache.spark.sql.catalyst.expressions.variant.VariantGet]
private val variantPathParserClz =
org.apache.spark.sql.catalyst.expressions.variant.VariantPathParser.getClass
private lazy val dataTypeObjectType = ObjectType(classOf[DataType])
private lazy val variantCastArgsObjectType = ObjectType(classOf[VariantCastArgs])

// Update `mapping` with any access to a variant. Add the requested fields of each variant and
// potentially remove non-eligible variants.
// If a struct containing a variant is directly used, this variant is not eligible for push down.
Expand All @@ -214,6 +227,21 @@ class VariantInRelation {
def collectRequestedFields(expr: Expression): Unit = expr match {
case v@VariantGet(StructPathToVariant(fields), _, _, _, _) =>
addField(fields, RequestedVariantField(v))
case s @ StaticInvoke(
variantGetClz,
_,
"variantGet",
Seq(StructPathToVariant(fields),
StaticInvoke(variantPathParserClz, _, "parse", Seq(path, _), _, _, _, _, _),
Literal(dataType, dataTypeObjectType),
Literal(d, variantCastArgsObjectType)),
_, _, _, _, _) =>
assert(d.isInstanceOf[VariantCastArgs])
val castArgs = d.asInstanceOf[VariantCastArgs]
if (path.foldable) {
addField(fields, RequestedVariantField(path, castArgs.failOnError, castArgs.zoneStr,
dataType.asInstanceOf[org.apache.spark.sql.types.DataType]))
}
case c@Cast(StructPathToVariant(fields), _, _, _) => addField(fields, RequestedVariantField(c))
case IsNotNull(StructPath(_, _)) | IsNull(StructPath(_, _)) =>
case StructPath(attrId, path) =>
Expand Down Expand Up @@ -244,6 +272,24 @@ class VariantInRelation {
// Rewrite the attribute in advance, rather than depending on the last branch to rewrite it.
// Ww need to avoid the `v@StructPathToVariant(fields)` branch to rewrite the child again.
GetStructField(rewriteAttribute(v), fields(RequestedVariantField(g)))
case s @ StaticInvoke(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is likely the most annoying part of RuntimeReplaceable: pattern match becomes less intuitive.

Now I think it's probably better not to use RuntimeReplaceable for expressions that need be matched post analysis, until we improve RuntimeReplaceable to be replaced truly at runtime.

Copy link
Contributor Author

@panbingkun panbingkun Jan 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's hold it first, and I'll try to investigate how to make a truly RuntimeReplaceable (as we discussed privately, I think its idea is to only execute the replaced expression at runtime, while still maintaining it during the analysis and optimization stages, right?)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that will be the best.

variantGetClz,
_,
"variantGet",
Seq(v @ StructPathToVariant(fields),
StaticInvoke(variantPathParserClz, _, "parse", Seq(path, _), _, _, _, _, _),
Literal(dataType, dataTypeObjectType),
Literal(d, variantCastArgsObjectType)),
_, _, _, _, _) =>
assert(d.isInstanceOf[VariantCastArgs])
val castArgs = d.asInstanceOf[VariantCastArgs]
if (path.foldable) {
GetStructField(rewriteAttribute(v), fields(RequestedVariantField(path,
castArgs.failOnError, castArgs.zoneStr,
dataType.asInstanceOf[org.apache.spark.sql.types.DataType])))
} else {
s
}
case c@Cast(v@StructPathToVariant(fields), _, _, _) =>
GetStructField(rewriteAttribute(v), fields(RequestedVariantField(c)))
case i@IsNotNull(StructPath(_, _)) => rewriteAttribute(i)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,18 @@ class PushVariantIntoScanSuite extends SharedSparkSession {
failOnError = true,
timeZoneId = Some(localTimeZone))

def replace(e: Expression): Expression = e match {
case r: RuntimeReplaceable => replace(r.replacement)
case _ => e.mapChildren(replace)
}

// No push down if the struct containing variant is used.
sql("select vs, variant_get(vs.v1, '$.a') as a from T").queryExecution.optimizedPlan match {
case Project(projectList, l: LogicalRelation) =>
val output = l.output
val vs = output(1)
assert(projectList(0) == vs)
checkAlias(projectList(1), "a", variantGet(GetStructField(vs, 0, Some("v1"))))
checkAlias(projectList(1), "a", replace(variantGet(GetStructField(vs, 0, Some("v1")))))
assert(vs.dataType == StructType(Array(
StructField("v1", VariantType),
StructField("v2", VariantType),
Expand All @@ -148,7 +153,7 @@ class PushVariantIntoScanSuite extends SharedSparkSession {
case Project(projectList, l: LogicalRelation) =>
val output = l.output
val va = output(2)
checkAlias(projectList(0), "a", variantGet(GetArrayItem(va, Literal(0))))
checkAlias(projectList(0), "a", replace(variantGet(GetArrayItem(va, Literal(0)))))
assert(va.dataType == ArrayType(VariantType))
case _ => fail()
}
Expand All @@ -158,7 +163,7 @@ class PushVariantIntoScanSuite extends SharedSparkSession {
case Project(projectList, l: LogicalRelation) =>
val output = l.output
val vd = output(3)
checkAlias(projectList(0), "a", variantGet(vd))
checkAlias(projectList(0), "a", replace(variantGet(vd)))
assert(vd.dataType == VariantType)
case _ => fail()
}
Expand Down
Loading