Skip to content

[SPARK-48845][SQL] GenericUDF catch exceptions from children #47268

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

Closed
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
Expand Up @@ -129,7 +129,11 @@ class HiveGenericUDFEvaluator(
override def returnType: DataType = inspectorToDataType(returnInspector)

def setArg(index: Int, arg: Any): Unit =
deferredObjects(index).asInstanceOf[DeferredObjectAdapter].set(arg)
deferredObjects(index).asInstanceOf[DeferredObjectAdapter].set(() => arg)

def setException(index: Int, exp: Throwable): Unit = {
deferredObjects(index).asInstanceOf[DeferredObjectAdapter].set(() => throw exp)
}

override def doEvaluate(): Any = unwrapper(function.evaluate(deferredObjects))
}
Expand All @@ -139,10 +143,10 @@ private[hive] class DeferredObjectAdapter(oi: ObjectInspector, dataType: DataTyp
extends DeferredObject with HiveInspectors {

private val wrapper = wrapperFor(oi, dataType)
private var func: Any = _
def set(func: Any): Unit = {
private var func: () => Any = _
def set(func: () => Any): Unit = {
this.func = func
}
override def prepare(i: Int): Unit = {}
override def get(): AnyRef = wrapper(func).asInstanceOf[AnyRef]
override def get(): AnyRef = wrapper(func()).asInstanceOf[AnyRef]
}
22 changes: 16 additions & 6 deletions sql/hive/src/main/scala/org/apache/spark/sql/hive/hiveUDFs.scala
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,13 @@ private[hive] case class HiveGenericUDF(

override def eval(input: InternalRow): Any = {
children.zipWithIndex.foreach {
case (child, idx) => evaluator.setArg(idx, child.eval(input))
case (child, idx) =>
try {
evaluator.setArg(idx, child.eval(input))
} catch {
case t: Throwable =>
evaluator.setException(idx, t)
}
}
evaluator.evaluate()
}
Expand All @@ -157,10 +163,15 @@ private[hive] case class HiveGenericUDF(
val setValues = evals.zipWithIndex.map {
case (eval, i) =>
s"""
|if (${eval.isNull}) {
| $refEvaluator.setArg($i, null);
|} else {
| $refEvaluator.setArg($i, ${eval.value});
|try {
| ${eval.code}
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 slightly different from the interpreted path. In codegen we still eagerly execute the function inputs, but delay the throw of errors. I understand that it's hard to be truly lazy in codegen, can we update the interpreted path instead to make it the same as codegen?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure and done. I have updated the code for non-codegen mode and the description for this pr.

| if (${eval.isNull}) {
| $refEvaluator.setArg($i, null);
| } else {
| $refEvaluator.setArg($i, ${eval.value});
| }
Copy link
Contributor

@panbingkun panbingkun Jul 10, 2024

Choose a reason for hiding this comment

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

  • It seems that catch (...) is only related to ${eval.code}
  • Why is it Exception instead of Throwable?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It seems that catch (...) is only related to ${eval.code}

Yes, we should catch the exceptions from child's executions.

Why is it Exception instead of Throwable?

The Exception can catch most of throwable problems. It's ok to be change to Throwable.

|} catch (Throwable t) {
| $refEvaluator.setException($i, t);
|}
|""".stripMargin
}
Expand All @@ -169,7 +180,6 @@ private[hive] case class HiveGenericUDF(
val resultTerm = ctx.freshName("result")
ev.copy(code =
code"""
|${evals.map(_.code).mkString("\n")}
|${setValues.mkString("\n")}
|$resultType $resultTerm = ($resultType) $refEvaluator.evaluate();
|boolean ${ev.isNull} = $resultTerm == null;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* 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.hive.execution;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

public class UDFCatchException extends GenericUDF {

@Override
public ObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException {
if (args.length != 1) {
throw new UDFArgumentException("Exactly one argument is expected.");
}
return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
}

@Override
public Object evaluate(GenericUDF.DeferredObject[] args) {
if (args == null) {
return null;
}
try {
return args[0].get();
} catch (Exception e) {
return null;
}
}

@Override
public String getDisplayString(String[] children) {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* 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.hive.execution;

import org.apache.hadoop.hive.ql.exec.UDF;

public class UDFThrowException extends UDF {
public String evaluate(String data) {
return Integer.valueOf(data).toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import org.apache.hadoop.io.{LongWritable, Writable}

import org.apache.spark.{SparkException, SparkFiles, TestUtils}
import org.apache.spark.sql.{AnalysisException, QueryTest, Row}
import org.apache.spark.sql.catalyst.expressions.CodegenObjectFactoryMode
import org.apache.spark.sql.catalyst.plans.logical.Project
import org.apache.spark.sql.execution.WholeStageCodegenExec
import org.apache.spark.sql.functions.{call_function, max}
Expand Down Expand Up @@ -801,6 +802,28 @@ class HiveUDFSuite extends QueryTest with TestHiveSingleton with SQLTestUtils {
}
}
}

test("SPARK-48845: GenericUDF catch exceptions from child UDFs") {
withTable("test_catch_exception") {
withUserDefinedFunction("udf_throw_exception" -> true, "udf_catch_exception" -> true) {
Seq("9", "9-1").toDF("a").write.saveAsTable("test_catch_exception")
sql("CREATE TEMPORARY FUNCTION udf_throw_exception AS " +
s"'${classOf[UDFThrowException].getName}'")
sql("CREATE TEMPORARY FUNCTION udf_catch_exception AS " +
s"'${classOf[UDFCatchException].getName}'")
Seq(
CodegenObjectFactoryMode.FALLBACK.toString,
CodegenObjectFactoryMode.NO_CODEGEN.toString
).foreach { codegenMode =>
withSQLConf(SQLConf.CODEGEN_FACTORY_MODE.key -> codegenMode) {
val df = sql(
"SELECT udf_catch_exception(udf_throw_exception(a)) FROM test_catch_exception")
checkAnswer(df, Seq(Row("9"), Row(null)))
}
}
}
}
}
}

class TestPair(x: Int, y: Int) extends Writable with Serializable {
Expand Down