You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ho...@apache.org on 2026/09/10 12:35:48 UTC

(spark) branch master updated: [SQL][MINOR] Bound nesting depth when converting protobuf Any to JSON

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new ef6f78bc8930 [SQL][MINOR] Bound nesting depth when converting protobuf Any to JSON
ef6f78bc8930 is described below

commit ef6f78bc8930157890a0238ac462ad214ead57d3
Author: Holden Karau <ho...@snowflake.com>
AuthorDate: Tue Sep 1 05:53:28 2026 +0000

    [SQL][MINOR] Bound nesting depth when converting protobuf Any to JSON
    
    JsonFormat.print re-parses each nested google.protobuf.Any with a fresh
    wire-parse recursion limit while recursing on the JVM stack, so a deeply
    nested Any-in-Any record overflows the executor stack and kills the task
    instead of surfacing as a malformed record. Walk the Any nesting
    iteratively under a single depth budget before printing, so over-deep
    records become ordinary malformed records (null in PERMISSIVE mode, an
    error in FAILFAST).
    
    Co-authored-by: Cursor <cu...@cursor.com>
    Co-Authored-By: Holden Karau <ho...@pigscanfly.ca>
---
 .../spark/sql/protobuf/ProtobufDeserializer.scala  | 61 +++++++++++++++++++++-
 .../sql/protobuf/ProtobufFunctionsSuite.scala      | 24 +++++++++
 2 files changed, 83 insertions(+), 2 deletions(-)

diff --git a/connector/protobuf/src/main/scala/org/apache/spark/sql/protobuf/ProtobufDeserializer.scala b/connector/protobuf/src/main/scala/org/apache/spark/sql/protobuf/ProtobufDeserializer.scala
index baee05a29948..3ff810b70182 100644
--- a/connector/protobuf/src/main/scala/org/apache/spark/sql/protobuf/ProtobufDeserializer.scala
+++ b/connector/protobuf/src/main/scala/org/apache/spark/sql/protobuf/ProtobufDeserializer.scala
@@ -18,7 +18,10 @@ package org.apache.spark.sql.protobuf
 
 import java.util.concurrent.TimeUnit
 
-import com.google.protobuf.{BoolValue, ByteString, BytesValue, DoubleValue, DynamicMessage, FloatValue, Int32Value, Int64Value, Message, StringValue, TypeRegistry, UInt32Value, UInt64Value}
+import scala.collection.mutable
+import scala.jdk.CollectionConverters._
+
+import com.google.protobuf.{BoolValue, ByteString, BytesValue, DoubleValue, DynamicMessage, FloatValue, Int32Value, Int64Value, InvalidProtocolBufferException, Message, StringValue, TypeRegistry, UInt32Value, UInt64Value}
 import com.google.protobuf.Descriptors._
 import com.google.protobuf.Descriptors.FieldDescriptor.JavaType._
 import com.google.protobuf.util.JsonFormat
@@ -94,6 +97,58 @@ private[sql] class ProtobufDeserializer(
       .usingTypeRegistry(typeRegistry)
   }
 
+  // Matches protobuf-java's default recursion limit for wire-format parsing. A nested
+  // google.protobuf.Any is stored as opaque bytes, so JsonFormat.print re-parses each Any
+  // level with a fresh recursion limit while recursing on the JVM stack; without a shared
+  // budget across levels, an Any-in-Any chain a few hundred KB long overflows the stack, and
+  // StackOverflowError is fatal: it escapes the NonFatal-based malformed-record handling
+  // that implements PERMISSIVE/FAILFAST parse modes and kills the task instead.
+  private val anyJsonRecursionLimit = 100
+
+  /**
+   * Performs the same Any unpacking that JsonFormat will perform (against the same type
+   * registry), but iteratively and under a single depth budget, so an over-deep message
+   * fails as an ordinary malformed record (InvalidProtocolBufferException).
+   */
+  private def checkAnyJsonRecursion(root: DynamicMessage): Unit = {
+    val stack = mutable.Stack[(Message, Int)]((root, 0))
+    while (stack.nonEmpty) {
+      val (message, depth) = stack.pop()
+      if (depth > anyJsonRecursionLimit) {
+        throw new InvalidProtocolBufferException(
+          "Message nesting in google.protobuf.Any exceeds the maximum supported depth " +
+            s"($anyJsonRecursionLimit) for JSON conversion")
+      }
+      val descriptor = message.getDescriptorForType
+      if (descriptor.getFullName == "google.protobuf.Any") {
+        val typeUrl =
+          message.getField(descriptor.findFieldByName("type_url")).asInstanceOf[String]
+        // Leave empty or unregistered type URLs for jsonPrinter.print to handle: an empty
+        // Any prints as {}, and an unresolvable type fails there with a descriptive error.
+        if (typeUrl.nonEmpty) {
+          val nestedDescriptor = typeRegistry.getDescriptorForTypeUrl(typeUrl)
+          if (nestedDescriptor != null) {
+            val bytes =
+              message.getField(descriptor.findFieldByName("value")).asInstanceOf[ByteString]
+            stack.push((DynamicMessage.parseFrom(nestedDescriptor, bytes), depth + 1))
+          }
+        }
+      } else {
+        message.getAllFields.asScala.foreach { case (field, fieldValue) =>
+          if (field.getJavaType == MESSAGE) {
+            if (field.isRepeated) {
+              fieldValue.asInstanceOf[java.util.List[Message]].asScala.foreach { item =>
+                stack.push((item, depth + 1))
+              }
+            } else {
+              stack.push((fieldValue.asInstanceOf[Message], depth + 1))
+            }
+          }
+        }
+      }
+    }
+  }
+
   private def newArrayWriter(
       protoField: FieldDescriptor,
       protoPath: Seq[String],
@@ -302,8 +357,10 @@ private[sql] class ProtobufDeserializer(
       case (MESSAGE, StringType)
         if protoType.getMessageType.getFullName == "google.protobuf.Any" =>
         (updater, ordinal, value) =>
+          val anyMessage = value.asInstanceOf[DynamicMessage]
+          checkAnyJsonRecursion(anyMessage)
           // Convert 'Any' protobuf message to JSON string.
-          val jsonStr = jsonPrinter.print(value.asInstanceOf[DynamicMessage])
+          val jsonStr = jsonPrinter.print(anyMessage)
           updater.set(ordinal, UTF8String.fromString(jsonStr))
 
       // Handle well known wrapper types. We unpack the value field when the desired
diff --git a/connector/protobuf/src/test/scala/org/apache/spark/sql/protobuf/ProtobufFunctionsSuite.scala b/connector/protobuf/src/test/scala/org/apache/spark/sql/protobuf/ProtobufFunctionsSuite.scala
index c25b4b264c65..8ecc983c4603 100644
--- a/connector/protobuf/src/test/scala/org/apache/spark/sql/protobuf/ProtobufFunctionsSuite.scala
+++ b/connector/protobuf/src/test/scala/org/apache/spark/sql/protobuf/ProtobufFunctionsSuite.scala
@@ -1506,6 +1506,30 @@ class ProtobufFunctionsSuite extends SharedSparkSession with ProtobufTestBase
     }
   }
 
+  test("deeply nested Any-in-Any is rejected as malformed instead of overflowing the stack") {
+    checkWithFileAndClassName("ProtoWithAny") { case (name, descFilePathOpt) =>
+      // Each nested Any level is re-parsed by JsonFormat with a fresh protobuf recursion
+      // limit; without a cross-level budget a deeply nested record overflows the executor
+      // stack with StackOverflowError, which PERMISSIVE mode cannot recover from.
+      var nested = AnyProto.pack(SimpleMessage.newBuilder().setId(1).build())
+      (0 until 2000).foreach(_ => nested = AnyProto.pack(nested))
+      val deeplyNested = ProtoWithAny.newBuilder()
+        .setEventName("deeply-nested")
+        .setDetails(nested)
+        .build()
+        .toByteArray
+      val inputDF = Seq(deeplyNested).toDF("binary")
+
+      val options = Map(
+        ProtobufOptions.CONVERT_ANY_FIELDS_TO_JSON_CONFIG -> "true",
+        "mode" -> "PERMISSIVE")
+      val dfJson = inputDF.select(
+        from_protobuf_wrapper($"binary", name, descFilePathOpt, options).as("proto"))
+      // The record is treated as malformed (null in PERMISSIVE mode) and the task survives.
+      assert(dfJson.collect()(0).getStruct(0) == null)
+    }
+  }
+
   test("test explicitly set zero values - proto3") {
     // All fields explicitly zero. Message, map, repeated, and oneof fields
     // are left unset, as null is their zero value.


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org