hello-stephen commented on code in PR #70808:
URL: https://github.com/apache/doris/pull/70808#discussion_r4795662630


##########
be/src/exprs/function/cast/cast_to_string.h:
##########
@@ -580,15 +580,27 @@ class CastToStringFunction {
 public:
     static Status execute_impl(RuntimeState* state, const 
ColumnWithTypeAndName& source_column,
                                ColumnWithTypeAndName& target_column, size_t 
input_rows_count,
-                               const NullMap::value_type* null_map = nullptr) {
+                               const NullMap::value_type* null_map = nullptr,
+                               bool serialize_for_file_load = false) {
         const IDataType& type = *source_column.type;
         const IColumn& col_from = *source_column.column;
 
         auto col_to = ColumnString::create();
 
         DataTypeSerDe::FormatOptions options;
+        // Native complex parsing removes an escape prefix; it does not decode 
JSON control
+        // escapes. Preserve raw newlines/NULs and protect both quote kinds 
and backslashes.
+        if (serialize_for_file_load) {
+            options.escape_char = '\\';
+            options.need_escape[static_cast<unsigned char>('\\')] = true;
+            options.need_escape[static_cast<unsigned char>('"')] = true;
+            options.need_escape[static_cast<unsigned char>('\'')] = true;

Review Comment:
   [P1] Preserve Avro nested strings when the load destination is VARIANT
   
   Load an Avro array containing one string, `O'Reilly`, into a nullable 
VARIANT column with strict mode off. The Avro VARCHAR source now contains 
`["O\'Reilly"]`. The typed ARRAY parser understands that escape, while the 
`TryParseToVariant` expression installed by 
`NereidsLoadUtils.castScanSlotForLoad` requires JSON and returns SQL NULL. 
`LoadTableReader::_convert` keeps the row, so a successful load can silently 
lose the entire array. Preserve a representation that the JSON destination can 
parse and add a load regression that asserts the stored VARIANT.



##########
regression-test/suites/external_table_p0/iceberg/test_iceberg_avro_read.groovy:
##########
@@ -0,0 +1,142 @@
+// 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.
+
+suite("test_iceberg_avro_read", 
"p0,external,iceberg,external_docker,external_docker_iceberg") {
+    if 
(!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest")))
 {
+        logger.info("disable iceberg test")
+        return
+    }
+    String dockerCommand = 
context.config.otherConfigs.get("externalDockerCommand") ?: "docker"
+    def executeCommand = { String command ->
+        StringBuilder stdout = new StringBuilder()
+        StringBuilder stderr = new StringBuilder()
+        def process = new ProcessBuilder("/bin/bash", "-c", command).start()
+        process.consumeProcessOutput(stdout, stderr)
+        process.waitForOrKill(300000)
+        assertEquals(0, process.exitValue(), "Fixture command failed: 
${stderr}\n${stdout}")
+        return stdout.toString()
+    }
+    String sparkContainer = 
context.config.otherConfigs.get("icebergSparkContainer")
+    if (sparkContainer == null || sparkContainer.isEmpty()) {
+        def matches = executeCommand("${dockerCommand} ps --format 
'{{.ID}}'").readLines().findAll { container ->
+            def probe = new ProcessBuilder("/bin/bash", "-c", 
"${dockerCommand} exec ${container} bash -lc " +
+                    "'test -f /mnt/SUCCESS && command -v spark-sql 
>/dev/null'").start()
+            probe.consumeProcessOutput(new StringBuilder(), new 
StringBuilder())
+            probe.waitForOrKill(30000)
+            return probe.exitValue() == 0
+        }
+        assertEquals(1, matches.size(), "Set icebergSparkContainer to the 
Spark Iceberg container")
+        sparkContainer = matches[0]
+    }
+    String source = new File(context.file.parentFile, 
"avro_data/CreateAvroFixtures.java").getText("UTF-8")
+    String encoded = source.getBytes("UTF-8").encodeBase64().toString()
+    String fixtureDir = "/tmp/doris_avro_${UUID.randomUUID()}"
+    String namespace = "doris_avro_read"
+    String output = executeCommand("${dockerCommand} exec ${sparkContainer} 
bash -lc '" +
+            "mkdir -p ${fixtureDir} && echo ${encoded} | base64 -d 
>${fixtureDir}/CreateAvroFixtures.java && " +
+            "javac -cp \"/opt/spark/jars/*\" 
${fixtureDir}/CreateAvroFixtures.java && " +
+            "java -cp \"${fixtureDir}:/opt/spark/jars/*\" CreateAvroFixtures 
${namespace}'")
+    def snapshots = [:]
+    output.readLines().findAll { it.startsWith("AVRO_SNAPSHOT ") }.each { line 
->
+        def fields = line.split(" ")
+        snapshots[fields[1]] = [fields[2], fields[3]]
+    }
+    assertEquals(4, snapshots.size(), "Independent Iceberg writer/reader must 
verify all format combinations")
+
+    String host = context.config.otherConfigs.get("externalEnvIp")
+    String restPort = context.config.otherConfigs.get("iceberg_rest_uri_port")
+    String minioPort = context.config.otherConfigs.get("iceberg_minio_port")
+    String catalogName = "avro_read_catalog"
+    sql "SET enable_file_scanner_v2 = true"
+    sql "SET time_zone = '+08:00'"
+    def tvf = { String codec, String format ->
+        return """s3('uri'='s3://warehouse/${namespace}/tvf/${codec}.avro',
+            's3.endpoint'='http://${host}:${minioPort}', 
's3.region'='us-east-1',
+            's3.access_key'='admin', 's3.secret_key'='password',
+            'use_path_style'='true', 'format'='${format}')"""
+    }
+    for (String codec : ['null', 'deflate', 'snappy', 'zstandard']) {
+        String sourceTvf = tvf(codec, 'AVRO')
+        "order_qt_tvf_${codec}_values" "SELECT id,label,items,amount,day,clock 
FROM ${sourceTvf} ORDER BY id"
+        "order_qt_tvf_${codec}_projection" "SELECT label,id FROM ${sourceTvf} 
WHERE id >= 3 ORDER BY id"
+        "qt_tvf_${codec}_count" "SELECT COUNT(*),COUNT(label),SUM(amount) FROM 
${sourceTvf}"
+    }
+    qt_tvf_empty "SELECT COUNT(*) FROM ${tvf('empty', 'avro')}"
+    sql "SWITCH internal"
+    sql "CREATE DATABASE IF NOT EXISTS ${namespace}"
+    sql "USE ${namespace}"
+    sql "DROP TABLE IF EXISTS avro_tvf_import"
+    sql """CREATE TABLE avro_tvf_import (id BIGINT, label STRING, amount 
DECIMAL(12,2))
+        DUPLICATE KEY(id) DISTRIBUTED BY HASH(id) BUCKETS 1 PROPERTIES 
('replication_num'='1')"""
+    sql "INSERT INTO avro_tvf_import SELECT id,label,amount FROM 
${tvf('snappy', 'avro')}"
+    order_qt_tvf_insert "SELECT * FROM avro_tvf_import ORDER BY id"
+    sql "TRUNCATE TABLE avro_tvf_import"
+    String streamData = output.readLines().find { 
it.startsWith('AVRO_STREAM_BASE64 ') }.split(' ')[1]
+    File streamFile = File.createTempFile('doris-avro-', '.avro')
+    streamFile.bytes = streamData.decodeBase64()
+    try {
+        streamLoad {
+            db namespace
+            table 'avro_tvf_import'
+            set 'format', 'avro'
+            file streamFile.absolutePath
+        }
+        sql "TRUNCATE TABLE avro_tvf_import"

Review Comment:
   [P3] Check the fixed-length Avro upload before truncating it
   
   The default Stream Load assertion checks success and equality of the 
reported total and loaded counts. The only SELECT sees the later chunked 
upload, so the fixed-length reader could drop rows or change values while this 
regression still passes. Check the expected rows after each upload.



##########
be/src/format_v2/avro/avro_container_reader.cpp:
##########
@@ -0,0 +1,1324 @@
+// 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.
+
+#include "format_v2/avro/avro_container_reader.h"
+
+#include <rapidjson/document.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+#include <snappy.h>
+#include <zlib.h>
+#define ZSTD_STATIC_LINKING_ONLY
+#include <zstd.h>
+
+#include <algorithm>
+#include <array>
+#include <avro/Compiler.hh>
+#include <avro/Generic.hh>
+#include <avro/NodeImpl.hh>
+#include <bit>
+#include <cstring>
+#include <limits>
+#include <string_view>
+#include <type_traits>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include "common/exception.h"
+#include "io/fs/file_reader.h"
+#include "io/io_common.h"
+#include "runtime/runtime_profile.h"
+
+namespace doris::format::avro {
+namespace {
+
+void require(bool condition, const char* message) {
+    if (!condition) {
+        throw Exception(ErrorCode::INVALID_ARGUMENT, message);
+    }
+}
+
+std::string folded_name(std::string name) {
+    for (auto& c : name) {
+        if (c >= 'A' && c <= 'Z') {
+            c += 'a' - 'A';
+        }
+    }
+    return name;
+}
+
+void validate_hive_logical_annotation(const rapidjson::Value& schema, bool 
check_string_coercion) {
+    const auto annotation = schema.FindMember("logicalType");
+    if (annotation == schema.MemberEnd() || !annotation->value.IsString()) {
+        return;
+    }
+    const std::string_view logical(annotation->value.GetString(),
+                                   annotation->value.GetStringLength());
+    const auto type = schema.FindMember("type");
+    if (type == schema.MemberEnd() || !type->value.IsString()) {
+        return;
+    }
+    const std::string_view physical(type->value.GetString(), 
type->value.GetStringLength());
+    const auto folded = folded_name(std::string(logical));
+    // Hive applies char/varchar coercion only to STRING; a LONG tagged 
varchar stays BIGINT.
+    // Unread roots never materialize Hive's truncation or padding semantics 
either.
+    require(physical != "string" || !check_string_coercion ||
+                    (folded != "char" && folded != "varchar"),
+            "Hive Avro char/varchar coercion is unsupported");
+    // Java equalsIgnoreCase also equates dotted/dotless I with decimal's 
ASCII i. Only BYTES
+    // uses Hive's decimal conversion; unknown tags and tags on other carriers 
remain inert.
+    const bool decimal =
+            folded == "decimal" ||
+            (folded.size() == 8 && folded.starts_with("dec") && 
folded.ends_with("mal") &&
+             (folded.substr(3, 2) == "\xc4\xb0" || folded.substr(3, 2) == 
"\xc4\xb1"));
+    require(physical != "bytes" || !decimal || logical == "decimal",
+            "Noncanonical Hive Avro decimal annotation is unsupported");
+}
+
+// Writer defaults never appear on the wire. Strip actual record-field 
defaults before the SDK
+// eagerly constructs them, but never interpret application metadata as 
schema. For example,
+// LONG.items may contain a varchar-shaped metadata object without requesting 
Hive coercion.
+// Avro error schemas are records too and have the same real fields/defaults.
+void strip_field_defaults(rapidjson::Value& schema, bool hive_validation,
+                          bool check_string_coercion = true,
+                          const std::unordered_set<std::string>* 
required_fields = nullptr) {
+    if (schema.IsArray()) {
+        for (auto& branch : schema.GetArray()) {
+            strip_field_defaults(branch, hive_validation, 
check_string_coercion);
+        }
+        return;
+    }
+    if (!schema.IsObject()) {
+        return;
+    }
+    if (hive_validation) {
+        validate_hive_logical_annotation(schema, check_string_coercion);
+    }
+    const auto type = schema.FindMember("type");
+    if (type == schema.MemberEnd()) {
+        return;
+    }
+    if (!type->value.IsString()) {
+        strip_field_defaults(type->value, hive_validation, 
check_string_coercion, required_fields);
+        return;
+    }
+    const std::string_view physical_type(type->value.GetString(), 
type->value.GetStringLength());
+    if ((physical_type == "record" || physical_type == "error")) {
+        const auto fields = schema.FindMember("fields");
+        if (fields != schema.MemberEnd() && fields->value.IsArray()) {
+            for (auto& field : fields->value.GetArray()) {
+                if (field.IsObject() && field.HasMember("type")) {
+                    field.RemoveMember("default");
+                    const bool required = check_string_coercion &&
+                                          (required_fields == nullptr ||
+                                           (field.HasMember("name") && 
field["name"].IsString() &&
+                                            
required_fields->contains(folded_name(std::string(
+                                                    field["name"].GetString(),
+                                                    
field["name"].GetStringLength())))));
+                    strip_field_defaults(field["type"], hive_validation, 
required);
+                }
+            }
+        }
+    } else if (physical_type == "array" || physical_type == "map") {
+        const auto child = schema.FindMember(physical_type == "array" ? 
"items" : "values");
+        if (child != schema.MemberEnd()) {
+            strip_field_defaults(child->value, hive_validation, 
check_string_coercion);
+        }
+    }
+}
+
+void validate_json_keys(const rapidjson::Value& value) {
+    if (value.IsObject()) {
+        std::unordered_set<std::string_view> keys;
+        for (const auto& member : value.GetObject()) {
+            const std::string_view key(member.name.GetString(), 
member.name.GetStringLength());
+            // RapidJSON, Gson and Avro C++ choose different duplicate 
members. Reject them
+            // before removing defaults, so no surviving default can reach 
eager SDK construction.
+            require(keys.insert(key).second, "Duplicate Avro schema JSON key");
+            validate_json_keys(member.value);
+        }
+    } else if (value.IsArray()) {
+        for (const auto& child : value.GetArray()) {
+            validate_json_keys(child);
+        }
+    }
+}
+
+std::string uncomment_hive_schema(const std::string& json) {
+    // Hive accepts Java comments, including CR-only // lines. Replace them 
with whitespace
+    // before the depth scan: a comment such as /* [ " */ is not schema 
structure.
+    std::string result = json;
+    bool quoted = false, escaped = false;
+    for (size_t i = 0; i < json.size(); ++i) {
+        const char c = json[i];
+        if (quoted) {
+            if (escaped) {
+                escaped = false;
+            } else if (c == '\\') {
+                escaped = true;
+            } else if (c == '"') {
+                quoted = false;
+            }
+        } else if (c == '"') {
+            quoted = true;
+        } else if (c == '/' && i + 1 < json.size()) {
+            size_t end = i;
+            if (json[i + 1] == '/') {
+                end = json.find_first_of("\r\n", i + 2);
+                end = end == std::string::npos ? json.size() : end;
+            } else if (json[i + 1] == '*') {
+                end = json.find("*/", i + 2);
+                require(end != std::string::npos, "Invalid Avro schema JSON");
+                end += 2;
+            }
+            if (end != i) {
+                // Do not concatenate tokens or alter quoted slash/escape 
bytes.
+                std::fill(result.begin() + i, result.begin() + end, ' ');
+                i = end - 1;
+            }
+        }
+    }
+    return result;
+}
+
+rapidjson::Document physical_schema_document(
+        const std::string& json, bool hive_validation,
+        const std::unordered_set<std::string>* required_fields = nullptr) {
+    // The caller's schema workspace already covers preprocessing copies. 
Writer schemas
+    // remain strict JSON; only Hive's validated reader literal admits 
comments.
+    const auto uncommented = hive_validation ? uncomment_hive_schema(json) : 
std::string();
+    const auto& source = hive_validation ? uncommented : json;
+    // Bound recursion before either JSON parser runs, including header-only 
files.
+    size_t depth = 0;
+    bool quoted = false, escaped = false;
+    for (const char c : source) {
+        if (quoted) {
+            if (escaped) {
+                escaped = false;
+            } else if (c == '\\') {
+                escaped = true;
+            } else if (c == '"') {
+                quoted = false;
+            }
+        } else if (c == '"') {
+            quoted = true;
+        } else if (c == '{' || c == '[') {
+            require(++depth <= 128, "Avro schema nesting is unsupported");
+        } else if (c == '}' || c == ']') {
+            require(depth != 0, "Invalid Avro schema JSON");
+            --depth;
+        }
+    }
+    require(depth == 0 && !quoted, "Invalid Avro schema JSON");
+    rapidjson::Document document;
+    document.Parse(source.data(), source.size());
+    require(!document.HasParseError(), "Invalid Avro schema JSON");
+    validate_json_keys(document);
+    strip_field_defaults(document, hive_validation, true, required_fields);
+    return document;
+}
+
+void normalize_format_logical_types(rapidjson::Value& schema, bool 
iceberg_compatible) {
+    // Visit schema positions only: a union/field/item/value may define a 
timestamp, whereas
+    // defaults and custom metadata objects are not schemas and must retain 
their own contents.
+    if (schema.IsArray()) {
+        for (auto& branch : schema.GetArray()) {
+            normalize_format_logical_types(branch, iceberg_compatible);
+        }
+        return;
+    }
+    if (!schema.IsObject()) {
+        return;
+    }
+    const auto map_annotation = schema.FindMember("logicalType");
+    // The SDK registry is process-wide. A plain Avro ARRAY<int> annotated 
with Iceberg's map
+    // extension must remain ARRAY even after another reader has registered 
that extension.
+    if (!iceberg_compatible && map_annotation != schema.MemberEnd() &&
+        map_annotation->value.IsString() &&
+        std::string_view(map_annotation->value.GetString(),
+                         map_annotation->value.GetStringLength()) == "map") {
+        schema.RemoveMember(map_annotation);
+    }
+    auto type = schema.FindMember("type");
+    if (type == schema.MemberEnd()) {
+        return;
+    }
+    if (!type->value.IsString()) {
+        normalize_format_logical_types(type->value, iceberg_compatible);
+        return;
+    }
+    const std::string_view physical_type(type->value.GetString(), 
type->value.GetStringLength());
+    if (iceberg_compatible && physical_type == "long") {
+        const auto adjusted = schema.FindMember("adjust-to-utc");
+        auto logical = schema.FindMember("logicalType");
+        // Iceberg 1.12 writes civil timestamps as timestamp-* plus Boolean 
false. Avro C++
+        // drops that custom property; preserve it before compilation or epoch 
0 becomes 08:00
+        // in a +08 session, and civil nanos is rejected as an unsupported 
instant.
+        if (adjusted != schema.MemberEnd() && adjusted->value.IsBool() &&
+            !adjusted->value.GetBool() && logical != schema.MemberEnd() &&
+            logical->value.IsString()) {
+            const std::string_view name(logical->value.GetString(),
+                                        logical->value.GetStringLength());
+            if (name == "timestamp-micros") {
+                
logical->value.SetString(rapidjson::StringRef("local-timestamp-micros"));
+            } else if (name == "timestamp-nanos") {
+                
logical->value.SetString(rapidjson::StringRef("local-timestamp-nanos"));
+            }
+        }
+    } else if ((physical_type == "record" || physical_type == "error")) {
+        const auto fields = schema.FindMember("fields");
+        if (fields != schema.MemberEnd() && fields->value.IsArray()) {
+            for (auto& field : fields->value.GetArray()) {
+                // Malformed record fields remain the SDK compiler's explicit 
error.
+                if (field.IsObject()) {
+                    auto field_type = field.FindMember("type");
+                    if (field_type != field.MemberEnd()) {
+                        normalize_format_logical_types(field_type->value, 
iceberg_compatible);
+                    }
+                }
+            }
+        }
+    } else if (physical_type == "array" || physical_type == "map") {
+        const auto child = schema.FindMember(physical_type == "array" ? 
"items" : "values");
+        if (child != schema.MemberEnd()) {
+            normalize_format_logical_types(child->value, iceberg_compatible);
+        }
+    }
+}
+
+::avro::ValidSchema compile_physical_schema(
+        const std::string& json, bool hive_validation = false, bool 
iceberg_compatible = false,
+        const std::unordered_set<std::string>* required_fields = nullptr) {
+    auto document = physical_schema_document(json, hive_validation, 
required_fields);
+    normalize_format_logical_types(document, iceberg_compatible);
+    rapidjson::StringBuffer output;
+    rapidjson::Writer<rapidjson::StringBuffer> writer(output);
+    require(document.Accept(writer), "Cannot serialize Avro physical schema");
+    return ::avro::compileJsonSchemaFromString(std::string(output.GetString(), 
output.GetSize()));
+}
+
+::avro::NodePtr physical_node(const ::avro::NodePtr& input) {
+    return input->type() == ::avro::AVRO_SYMBOLIC ? 
::avro::resolveSymbol(input) : input;
+}
+
+::avro::NodePtr non_null_branch(const ::avro::NodePtr& input, bool* nullable) {
+    auto node = physical_node(input);
+    *nullable = node->type() == ::avro::AVRO_NULL;
+    if (node->type() != ::avro::AVRO_UNION) {
+        return node;
+    }
+    ::avro::NodePtr value;
+    for (size_t i = 0; i < node->leaves(); ++i) {
+        auto child = physical_node(node->leafAt(i));
+        if (child->type() == ::avro::AVRO_NULL) {
+            *nullable = true;
+        } else {
+            require(!value, "Reader schema requires unsupported Avro union 
resolution");
+            value = std::move(child);
+        }
+    }
+    return value;
+}
+
+void validate_schema_pair(const ::avro::NodePtr& writer, const 
::avro::NodePtr& reader,
+                          size_t depth = 0, bool exact_value_types = false,
+                          bool normalized_projection = false);
+
+void validate_record_pair(const ::avro::NodePtr& from, const ::avro::NodePtr& 
to, size_t depth,
+                          bool exact_value_types, bool normalized_projection) {
+    // Hive resolves record fields by exact name even for before -> after 
record renames.
+    // FIXED and ENUM retain their separate named-type checks in 
validate_schema_pair().
+    std::unordered_set<std::string> reader_names;
+    std::unordered_map<std::string, size_t> writer_names;
+    bool indexed_writer_names = false;
+    for (size_t i = 0; i < to->leaves(); ++i) {
+        auto folded = folded_name(to->nameAt(i));
+        require(reader_names.insert(folded).second,
+                "Avro reader has ambiguous case-insensitive field names");
+        size_t writer_index = 0;
+        bool found = from->nameIndex(to->nameAt(i), writer_index);
+        if (!found) {
+            if (!indexed_writer_names) {
+                for (size_t j = 0; j < from->leaves(); ++j) {
+                    require(writer_names.emplace(folded_name(from->nameAt(j)), 
j).second,
+                            "Avro reader has ambiguous case-insensitive field 
names");
+                }
+                indexed_writer_names = true;
+            }
+            const auto folded_match = writer_names.find(folded);
+            // HMS lowercases STRUCT children (Name -> name); only its 
normalized projection
+            // uses folded matches. Writer-to-literal Avro resolution must 
remain exact.
+            if (normalized_projection && folded_match != writer_names.end()) {
+                writer_index = folded_match->second;
+                found = true;
+            } else {
+                require(folded_match == writer_names.end(),
+                        "Avro reader field differs only by case");
+            }
+        }
+        if (found) {
+            validate_schema_pair(from->leafAt(writer_index), to->leafAt(i), 
depth + 1,
+                                 exact_value_types, normalized_projection);
+            continue;
+        }
+        require(!exact_value_types, "Projected field is absent from Avro 
reader schema");
+        bool nullable = false;
+        (void)non_null_branch(to->leafAt(i), &nullable);
+        require(nullable, "Missing Avro reader field without a nullable 
default");
+    }
+}
+
+void validate_schema_pair(const ::avro::NodePtr& writer, const 
::avro::NodePtr& reader,
+                          size_t depth, bool exact_value_types, bool 
normalized_projection) {
+    require(depth < 64, "Avro reader schema nesting is unsupported");
+    bool writer_null = false, reader_null = false;
+    const auto from = non_null_branch(writer, &writer_null);
+    const auto to = non_null_branch(reader, &reader_null);
+    require(!writer_null || reader_null, "Avro reader schema cannot resolve 
nullable writer");
+    if (!from || from->type() == ::avro::AVRO_NULL) {
+        return;
+    }
+    require(to && to->type() != ::avro::AVRO_NULL, "Incompatible Avro reader 
schema");
+    const auto& from_logical = from->logicalType();
+    const auto& to_logical = to->logicalType();
+    const auto source = from->type(), target = to->type();
+    // Hive 3 maps FIXED decimal to BINARY and returns its raw bytes. This 
exception belongs
+    // only to the HMS projection; the actual Avro reader literal must still 
match the decimal.
+    if (normalized_projection && source == ::avro::AVRO_FIXED && target == 
::avro::AVRO_BYTES &&
+        to_logical.type() == ::avro::LogicalType::NONE &&
+        (from_logical.type() == ::avro::LogicalType::NONE ||
+         from_logical.type() == ::avro::LogicalType::DECIMAL)) {
+        return;
+    }
+    // A SQL cast after writer-logical decoding is not Avro resolution (date 
int 1 becomes
+    // 19700102). Require identical logical interpretation before 
projection/predicate mapping.
+    require(from_logical.type() == to_logical.type(), "Incompatible Avro 
reader logical type");

Review Comment:
   [P2] Read UUID-annotated strings with Hive's STRING semantics
   
   A Hive 3 table can use a nullable STRING with `logicalType: "uuid"` in both 
its reader literal and its Avro file. Hive returns the original string. Doris 
synthesizes a plain STRING projection from HMS and this comparison rejects UUID 
versus NONE with `Incompatible Avro reader logical type`, even when the writer 
and reader schemas match. Apply Hive's logical-type rules when interpreting 
these schemas, while preserving UUID behavior for standalone Avro and Iceberg. 
[Hive 3 type 
mapping](https://github.com/apache/hive/blob/rel/release-3.1.3/serde/src/java/org/apache/hadoop/hive/serde2/avro/SchemaToTypeInfo.java#L149-L192)
 ยท [Hive 3 string 
deserialization](https://github.com/apache/hive/blob/rel/release-3.1.3/serde/src/java/org/apache/hadoop/hive/serde2/avro/AvroDeserializer.java#L234-L240)



##########
be/src/format_v2/avro/avro_container_reader.cpp:
##########
@@ -0,0 +1,1324 @@
+// 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.
+
+#include "format_v2/avro/avro_container_reader.h"
+
+#include <rapidjson/document.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+#include <snappy.h>
+#include <zlib.h>
+#define ZSTD_STATIC_LINKING_ONLY
+#include <zstd.h>
+
+#include <algorithm>
+#include <array>
+#include <avro/Compiler.hh>
+#include <avro/Generic.hh>
+#include <avro/NodeImpl.hh>
+#include <bit>
+#include <cstring>
+#include <limits>
+#include <string_view>
+#include <type_traits>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include "common/exception.h"
+#include "io/fs/file_reader.h"
+#include "io/io_common.h"
+#include "runtime/runtime_profile.h"
+
+namespace doris::format::avro {
+namespace {
+
+void require(bool condition, const char* message) {
+    if (!condition) {
+        throw Exception(ErrorCode::INVALID_ARGUMENT, message);
+    }
+}
+
+std::string folded_name(std::string name) {
+    for (auto& c : name) {
+        if (c >= 'A' && c <= 'Z') {
+            c += 'a' - 'A';
+        }
+    }
+    return name;
+}
+
+void validate_hive_logical_annotation(const rapidjson::Value& schema, bool 
check_string_coercion) {
+    const auto annotation = schema.FindMember("logicalType");
+    if (annotation == schema.MemberEnd() || !annotation->value.IsString()) {
+        return;
+    }
+    const std::string_view logical(annotation->value.GetString(),
+                                   annotation->value.GetStringLength());
+    const auto type = schema.FindMember("type");
+    if (type == schema.MemberEnd() || !type->value.IsString()) {
+        return;
+    }
+    const std::string_view physical(type->value.GetString(), 
type->value.GetStringLength());
+    const auto folded = folded_name(std::string(logical));
+    // Hive applies char/varchar coercion only to STRING; a LONG tagged 
varchar stays BIGINT.
+    // Unread roots never materialize Hive's truncation or padding semantics 
either.
+    require(physical != "string" || !check_string_coercion ||
+                    (folded != "char" && folded != "varchar"),
+            "Hive Avro char/varchar coercion is unsupported");
+    // Java equalsIgnoreCase also equates dotted/dotless I with decimal's 
ASCII i. Only BYTES
+    // uses Hive's decimal conversion; unknown tags and tags on other carriers 
remain inert.
+    const bool decimal =
+            folded == "decimal" ||
+            (folded.size() == 8 && folded.starts_with("dec") && 
folded.ends_with("mal") &&
+             (folded.substr(3, 2) == "\xc4\xb0" || folded.substr(3, 2) == 
"\xc4\xb1"));
+    require(physical != "bytes" || !decimal || logical == "decimal",
+            "Noncanonical Hive Avro decimal annotation is unsupported");
+}
+
+// Writer defaults never appear on the wire. Strip actual record-field 
defaults before the SDK
+// eagerly constructs them, but never interpret application metadata as 
schema. For example,
+// LONG.items may contain a varchar-shaped metadata object without requesting 
Hive coercion.
+// Avro error schemas are records too and have the same real fields/defaults.
+void strip_field_defaults(rapidjson::Value& schema, bool hive_validation,
+                          bool check_string_coercion = true,
+                          const std::unordered_set<std::string>* 
required_fields = nullptr) {
+    if (schema.IsArray()) {
+        for (auto& branch : schema.GetArray()) {
+            strip_field_defaults(branch, hive_validation, 
check_string_coercion);
+        }
+        return;
+    }
+    if (!schema.IsObject()) {
+        return;
+    }
+    if (hive_validation) {
+        validate_hive_logical_annotation(schema, check_string_coercion);
+    }
+    const auto type = schema.FindMember("type");
+    if (type == schema.MemberEnd()) {
+        return;
+    }
+    if (!type->value.IsString()) {
+        strip_field_defaults(type->value, hive_validation, 
check_string_coercion, required_fields);
+        return;
+    }
+    const std::string_view physical_type(type->value.GetString(), 
type->value.GetStringLength());
+    if ((physical_type == "record" || physical_type == "error")) {
+        const auto fields = schema.FindMember("fields");
+        if (fields != schema.MemberEnd() && fields->value.IsArray()) {
+            for (auto& field : fields->value.GetArray()) {
+                if (field.IsObject() && field.HasMember("type")) {
+                    field.RemoveMember("default");
+                    const bool required = check_string_coercion &&
+                                          (required_fields == nullptr ||
+                                           (field.HasMember("name") && 
field["name"].IsString() &&
+                                            
required_fields->contains(folded_name(std::string(
+                                                    field["name"].GetString(),
+                                                    
field["name"].GetStringLength())))));
+                    strip_field_defaults(field["type"], hive_validation, 
required);
+                }
+            }
+        }
+    } else if (physical_type == "array" || physical_type == "map") {
+        const auto child = schema.FindMember(physical_type == "array" ? 
"items" : "values");
+        if (child != schema.MemberEnd()) {
+            strip_field_defaults(child->value, hive_validation, 
check_string_coercion);
+        }
+    }
+}
+
+void validate_json_keys(const rapidjson::Value& value) {
+    if (value.IsObject()) {
+        std::unordered_set<std::string_view> keys;
+        for (const auto& member : value.GetObject()) {
+            const std::string_view key(member.name.GetString(), 
member.name.GetStringLength());
+            // RapidJSON, Gson and Avro C++ choose different duplicate 
members. Reject them
+            // before removing defaults, so no surviving default can reach 
eager SDK construction.
+            require(keys.insert(key).second, "Duplicate Avro schema JSON key");
+            validate_json_keys(member.value);
+        }
+    } else if (value.IsArray()) {
+        for (const auto& child : value.GetArray()) {
+            validate_json_keys(child);
+        }
+    }
+}
+
+std::string uncomment_hive_schema(const std::string& json) {
+    // Hive accepts Java comments, including CR-only // lines. Replace them 
with whitespace
+    // before the depth scan: a comment such as /* [ " */ is not schema 
structure.
+    std::string result = json;
+    bool quoted = false, escaped = false;
+    for (size_t i = 0; i < json.size(); ++i) {
+        const char c = json[i];
+        if (quoted) {
+            if (escaped) {
+                escaped = false;
+            } else if (c == '\\') {
+                escaped = true;
+            } else if (c == '"') {
+                quoted = false;
+            }
+        } else if (c == '"') {
+            quoted = true;
+        } else if (c == '/' && i + 1 < json.size()) {
+            size_t end = i;
+            if (json[i + 1] == '/') {
+                end = json.find_first_of("\r\n", i + 2);
+                end = end == std::string::npos ? json.size() : end;
+            } else if (json[i + 1] == '*') {
+                end = json.find("*/", i + 2);
+                require(end != std::string::npos, "Invalid Avro schema JSON");
+                end += 2;
+            }
+            if (end != i) {
+                // Do not concatenate tokens or alter quoted slash/escape 
bytes.
+                std::fill(result.begin() + i, result.begin() + end, ' ');
+                i = end - 1;
+            }
+        }
+    }
+    return result;
+}
+
+rapidjson::Document physical_schema_document(
+        const std::string& json, bool hive_validation,
+        const std::unordered_set<std::string>* required_fields = nullptr) {
+    // The caller's schema workspace already covers preprocessing copies. 
Writer schemas
+    // remain strict JSON; only Hive's validated reader literal admits 
comments.
+    const auto uncommented = hive_validation ? uncomment_hive_schema(json) : 
std::string();
+    const auto& source = hive_validation ? uncommented : json;
+    // Bound recursion before either JSON parser runs, including header-only 
files.
+    size_t depth = 0;
+    bool quoted = false, escaped = false;
+    for (const char c : source) {
+        if (quoted) {
+            if (escaped) {
+                escaped = false;
+            } else if (c == '\\') {
+                escaped = true;
+            } else if (c == '"') {
+                quoted = false;
+            }
+        } else if (c == '"') {
+            quoted = true;
+        } else if (c == '{' || c == '[') {
+            require(++depth <= 128, "Avro schema nesting is unsupported");
+        } else if (c == '}' || c == ']') {
+            require(depth != 0, "Invalid Avro schema JSON");
+            --depth;
+        }
+    }
+    require(depth == 0 && !quoted, "Invalid Avro schema JSON");
+    rapidjson::Document document;
+    document.Parse(source.data(), source.size());
+    require(!document.HasParseError(), "Invalid Avro schema JSON");
+    validate_json_keys(document);
+    strip_field_defaults(document, hive_validation, true, required_fields);
+    return document;
+}
+
+void normalize_format_logical_types(rapidjson::Value& schema, bool 
iceberg_compatible) {
+    // Visit schema positions only: a union/field/item/value may define a 
timestamp, whereas
+    // defaults and custom metadata objects are not schemas and must retain 
their own contents.
+    if (schema.IsArray()) {
+        for (auto& branch : schema.GetArray()) {
+            normalize_format_logical_types(branch, iceberg_compatible);
+        }
+        return;
+    }
+    if (!schema.IsObject()) {
+        return;
+    }
+    const auto map_annotation = schema.FindMember("logicalType");
+    // The SDK registry is process-wide. A plain Avro ARRAY<int> annotated 
with Iceberg's map
+    // extension must remain ARRAY even after another reader has registered 
that extension.
+    if (!iceberg_compatible && map_annotation != schema.MemberEnd() &&
+        map_annotation->value.IsString() &&
+        std::string_view(map_annotation->value.GetString(),
+                         map_annotation->value.GetStringLength()) == "map") {
+        schema.RemoveMember(map_annotation);
+    }
+    auto type = schema.FindMember("type");
+    if (type == schema.MemberEnd()) {
+        return;
+    }
+    if (!type->value.IsString()) {
+        normalize_format_logical_types(type->value, iceberg_compatible);
+        return;
+    }
+    const std::string_view physical_type(type->value.GetString(), 
type->value.GetStringLength());
+    if (iceberg_compatible && physical_type == "long") {
+        const auto adjusted = schema.FindMember("adjust-to-utc");
+        auto logical = schema.FindMember("logicalType");
+        // Iceberg 1.12 writes civil timestamps as timestamp-* plus Boolean 
false. Avro C++
+        // drops that custom property; preserve it before compilation or epoch 
0 becomes 08:00
+        // in a +08 session, and civil nanos is rejected as an unsupported 
instant.
+        if (adjusted != schema.MemberEnd() && adjusted->value.IsBool() &&
+            !adjusted->value.GetBool() && logical != schema.MemberEnd() &&
+            logical->value.IsString()) {
+            const std::string_view name(logical->value.GetString(),
+                                        logical->value.GetStringLength());
+            if (name == "timestamp-micros") {
+                
logical->value.SetString(rapidjson::StringRef("local-timestamp-micros"));
+            } else if (name == "timestamp-nanos") {
+                
logical->value.SetString(rapidjson::StringRef("local-timestamp-nanos"));
+            }
+        }
+    } else if ((physical_type == "record" || physical_type == "error")) {
+        const auto fields = schema.FindMember("fields");
+        if (fields != schema.MemberEnd() && fields->value.IsArray()) {
+            for (auto& field : fields->value.GetArray()) {
+                // Malformed record fields remain the SDK compiler's explicit 
error.
+                if (field.IsObject()) {
+                    auto field_type = field.FindMember("type");
+                    if (field_type != field.MemberEnd()) {
+                        normalize_format_logical_types(field_type->value, 
iceberg_compatible);
+                    }
+                }
+            }
+        }
+    } else if (physical_type == "array" || physical_type == "map") {
+        const auto child = schema.FindMember(physical_type == "array" ? 
"items" : "values");
+        if (child != schema.MemberEnd()) {
+            normalize_format_logical_types(child->value, iceberg_compatible);
+        }
+    }
+}
+
+::avro::ValidSchema compile_physical_schema(
+        const std::string& json, bool hive_validation = false, bool 
iceberg_compatible = false,
+        const std::unordered_set<std::string>* required_fields = nullptr) {
+    auto document = physical_schema_document(json, hive_validation, 
required_fields);
+    normalize_format_logical_types(document, iceberg_compatible);
+    rapidjson::StringBuffer output;
+    rapidjson::Writer<rapidjson::StringBuffer> writer(output);
+    require(document.Accept(writer), "Cannot serialize Avro physical schema");
+    return ::avro::compileJsonSchemaFromString(std::string(output.GetString(), 
output.GetSize()));
+}
+
+::avro::NodePtr physical_node(const ::avro::NodePtr& input) {
+    return input->type() == ::avro::AVRO_SYMBOLIC ? 
::avro::resolveSymbol(input) : input;
+}
+
+::avro::NodePtr non_null_branch(const ::avro::NodePtr& input, bool* nullable) {
+    auto node = physical_node(input);
+    *nullable = node->type() == ::avro::AVRO_NULL;
+    if (node->type() != ::avro::AVRO_UNION) {
+        return node;
+    }
+    ::avro::NodePtr value;
+    for (size_t i = 0; i < node->leaves(); ++i) {
+        auto child = physical_node(node->leafAt(i));
+        if (child->type() == ::avro::AVRO_NULL) {
+            *nullable = true;
+        } else {
+            require(!value, "Reader schema requires unsupported Avro union 
resolution");
+            value = std::move(child);
+        }
+    }
+    return value;
+}
+
+void validate_schema_pair(const ::avro::NodePtr& writer, const 
::avro::NodePtr& reader,
+                          size_t depth = 0, bool exact_value_types = false,
+                          bool normalized_projection = false);
+
+void validate_record_pair(const ::avro::NodePtr& from, const ::avro::NodePtr& 
to, size_t depth,
+                          bool exact_value_types, bool normalized_projection) {
+    // Hive resolves record fields by exact name even for before -> after 
record renames.
+    // FIXED and ENUM retain their separate named-type checks in 
validate_schema_pair().
+    std::unordered_set<std::string> reader_names;
+    std::unordered_map<std::string, size_t> writer_names;
+    bool indexed_writer_names = false;
+    for (size_t i = 0; i < to->leaves(); ++i) {
+        auto folded = folded_name(to->nameAt(i));
+        require(reader_names.insert(folded).second,
+                "Avro reader has ambiguous case-insensitive field names");
+        size_t writer_index = 0;
+        bool found = from->nameIndex(to->nameAt(i), writer_index);
+        if (!found) {
+            if (!indexed_writer_names) {
+                for (size_t j = 0; j < from->leaves(); ++j) {
+                    require(writer_names.emplace(folded_name(from->nameAt(j)), 
j).second,
+                            "Avro reader has ambiguous case-insensitive field 
names");
+                }
+                indexed_writer_names = true;
+            }
+            const auto folded_match = writer_names.find(folded);
+            // HMS lowercases STRUCT children (Name -> name); only its 
normalized projection
+            // uses folded matches. Writer-to-literal Avro resolution must 
remain exact.
+            if (normalized_projection && folded_match != writer_names.end()) {
+                writer_index = folded_match->second;
+                found = true;
+            } else {
+                require(folded_match == writer_names.end(),
+                        "Avro reader field differs only by case");
+            }
+        }
+        if (found) {
+            validate_schema_pair(from->leafAt(writer_index), to->leafAt(i), 
depth + 1,
+                                 exact_value_types, normalized_projection);
+            continue;
+        }
+        require(!exact_value_types, "Projected field is absent from Avro 
reader schema");
+        bool nullable = false;
+        (void)non_null_branch(to->leafAt(i), &nullable);
+        require(nullable, "Missing Avro reader field without a nullable 
default");
+    }
+}
+
+void validate_schema_pair(const ::avro::NodePtr& writer, const 
::avro::NodePtr& reader,
+                          size_t depth, bool exact_value_types, bool 
normalized_projection) {
+    require(depth < 64, "Avro reader schema nesting is unsupported");
+    bool writer_null = false, reader_null = false;
+    const auto from = non_null_branch(writer, &writer_null);
+    const auto to = non_null_branch(reader, &reader_null);
+    require(!writer_null || reader_null, "Avro reader schema cannot resolve 
nullable writer");
+    if (!from || from->type() == ::avro::AVRO_NULL) {
+        return;
+    }
+    require(to && to->type() != ::avro::AVRO_NULL, "Incompatible Avro reader 
schema");
+    const auto& from_logical = from->logicalType();
+    const auto& to_logical = to->logicalType();
+    const auto source = from->type(), target = to->type();
+    // Hive 3 maps FIXED decimal to BINARY and returns its raw bytes. This 
exception belongs
+    // only to the HMS projection; the actual Avro reader literal must still 
match the decimal.
+    if (normalized_projection && source == ::avro::AVRO_FIXED && target == 
::avro::AVRO_BYTES &&
+        to_logical.type() == ::avro::LogicalType::NONE &&
+        (from_logical.type() == ::avro::LogicalType::NONE ||
+         from_logical.type() == ::avro::LogicalType::DECIMAL)) {
+        return;
+    }
+    // A SQL cast after writer-logical decoding is not Avro resolution (date 
int 1 becomes
+    // 19700102). Require identical logical interpretation before 
projection/predicate mapping.
+    require(from_logical.type() == to_logical.type(), "Incompatible Avro 
reader logical type");
+    if (from_logical.type() == ::avro::LogicalType::DECIMAL) {
+        // Decimal parameter evolution is not implemented by this physical 
compatibility gate.
+        require(from_logical.precision() == to_logical.precision() &&
+                        from_logical.scale() == to_logical.scale(),
+                "Avro decimal reader precision/scale evolution is 
unsupported");
+    }
+    if (normalized_projection && ((source == ::avro::AVRO_FIXED && target == 
::avro::AVRO_BYTES) ||
+                                  (source == ::avro::AVRO_ENUM && target == 
::avro::AVRO_STRING &&
+                                   from_logical.type() == 
::avro::LogicalType::NONE))) {
+        // A DECIMAL projection keeps its parameters; enums carry symbols as 
strings. The separate
+        // writer-to-literal gate has already enforced named types, sizes and 
symbol membership.
+        return;
+    }
+    const bool promoted = (source == ::avro::AVRO_INT &&
+                           (target == ::avro::AVRO_LONG || target == 
::avro::AVRO_FLOAT ||
+                            target == ::avro::AVRO_DOUBLE)) ||
+                          (source == ::avro::AVRO_LONG &&
+                           (target == ::avro::AVRO_FLOAT || target == 
::avro::AVRO_DOUBLE)) ||
+                          (source == ::avro::AVRO_FLOAT && target == 
::avro::AVRO_DOUBLE) ||
+                          (source == ::avro::AVRO_STRING && target == 
::avro::AVRO_BYTES) ||
+                          (source == ::avro::AVRO_BYTES && target == 
::avro::AVRO_STRING);
+    // Java resolves bytes to STRING with UTF-8 replacement; raw byte 
insertion is not equivalent.
+    require(source != ::avro::AVRO_BYTES || target != ::avro::AVRO_STRING,
+            "Hive Avro bytes-to-string resolution is unsupported");
+    const bool identical_string_storage =
+            source == ::avro::AVRO_STRING && target == ::avro::AVRO_BYTES;
+    require(source == target || (promoted && (!exact_value_types || 
identical_string_storage) &&
+                                 from_logical.type() == 
::avro::LogicalType::NONE),
+            "Incompatible Avro reader physical type");
+    if (source == ::avro::AVRO_RECORD) {
+        validate_record_pair(from, to, depth, exact_value_types, 
normalized_projection);
+    } else if (source == ::avro::AVRO_ARRAY || source == ::avro::AVRO_MAP) {
+        validate_schema_pair(from->leafAt(source == ::avro::AVRO_MAP ? 1 : 0),
+                             to->leafAt(target == ::avro::AVRO_MAP ? 1 : 0), 
depth + 1,
+                             exact_value_types, normalized_projection);
+    } else if (source == ::avro::AVRO_FIXED) {
+        require(from->name() == to->name() && from->fixedSize() == 
to->fixedSize(),
+                "Incompatible Avro fixed reader schema");
+    } else if (source == ::avro::AVRO_ENUM) {
+        require(from->name() == to->name(), "Incompatible Avro enum reader 
schema");
+        for (size_t i = 0; i < from->names(); ++i) {
+            size_t index = 0;
+            require(to->nameIndex(from->nameAt(i), index), "Incompatible Avro 
enum symbols");
+        }
+    }
+}
+
+template <typename Cursor>
+int64_t read_long(Cursor& cursor) {
+    uint64_t value = 0;
+    for (unsigned shift = 0; shift < 64; shift += 7) {
+        const uint8_t byte = cursor.byte();
+        // The tenth byte has only one available bit in a 64-bit Avro varint.
+        require(shift != 63 || byte <= 1, "Avro varint overflows");
+        value |= static_cast<uint64_t>(byte & 127) << shift;
+        if ((byte & 128) == 0) {
+            return static_cast<int64_t>(value >> 1) ^ 
-static_cast<int64_t>(value & 1);
+        }
+    }
+    throw Exception(ErrorCode::INVALID_ARGUMENT, "Invalid Avro varint");
+}
+
+struct MemoryCursor {
+    const uint8_t* data = nullptr;
+    size_t length = 0;
+    size_t position = 0;
+    size_t remaining() const { return length - position; }
+    uint8_t byte() {
+        require(remaining() != 0, "Truncated Avro value");
+        return data[position++];
+    }
+    void read(void* output, size_t size) {
+        require(size <= remaining(), "Truncated Avro value");
+        if (size != 0) {
+            memcpy(output, data + position, size);
+        }
+        position += size;
+    }
+    void skip(size_t size) {
+        require(size <= remaining(), "Truncated Avro value");
+        position += size;
+    }
+};
+
+class FileCursor {
+public:
+    FileCursor(io::FileReaderSPtr file, std::shared_ptr<io::IOContext> context)
+            : _file(std::move(file)), _context(std::move(context)) {}
+    size_t position() const { return _position; }
+    size_t remaining() const { return _file->size() - _position; }
+    size_t scratch_bytes() const { return _prefix_buffer.capacity(); }
+    void coalesce_prefix(const AvroContainerReader::Reserve& reserve) {
+        reserve(1024 * 1024);
+        _prefix_buffer.resize(1024 * 1024);
+        _buffer_size = 0;
+    }
+    void seek(size_t position) {
+        require(position <= _file->size(), "Invalid Avro file offset");
+        _position = position;
+    }
+    uint8_t byte() {
+        uint8_t value;
+        read(&value, 1);
+        return value;
+    }
+    void read(void* output, size_t size) {
+        require(size <= remaining(), "Truncated Avro container");
+        auto* destination = static_cast<uint8_t*>(output);
+        while (size != 0) {
+            if (_context != nullptr && _context->should_stop) {
+                throw Exception(ErrorCode::CANCELLED, "Avro scan cancelled");
+            }
+            if (_position < _buffer_start || _position >= _buffer_start + 
_buffer_size) {
+                size_t read = 0;
+                auto* buffer = _prefix_buffer.empty() ? _buffer.data() : 
_prefix_buffer.data();
+                const auto capacity =
+                        _prefix_buffer.empty() ? _buffer.size() : 
_prefix_buffer.size();
+                auto status =
+                        _file->read_at(_position, Slice(buffer, 
std::min(capacity, remaining())),
+                                       &read, _context.get());
+                if (!status.ok()) {
+                    throw Exception(status);
+                }
+                require(read != 0, "Truncated Avro container");
+                _buffer_start = _position;
+                _buffer_size = read;
+            }
+            const size_t count = std::min(size, _buffer_start + _buffer_size - 
_position);
+            const auto* buffer = _prefix_buffer.empty() ? _buffer.data() : 
_prefix_buffer.data();
+            memcpy(destination, buffer + _position - _buffer_start, count);
+            destination += count;
+            size -= count;
+            _position += count;
+        }
+    }
+
+private:
+    io::FileReaderSPtr _file;
+    std::shared_ptr<io::IOContext> _context;
+    std::array<char, 64 * 1024> _buffer;
+    std::vector<char> _prefix_buffer;
+    size_t _position = 0;
+    size_t _buffer_start = 0;
+    size_t _buffer_size = 0;
+};
+
+struct MetadataCursor {
+    FileCursor& file;
+    size_t end;
+    size_t remaining() const { return end - file.position(); }
+    uint8_t byte() {
+        require(remaining() != 0, "Truncated Avro metadata block");
+        return file.byte();
+    }
+    void read(void* output, size_t size) {
+        require(size <= remaining(), "Truncated Avro metadata block");
+        file.read(output, size);
+    }
+};
+
+::avro::NodePtr resolved(const ::avro::NodePtr& node) {
+    return node->type() == ::avro::AVRO_SYMBOLIC ? ::avro::resolveSymbol(node) 
: node;
+}
+
+} // namespace
+
+struct AvroContainerReader::Impl {
+    FileCursor file;
+    Reserve reserve;
+    Checkpoint checkpoint;
+    Workspace workspace;
+    RuntimeProfile::Counter* decompress_time = nullptr;
+    ::avro::ValidSchema schema;
+    ::avro::ValidSchema projected_schema;
+    std::unordered_map<std::string, std::string> metadata;
+    size_t metadata_charge = 0;
+    std::array<uint8_t, 16> sync;
+    std::vector<uint8_t> compressed;
+    std::vector<uint8_t> uncompressed;
+    std::unordered_map<const ::avro::Node*, size_t> datum_sizes;
+    std::unordered_map<const ::avro::Node*, std::vector<int32_t>> 
record_projections;
+    size_t projection_charge = 0;
+    MemoryCursor data;
+    size_t header_end = 0;
+    int64_t remaining_rows = 0;
+    int64_t total_rows = 0;
+    size_t schema_charge = 0;
+    bool loaded = false;
+
+    void build_projection(const ::avro::NodePtr& input, const ::avro::NodePtr& 
output) {
+        const auto source = resolved(input);
+        const auto target = resolved(output);
+        if (source->type() == ::avro::AVRO_RECORD) {
+            if (record_projections.contains(target.get())) {
+                return;
+            }
+            // Resolve names once per projected record, never by scanning 
names for each row.
+            // The name views live in projected_schema for the complete 
decoder lifetime.
+            reserve(128 + source->leaves() * sizeof(int32_t) + 
target->leaves() * 96);
+            std::unordered_map<std::string_view, int32_t> ordinals;
+            for (size_t i = 0; i < target->leaves(); ++i) {
+                ordinals.emplace(target->nameAt(i), static_cast<int32_t>(i));
+            }
+            std::vector<int32_t> fields(source->leaves(), -1);
+            size_t matched = 0;
+            for (size_t i = 0; i < source->leaves(); ++i) {
+                const auto found = ordinals.find(source->nameAt(i));
+                if (found != ordinals.end()) {
+                    fields[i] = found->second;
+                    ++matched;
+                    build_projection(source->leafAt(i), 
target->leafAt(found->second));
+                }
+            }
+            require(matched == target->leaves(), "Invalid Avro record 
projection");
+            projection_charge += 128 + fields.capacity() * sizeof(int32_t);
+            record_projections.emplace(target.get(), std::move(fields));
+        } else if (source->type() == ::avro::AVRO_UNION) {
+            const bool swap =
+                    source->leaves() == 2 && source->leafAt(1)->type() == 
::avro::AVRO_NULL;
+            for (size_t i = 0; i < source->leaves(); ++i) {
+                build_projection(source->leafAt(i), target->leafAt(swap ? 1 - 
i : i));
+            }
+        } else if (source->type() == ::avro::AVRO_ARRAY || source->type() == 
::avro::AVRO_MAP) {
+            const size_t child = source->type() == ::avro::AVRO_MAP ? 1 : 0;
+            build_projection(source->leafAt(child), target->leafAt(child));
+        }
+    }
+
+    Impl(io::FileReaderSPtr input, std::shared_ptr<io::IOContext> context, 
Reserve allocation,
+         Checkpoint reset, Workspace codec_workspace, RuntimeProfile* profile,
+         bool iceberg_compatible)
+            : file(std::move(input), std::move(context)),
+              reserve(std::move(allocation)),
+              checkpoint(std::move(reset)),
+              workspace(std::move(codec_workspace)) {
+        if (profile != nullptr) {
+            decompress_time = ADD_CHILD_TIMER_WITH_LEVEL(profile, 
"AvroDecompressTime",
+                                                         
"AvroDecodeAndMaterializeTime", 1);
+        }
+        std::array<uint8_t, 4> magic;
+        file.read(magic.data(), magic.size());
+        require(magic == std::array<uint8_t, 4> {'O', 'b', 'j', 1}, "Invalid 
Avro magic");
+        for (int64_t count = read_long(file); count != 0; count = 
read_long(file)) {
+            std::optional<size_t> block_end;
+            if (count < 0) {
+                require(count != std::numeric_limits<int64_t>::min(),
+                        "Invalid Avro metadata count");
+                count = -count;
+                const auto bytes = read_long(file);
+                require(bytes >= 0 && static_cast<uint64_t>(bytes) <= 
file.remaining(),
+                        "Invalid Avro metadata block");
+                block_end = file.position() + static_cast<size_t>(bytes);
+            }
+            // A negative map block cannot borrow bytes from its successor or 
the sync marker.
+            MetadataCursor block_input {
+                    .file = file, .end = block_end.value_or(file.position() + 
file.remaining())};
+            growth(0, count, 128);
+            require(static_cast<uint64_t>(count) <= block_input.remaining() / 
2,
+                    "Truncated Avro metadata");
+            for (int64_t i = 0; i < count; ++i) {
+                auto key = read_string(block_input);
+                auto value = read_string(block_input);
+                metadata.insert_or_assign(std::move(key), std::move(value));
+            }
+            require(!block_end || file.position() == *block_end,
+                    "Avro metadata block size mismatch");
+        }
+        file.read(sync.data(), sync.size());
+        // Header metadata never changes after parsing. Walking it from 
scratchBytes() after
+        // every COUNT/data row makes retained-memory accounting O(rows * 
metadata entries).
+        for (const auto& [key, value] : metadata) {
+            metadata_charge += 128 + key.capacity() + value.capacity();
+        }
+        header_end = file.position();
+        const auto found = metadata.find("avro.schema");
+        require(found != metadata.end(), "Avro schema metadata is missing");
+        // Cover the preprocessing DOM/output and compiler graph before 
allocating any of them.
+        growth(0, found->second.size(), 32);
+        schema_charge = found->second.size() * 32;
+        schema = compile_physical_schema(found->second, false, 
iceberg_compatible);
+    }
+
+    void growth(size_t capacity, size_t count, size_t item_size = 1) const {
+        require(count <= std::numeric_limits<int64_t>::max() / 2 / item_size,
+                "Avro allocation size overflows");
+        if (count > capacity) {
+            reserve(std::max(count, capacity * 2) * item_size);
+        }
+    }
+
+    void grow_buffer(std::vector<uint8_t>& buffer, size_t size) const {
+        const auto maximum =
+                std::min(buffer.max_size(), 
size_t(std::numeric_limits<int64_t>::max()) / 2);
+        require(size <= maximum, "Avro allocation size overflows");
+        if (size > buffer.capacity()) {
+            // Chunked output must not retain every superseded capacity 
(64+128+... KiB).
+            // Admit only the delta; a 2->4 MiB reallocation still needs a 
scoped 2 MiB
+            // lease so its actual 6 MiB old/new overlap is checked before 
allocating.
+            const auto target = std::max(
+                    size,
+                    buffer.capacity() + std::min(buffer.capacity(), maximum - 
buffer.capacity()));
+            auto old_buffer = buffer.capacity() == 0 ? nullptr : 
workspace(buffer.capacity());
+            reserve(target - buffer.capacity());
+            buffer.reserve(target);
+        }
+    }
+
+    template <typename Cursor>
+    std::string read_string(Cursor& input) {
+        const auto length = read_long(input);
+        require(length >= 0, "Invalid Avro string length");
+        // Check the current block's boundary before admitting or allocating 
the string.
+        require(static_cast<uint64_t>(length) <= input.remaining(), "Truncated 
Avro string");
+        growth(0, length);
+        std::string value(static_cast<size_t>(length), '\0');
+        input.read(value.data(), value.size());
+        return value;
+    }
+
+    size_t datum_size(const ::avro::NodePtr& input) {
+        const auto node = resolved(input);
+        if (const auto found = datum_sizes.find(node.get()); found != 
datum_sizes.end()) {
+            return found->second;
+        }
+        size_t size = 0;
+        switch (node->type()) {
+        case ::avro::AVRO_STRING:
+            size = sizeof(std::string);
+            break;
+        case ::avro::AVRO_BYTES:
+            size = sizeof(std::vector<uint8_t>);
+            break;
+        case ::avro::AVRO_FIXED:
+            size = sizeof(::avro::GenericFixed) + node->fixedSize();
+            break;
+        case ::avro::AVRO_ARRAY:
+            size = sizeof(::avro::GenericArray);
+            break;
+        case ::avro::AVRO_MAP:
+            size = sizeof(::avro::GenericMap);
+            break;
+        case ::avro::AVRO_ENUM:
+            size = sizeof(::avro::GenericEnum);
+            break;
+        case ::avro::AVRO_UNION: {
+            // Estimate the canonical null-first skeleton even when this is a 
writer node used
+            // to admit a nested branch. An unused large FIXED alternative 
must not consume budget.
+            const size_t first =
+                    node->leaves() == 2 && node->leafAt(1)->type() == 
::avro::AVRO_NULL ? 1 : 0;
+            size = sizeof(::avro::GenericUnion) + 
datum_size(node->leafAt(first));
+            break;
+        }
+        case ::avro::AVRO_RECORD:
+            size = sizeof(::avro::GenericRecord) + node->leaves() * 
sizeof(::avro::GenericDatum);
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                const auto child = datum_size(node->leafAt(i));
+                require(child <= std::numeric_limits<int64_t>::max() - size,
+                        "Avro datum size overflows");
+                size += child;
+            }
+            break;
+        default:
+            break;
+        }
+        datum_sizes.emplace(node.get(), size);
+        return size;
+    }
+
+    bool zero_width(const ::avro::NodePtr& input) {
+        const auto node = resolved(input);
+        if (node->type() == ::avro::AVRO_NULL) {
+            return true;
+        }
+        if (node->type() == ::avro::AVRO_FIXED) {
+            return node->fixedSize() == 0;
+        }
+        if (node->type() != ::avro::AVRO_RECORD) {
+            return false;
+        }
+        for (size_t i = 0; i < node->leaves(); ++i) {
+            if (!zero_width(node->leafAt(i))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    int64_t block_header(size_t* payload_end) {
+        const int64_t count = read_long(file);
+        const int64_t bytes = read_long(file);
+        require(count >= 0 && bytes >= 0 && file.remaining() >= sync.size() &&
+                        static_cast<uint64_t>(bytes) <= file.remaining() - 
sync.size(),
+                "Invalid Avro data block bounds");
+        *payload_end = file.position() + bytes;
+        return count;
+    }
+
+    void verify_sync() {
+        std::array<uint8_t, 16> marker;
+        file.read(marker.data(), marker.size());
+        require(marker == sync, "Avro sync mismatch");
+    }
+
+    void decompress_snappy() {
+        require(compressed.size() >= 4, "Truncated Avro Snappy block");
+        const size_t length = compressed.size() - 4;
+        size_t output_size = 0;
+        require(snappy::GetUncompressedLength(reinterpret_cast<const 
char*>(compressed.data()),
+                                              length, &output_size),
+                "Invalid Avro Snappy block");
+        grow_buffer(uncompressed, output_size);
+        uncompressed.resize(output_size);
+        require(snappy::RawUncompress(reinterpret_cast<const 
char*>(compressed.data()), length,
+                                      
reinterpret_cast<char*>(uncompressed.data())),
+                "Avro Snappy decompression failed");
+        uint32_t expected = 0;
+        for (size_t i = length; i < compressed.size(); ++i) {
+            expected = (expected << 8) | compressed[i];
+        }
+        auto actual = crc32(0, nullptr, 0);
+        for (size_t offset = 0; offset < uncompressed.size();) {
+            const auto size = std::min(size_t(64 * 1024), uncompressed.size() 
- offset);
+            actual = crc32(actual, uncompressed.data() + offset, 
static_cast<uInt>(size));
+            offset += size;
+        }
+        require(expected == actual, "Avro Snappy checksum mismatch");
+    }
+
+    void decompress_zstandard() {
+        // Even a zero-byte Avro datum needs a real compressed frame when a 
block owns rows.
+        require(!compressed.empty(), "Missing Avro Zstandard frame");
+        size_t offset = 0;
+        while (offset < compressed.size()) {
+            const auto* frame = compressed.data() + offset;
+            const auto frame_size = ZSTD_findFrameCompressedSize(frame, 
compressed.size() - offset);
+            require(!ZSTD_isError(frame_size), "Invalid Avro Zstandard frame");
+            const auto workspace_bytes = 
ZSTD_estimateDStreamSize_fromFrame(frame, frame_size);
+            require(!ZSTD_isError(workspace_bytes), "Invalid Avro Zstandard 
window");
+            auto workspace_lease = workspace(workspace_bytes);
+            std::unique_ptr<ZSTD_DStream, decltype(&ZSTD_freeDStream)> 
stream(ZSTD_createDStream(),
+                                                                              
&ZSTD_freeDStream);
+            require(stream != nullptr && 
!ZSTD_isError(ZSTD_initDStream(stream.get())),
+                    "Cannot initialize Avro Zstandard decoder");
+            ZSTD_inBuffer input {frame, frame_size, 0};
+            std::array<uint8_t, 64 * 1024> chunk;
+            size_t remaining = 1;
+            while (input.pos < input.size || remaining != 0) {
+                ZSTD_outBuffer output {chunk.data(), chunk.size(), 0};
+                remaining = ZSTD_decompressStream(stream.get(), &output, 
&input);
+                require(!ZSTD_isError(remaining), "Avro Zstandard 
decompression failed");
+                append(chunk.data(), output.pos);
+                require(input.pos != input.size || remaining == 0 || 
output.pos != 0,
+                        "Truncated Avro Zstandard frame");
+            }
+            offset += frame_size;
+        }
+    }
+
+    void decompress_deflate() {
+        if (compressed.empty()) {
+            // Avro C++ omits the deflate frame for zero-byte records, even 
with a positive count.
+            // Check the writer schema: an empty COUNT projection cannot 
legitimize missing data.
+            require(remaining_rows == 0 || zero_width(schema.root()),
+                    "Truncated Avro deflate block");
+            return;
+        }
+        auto workspace_lease = workspace(256 * 1024);
+        z_stream stream {};
+        require(inflateInit2(&stream, -15) == Z_OK, "Cannot initialize Avro 
deflate decoder");
+        std::unique_ptr<z_stream, decltype(&inflateEnd)> cleanup(&stream, 
&inflateEnd);
+        std::array<uint8_t, 64 * 1024> chunk;
+        size_t offset = 0;
+        int result = Z_OK;
+        while (result != Z_STREAM_END) {

Review Comment:
   [P2] Observe scanner stop during Avro block expansion
   
   If another scanner satisfies LIMIT after this scanner buffers a large 
compressed OCF block, `FileScannerV2::try_stop` signals the scanner but this 
loop keeps inflating and retaining the entire output. The row and byte caps are 
checked outside `hasMoreBefore()`, so they cannot bound this work. Zstandard 
has the same gap. Check the existing stop signal between codec chunks and 
periodically while decoding or skipping large collections. Preserve the normal 
EOF behavior when a scan stops after LIMIT.



-- 
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]

Reply via email to