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


##########
be/src/format_v2/avro/avro_reader.cpp:
##########
@@ -0,0 +1,1434 @@
+// 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_reader.h"
+
+#include <algorithm>
+#include <array>
+#include <avro/Generic.hh>
+#include <avro/NodeImpl.hh>
+#include <charconv>
+#include <limits>
+#include <mutex>
+#include <string_view>
+#include <type_traits>
+#include <unordered_set>
+#include <utility>
+
+#include "common/exception.h"
+#include "core/assert_cast.h"
+#include "core/block/block.h"
+#include "core/column/column_array.h"
+#include "core/column/column_map.h"
+#include "core/column/column_nullable.h"
+#include "core/column/column_struct.h"
+#include "core/column/column_vector.h"
+#include "core/custom_allocator.h"
+#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_date_or_datetime_v2.h"
+#include "core/data_type/data_type_decimal.h"
+#include "core/data_type/data_type_map.h"
+#include "core/data_type/data_type_nothing.h"
+#include "core/data_type/data_type_nullable.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "core/data_type/data_type_struct.h"
+#include "core/data_type/data_type_time.h"
+#include "core/data_type/data_type_timestamp_ns.h"
+#include "core/data_type/data_type_timestamptz.h"
+#include "core/data_type/data_type_uuid.h"
+#include "core/data_type/data_type_varbinary.h"
+#include "core/value/timestamp_ns_value.h"
+#include "core/value/timestamptz_value.h"
+#include "format_v2/avro/avro_container_reader.h"
+#include "format_v2/column_mapper.h"
+#include "format_v2/materialized_reader_util.h"
+#include "format_v2/schema_projection.h"
+#include "io/fs/file_reader.h"
+#include "io/io_common.h"
+#include "runtime/file_scan_profile.h"
+#include "runtime/memory/mem_tracker_limiter.h"
+#include "runtime/memory/thread_mem_tracker_mgr.h"
+#include "runtime/runtime_state.h"
+#include "runtime/thread_context.h"
+#include "storage/utils.h"
+#include "util/string_util.h"
+#include "util/timezone_utils.h"
+
+namespace doris::format::avro {
+namespace {
+
+::avro::NodePtr resolved_node(const ::avro::NodePtr& node) {
+    return node->type() == ::avro::AVRO_SYMBOLIC ? ::avro::resolveSymbol(node) 
: node;
+}
+
+struct AvroTemporalPolicy {
+    cctz::time_zone timezone = cctz::utc_time_zone();
+    bool hive_compatible = false;
+    bool legacy_calendar = false;
+    bool ambiguous_calendar = false;
+    bool legacy_timezone = false;
+    bool ambiguous_timezone = false;
+    bool legacy_conversion = false;
+};
+
+bool parse_writer_timezone(const std::string& name, cctz::time_zone* zone) {
+    std::string_view offset(name);
+    bool prefixed = false;
+    if (offset.starts_with("GMT") || offset.starts_with("UTC")) {
+        offset.remove_prefix(3);
+        prefixed = true;
+    } else if (offset.starts_with("UT")) {
+        offset.remove_prefix(2);
+        prefixed = true;
+    }
+    if ((prefixed && offset.empty()) || name == "Z") {
+        *zone = cctz::utc_time_zone();
+        return true;
+    }
+    if (offset.empty()) {
+        return false;
+    }
+    if (offset.front() != '+' && offset.front() != '-') {
+        // Hive emits normalized Java ZoneIds. Use named TZDB rules without 
SQL-only aliases.
+        return cctz::load_time_zone(name, zone);
+    }
+    const bool negative = offset.front() == '-';
+    offset.remove_prefix(1);
+    auto parse = [](std::string_view part, int* value) {
+        if (part.empty() || part.size() > 2 ||
+            !std::ranges::all_of(part, [](char c) { return c >= '0' && c <= 
'9'; })) {
+            return false;
+        }
+        const auto result = std::from_chars(part.data(), part.data() + 
part.size(), *value);
+        return result.ec == std::errc() && result.ptr == part.data() + 
part.size();
+    };
+    int hours = 0, minutes = 0, seconds = 0;
+    const auto colon = offset.find(':');
+    if (!parse(offset.substr(0, colon), &hours)) {
+        return false;
+    }
+    if (colon != std::string_view::npos) {
+        offset.remove_prefix(colon + 1);
+        const auto second_colon = offset.find(':');
+        const auto minute = offset.substr(0, second_colon);
+        if (minute.size() != 2 || !parse(minute, &minutes)) {
+            return false;
+        }
+        if (second_colon != std::string_view::npos) {
+            const auto second = offset.substr(second_colon + 1);
+            if (second.size() != 2 || !parse(second, &seconds)) {
+                return false;
+            }
+        }
+    }
+    // Java ZoneOffset permits +/-18h, unlike the SQL session's -12h/+14h 
setting.
+    if (hours > 18 || minutes > 59 || seconds > 59 ||
+        (hours == 18 && (minutes != 0 || seconds != 0))) {
+        return false;
+    }
+    const int total = (negative ? -1 : 1) * (hours * 3600 + minutes * 60 + 
seconds);
+    *zone = TimezoneUtils::create_fixed_offset_time_zone(total);
+    return true;
+}
+
+constexpr size_t MAX_SCHEMA_BYTES = 64 * 1024 * 1024;
+
+size_t schema_cost_add(size_t current, size_t count, size_t copies = 1) {
+    if (current > MAX_SCHEMA_BYTES || count > (MAX_SCHEMA_BYTES - current) / 
copies) {
+        throw Exception(ErrorCode::NOT_IMPLEMENTED_ERROR,
+                        "Expanded Avro schema size is unsupported");
+    }
+    return current + count * copies;
+}
+
+Status init_hive_temporal_policy(const AvroContainerReader& reader,
+                                 const io::FileSystemProperties& 
system_properties,
+                                 AvroTemporalPolicy* temporal) {
+    const auto zone = reader.metadata("writer.time.zone");
+    if (zone && !parse_writer_timezone(*zone, &temporal->timezone)) {
+        return Status::InvalidArgument("Invalid Avro writer timezone");
+    }
+    const auto& properties = system_properties.properties;
+    const auto skip = properties.find("hive.avro.timestamp.skip.conversion");
+    const bool skip_conversion = skip != properties.end() && 
iequal(skip->second, "true");
+    if (skip != properties.end() && !skip_conversion && !iequal(skip->second, 
"false")) {
+        return Status::InvalidArgument("Invalid Hive Avro timestamp 
skip-conversion policy");
+    }
+    temporal->ambiguous_timezone = !zone.has_value() && !skip_conversion;
+    // Explicit UTC needs no historical JVM offset lookup (for example, 
1899-01-01).
+    temporal->legacy_timezone = temporal->ambiguous_timezone;
+    if (!zone.has_value() && skip_conversion) {
+        // An explicit Hive skip-conversion policy uses UTC; writer.time.zone 
wins if present.
+        temporal->timezone = cctz::utc_time_zone();
+    }
+    const auto proleptic = reader.metadata("writer.proleptic");
+    if (proleptic && *proleptic != "true" && *proleptic != "false") {
+        return Status::InvalidArgument("Invalid Avro writer calendar");
+    }
+    // Standard Avro and Hive 2 can both omit the markers but use different 
calendars.
+    // Hive 3 writes its zone; Hive 4 records the calendar choice explicitly.
+    temporal->legacy_calendar = proleptic && *proleptic == "false";
+    temporal->ambiguous_calendar = !proleptic.has_value() && !zone.has_value();
+    // Hive 4 writes this marker even for INT-only files; only a timestamp 
value uses it.
+    temporal->legacy_conversion = 
reader.metadata("writer.zone.conversion.legacy") == "true";
+    return Status::OK();
+}
+
+struct SchemaCost {
+    size_t retained = 1024;
+    // Copies share DataTypePtr but own ColumnDefinition vectors, names and 
string identifiers.
+    size_t copy = 2 * sizeof(ColumnDefinition);
+};
+
+SchemaCost expanded_schema_cost(const ::avro::NodePtr& input,
+                                std::unordered_map<const ::avro::Node*, 
SchemaCost>* sizes,
+                                std::unordered_set<const ::avro::Node*>* 
ancestors) {
+    const auto node = resolved_node(input);
+    if (ancestors->size() >= 64 || !ancestors->insert(node.get()).second) {
+        throw Exception(ErrorCode::NOT_IMPLEMENTED_ERROR,
+                        "Recursive or excessively nested Avro schemas are 
unsupported");
+    }
+    Defer pop([&] { ancestors->erase(node.get()); });
+    if (const auto found = sizes->find(node.get()); found != sizes->end()) {
+        return found->second;
+    }
+    SchemaCost cost;
+    for (size_t i = 0; i < node->leaves(); ++i) {
+        const auto child = expanded_schema_cost(node->leafAt(i), sizes, 
ancestors);
+        const auto name_bytes = node->type() == ::avro::AVRO_RECORD ? 
node->nameAt(i).size() : 0;
+        cost.copy = schema_cost_add(cost.copy, child.copy);
+        cost.copy = schema_cost_add(cost.copy, name_bytes, 2);
+        cost.retained = schema_cost_add(cost.retained, child.retained);
+        cost.retained = schema_cost_add(cost.retained, name_bytes, 6);
+        // Each mapped ancestor owns original/projected child trees. Filter 
localization and
+        // projection rebuilds overlap deep mapping snapshots, so their cost 
grows with depth.
+        // The envelope covers 32 subtree copies per enclosing level, 
including predicate maps.
+        cost.retained = schema_cost_add(cost.retained, child.copy, 32);
+    }
+    sizes->emplace(node.get(), cost);
+    return cost;
+}
+
+std::string lowercase(std::string name) {
+    for (auto& c : name) {
+        if (c >= 'A' && c <= 'Z') {
+            c += 'a' - 'A';
+        }
+    }
+    return name;
+}
+
+Status set_identifier(const ::avro::NodePtr& node, size_t attributes_index, 
const char* attribute,
+                      ColumnDefinition* column) {
+    if (attributes_index >= node->customAttributes()) {
+        return Status::OK();
+    }
+    const auto value = 
node->customAttributesAt(attributes_index).getAttribute(attribute);
+    if (!value.has_value()) {
+        return Status::OK();
+    }
+    int32_t id = 0;
+    const auto parsed = std::from_chars(value->data(), value->data() + 
value->size(), id);
+    if (parsed.ec != std::errc() || parsed.ptr != value->data() + 
value->size() || id <= 0) {
+        return Status::InvalidArgument("Invalid Avro field identifier");
+    }
+    column->identifier = Field::create_field<TYPE_INT>(id);
+    return Status::OK();
+}
+
+bool is_logical_map(const ::avro::NodePtr& node) {
+    const auto logical = node->logicalType();
+    return node->type() == ::avro::AVRO_ARRAY && logical.type() == 
::avro::LogicalType::CUSTOM &&
+           logical.customLogicalType()->name() == "map";
+}
+
+// Keep logical and physical alternatives in one visitor so nullable handling 
is shared.
+// 
NOLINTNEXTLINE(readability-function-size,readability-function-cognitive-complexity)
+Status build_schema(const ::avro::NodePtr& input, const std::string& name, 
int32_t ordinal,
+                    bool timestamp_tz, bool varbinary, bool 
defer_unsupported_nanos,
+                    std::unordered_set<const ::avro::Node*>* ancestors, 
ColumnDefinition* column) {
+    const auto node = resolved_node(input);
+    // A recursive Avro record cannot be represented by a finite Doris STRUCT 
type.
+    if (ancestors->size() >= 64 || !ancestors->insert(node.get()).second) {
+        return Status::NotSupported("Recursive or excessively nested Avro 
schemas are unsupported");
+    }
+    struct Pop {
+        std::unordered_set<const ::avro::Node*>* nodes;
+        const ::avro::Node* node;
+        ~Pop() { nodes->erase(node); }
+    } pop {.nodes = ancestors, .node = node.get()};
+    if (node->leaves() > 
static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
+        return Status::NotSupported("Avro schema has too many fields");
+    }
+    column->name = lowercase(name);
+    column->local_id = ordinal;
+    column->identifier = Field::create_field<TYPE_STRING>(column->name);
+    if (node->type() == ::avro::AVRO_UNION) {
+        ::avro::NodePtr value;
+        for (size_t i = 0; i < node->leaves(); ++i) {
+            if (node->leafAt(i)->type() != ::avro::AVRO_NULL) {
+                if (value != nullptr) {
+                    return Status::NotSupported(
+                            "Avro unions with multiple non-null types are 
unsupported");
+                }
+                value = node->leafAt(i);
+            }
+        }
+        if (value != nullptr) {
+            return build_schema(value, name, ordinal, timestamp_tz, varbinary,
+                                defer_unsupported_nanos, ancestors, column);
+        }
+        column->type = make_nullable(std::make_shared<DataTypeString>());
+        return Status::OK();
+    }
+
+    DataTypePtr type;
+    const auto logical = node->logicalType();
+    using Logical = ::avro::LogicalType;
+    switch (logical.type()) {
+    case Logical::DECIMAL:
+        if (logical.precision() > 76) {
+            return Status::NotSupported("Avro decimal precision exceeds 76");
+        }
+        type = create_decimal(logical.precision(), logical.scale(), false);
+        break;
+    case Logical::UUID:
+        type = std::make_shared<DataTypeUUID>();
+        break;
+    case Logical::DATE:
+        type = std::make_shared<DataTypeDateV2>();
+        break;
+    case Logical::TIME_MILLIS:
+    case Logical::TIME_MICROS:
+        type = std::make_shared<DataTypeTimeV2>(logical.type() == 
Logical::TIME_MILLIS ? 3 : 6);
+        break;
+    case Logical::TIMESTAMP_NANOS:
+        // TIMESTAMP_NS is a civil clock and TIMESTAMPTZ retains only 
microseconds. Neither can
+        // represent a nanosecond UTC instant without losing timezone 
semantics or precision.
+        if (!defer_unsupported_nanos) {
+            return Status::NotSupported("Avro timestamp-nanos is unsupported");
+        }
+        // Iceberg already marks this column unsupported. Publish no value 
representation so
+        // other roots can be scanned; open() rejects a projection that 
actually needs this leaf.
+        type = std::make_shared<DataTypeNothing>();
+        break;
+    case Logical::LOCAL_TIMESTAMP_NANOS:
+        type = std::make_shared<DataTypeTimeStampNs>();
+        column->timestamp_is_adjusted_to_utc = logical.type() == 
Logical::TIMESTAMP_NANOS;
+        break;
+    case Logical::TIMESTAMP_MILLIS:
+    case Logical::TIMESTAMP_MICROS:
+    case Logical::LOCAL_TIMESTAMP_MILLIS:
+    case Logical::LOCAL_TIMESTAMP_MICROS: {
+        const bool adjusted = logical.type() == Logical::TIMESTAMP_MILLIS ||
+                              logical.type() == Logical::TIMESTAMP_MICROS;
+        const int scale = logical.type() == Logical::TIMESTAMP_MILLIS ||
+                                          logical.type() == 
Logical::LOCAL_TIMESTAMP_MILLIS
+                                  ? 3
+                                  : 6;
+        type = timestamp_tz && adjusted ? 
DataTypePtr(std::make_shared<DataTypeTimeStampTz>(scale))
+                                        : 
DataTypePtr(std::make_shared<DataTypeDateTimeV2>(scale));
+        column->timestamp_is_adjusted_to_utc = adjusted;
+        break;
+    }
+    default:
+        break;
+    }
+    if (type == nullptr) {
+        switch (node->type()) {
+        case ::avro::AVRO_NULL:
+            type = std::make_shared<DataTypeString>();
+            break;
+        case ::avro::AVRO_BOOL:
+            type = std::make_shared<DataTypeUInt8>();
+            break;
+        case ::avro::AVRO_INT:
+            type = std::make_shared<DataTypeInt32>();
+            break;
+        case ::avro::AVRO_LONG:
+            type = std::make_shared<DataTypeInt64>();
+            break;
+        case ::avro::AVRO_FLOAT:
+            type = std::make_shared<DataTypeFloat32>();
+            break;
+        case ::avro::AVRO_DOUBLE:
+            type = std::make_shared<DataTypeFloat64>();
+            break;
+        case ::avro::AVRO_BYTES:
+        case ::avro::AVRO_FIXED:
+            type = varbinary ? 
DataTypePtr(std::make_shared<DataTypeVarbinary>())
+                             : DataTypePtr(std::make_shared<DataTypeString>());
+            break;
+        case ::avro::AVRO_STRING:
+        case ::avro::AVRO_ENUM:
+            type = std::make_shared<DataTypeString>();
+            break;
+        case ::avro::AVRO_RECORD: {
+            DataTypes types;
+            Strings names;
+            std::unordered_set<std::string> field_names;
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                // Avro distinguishes Foo from foo, but Doris maps both 
through lowercase keys.
+                // Reject collisions within this record before publishing an 
ambiguous STRUCT.
+                if (!field_names.insert(lowercase(node->nameAt(i))).second) {
+                    return Status::NotSupported(
+                            "Avro record has ambiguous case-insensitive field 
names");
+                }
+                ColumnDefinition child;
+                RETURN_IF_ERROR(build_schema(node->leafAt(i), node->nameAt(i),
+                                             static_cast<int32_t>(i), 
timestamp_tz, varbinary,
+                                             defer_unsupported_nanos, 
ancestors, &child));
+                RETURN_IF_ERROR(set_identifier(node, i, "field-id", &child));
+                types.push_back(child.type);
+                names.push_back(child.name);
+                column->children.push_back(std::move(child));
+            }
+            if (types.empty()) {
+                // A nested STRUCT needs a child column to retain its row 
count.
+                return Status::NotSupported(
+                        "Nested empty Avro records cannot be represented as a 
Doris STRUCT");
+            }
+            type = std::make_shared<DataTypeStruct>(types, names);
+            break;
+        }
+        case ::avro::AVRO_ARRAY:
+        case ::avro::AVRO_MAP: {
+            const bool map = node->type() == ::avro::AVRO_MAP || 
is_logical_map(node);

Review Comment:
   [P2] Scope Iceberg’s logical map to Iceberg reads
   
   An ordinary Avro file with 
`{"type":"array","items":"int","logicalType":"map"}` should expose its 
underlying ARRAY in an S3 TVF. The process-wide registration makes 
`is_logical_map()` true during schema inference, so `build_schema()` rejects 
this valid file with `Invalid Avro logical map entry schema`. A 
compatible-looking key/value record array can instead appear as MAP. Gate the 
extension on the Iceberg read context and add a normal TVF inference control 
that still passes after an Iceberg read registers the logical type. [Avro 
logical 
types](https://avro.apache.org/docs/1.12.0/specification/#logical-types).



##########
be/src/format_v2/avro/avro_container_reader.cpp:
##########
@@ -0,0 +1,1291 @@
+// 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;
+}
+
+// Writer defaults never appear on the wire. Avro C++ eagerly builds their 
GenericDatum values
+// and assumes union branch zero, rejecting legal null defaults on later 
branches. Strip only
+// record-field defaults before compiling a physical schema; retain all types 
and logical metadata.
+void strip_field_defaults(rapidjson::Value& value, bool hive_validation,
+                          bool check_string_coercion = true,
+                          const std::unordered_set<std::string>* 
required_fields = nullptr) {
+    if (value.IsArray()) {
+        for (auto& child : value.GetArray()) {
+            strip_field_defaults(child, hive_validation, 
check_string_coercion);
+        }
+    } else if (value.IsObject()) {
+        if (hive_validation && value.HasMember("logicalType") && 
value["logicalType"].IsString()) {
+            const std::string_view logical(value["logicalType"].GetString(),
+                                           
value["logicalType"].GetStringLength());
+            // Hive compares decimal/char/varchar with Java equalsIgnoreCase. 
Reject non-ASCII
+            // spellings too, whose Unicode case equivalence the native 
compiler does not share.
+            require(std::ranges::all_of(logical, [](unsigned char c) { return 
c < 128; }),
+                    "Non-ASCII Hive Avro logical annotation is unsupported");
+            const auto folded = folded_name(std::string(logical));
+            // Skipped columns never materialize Hive's truncation/padding 
semantics. Preserve
+            // full-schema structural validation while checking coercion only 
on required roots.
+            require(!check_string_coercion || (folded != "char" && folded != 
"varchar"),
+                    "Hive Avro char/varchar coercion is unsupported");
+            require(folded != "decimal" || logical == "decimal",
+                    "Noncanonical Hive Avro decimal annotation is 
unsupported");
+        }
+        if (value.HasMember("fields") && value["fields"].IsArray()) {
+            for (auto& field : value["fields"].GetArray()) {
+                if (field.IsObject()) {
+                    field.RemoveMember("default");
+                    if (field.HasMember("type")) {
+                        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);
+                    }
+                }
+            }
+        }
+        for (const auto* key : {"type", "items", "values"}) {
+            if (value.HasMember(key)) {
+                strip_field_defaults(value[key], 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_iceberg_timestamps(rapidjson::Value& schema) {
+    // 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_iceberg_timestamps(branch);
+        }
+        return;
+    }
+    if (!schema.IsObject()) {
+        return;
+    }
+    auto type = schema.FindMember("type");
+    if (type == schema.MemberEnd()) {
+        return;
+    }
+    if (!type->value.IsString()) {
+        normalize_iceberg_timestamps(type->value);
+        return;
+    }
+    const std::string_view physical_type(type->value.GetString(), 
type->value.GetStringLength());
+    if (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") {
+        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_iceberg_timestamps(field_type->value);
+                    }
+                }
+            }
+        }
+    } else if (physical_type == "array" || physical_type == "map") {
+        const auto child = schema.FindMember(physical_type == "array" ? 
"items" : "values");
+        if (child != schema.MemberEnd()) {
+            normalize_iceberg_timestamps(child->value);
+        }
+    }
+}
+
+::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);
+    // The Iceberg extension must not change ordinary Avro or Hive instant 
semantics.
+    if (iceberg_compatible) {
+        normalize_iceberg_timestamps(document);
+    }
+    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,
+                          bool match_record_names, 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,
+                          bool match_record_names, size_t depth, bool 
exact_value_types,
+                          bool normalized_projection) {
+    require(!match_record_names || from->name() == to->name(),

Review Comment:
   [P2] Accept Hive-compatible root record names in explicit Avro schemas
   
   A Hive 3.1.3 file whose root record is `before` and contains `id=7` can be 
read through an explicit Hive reader literal named `after` with 
`id:["null","int"]` and `default:null`. The FE admits that literal. Hive 
re-encodes through `GenericDatumReader`, and its Avro 1.8.2 resolver matches 
record fields by name without comparing the root record names. Doris rejects 
the file here before comparing `id`. Preserve Hive’s root record behavior while 
retaining exact field-name resolution and the separate FIXED and ENUM name 
checks. Update the different-root-name control in `avro_reader_test.cpp`. [Hive 
3.1.3 
reader](https://github.com/apache/hive/blob/rel/release-3.1.3/serde/src/java/org/apache/hadoop/hive/serde2/avro/AvroDeserializer.java#L102-L125),
 [Avro 1.8.2 
resolver](https://github.com/apache/avro/blob/release-1.8.2/lang/java/avro/src/main/java/org/apache/avro/io/parsing/ResolvingGrammarGenerator.java#L199-L272).



##########
be/src/format_v2/table/iceberg_reader.cpp:
##########
@@ -2201,93 +2250,133 @@ Status 
IcebergTableReader::_build_missing_equality_delete_key_expr(
     return Status::OK();
 }
 
-Status 
IcebergTableReader::_append_equality_delete_predicates(format::FileScanRequest* 
request) {
-    DORIS_CHECK(request != nullptr);
+Status IcebergTableReader::_collect_equality_delete_columns(
+        format::FileScanRequest* request, 
std::vector<format::ColumnDefinition>* projected_schema) {
+    std::unordered_map<int32_t, const format::ColumnDefinition*> roots;
     for (const auto& filter : _equality_delete_filters) {
-        DCHECK_EQ(filter.field_ids.size(), filter.key_types.size());
-        DCHECK_EQ(filter.field_ids.size(), filter.delete_key_types.size());
-        // A delete file without rows deletes nothing, but 
EqualityDeletePredicate evaluates its
-        // keys before it looks at the delete set, so the strict comparison 
casts would still run:
-        // a DATE key 1000-01-01 compared with an empty TIMESTAMP_NS delete 
file fails the scan
-        // with an overflow. It is skipped here rather than at load time, so 
the loaded filter
-        // still disables aggregate pushdown as before.
         if (filter.delete_block.rows() == 0) {
             continue;
         }
-        VExprSPtrs key_exprs;
-        DataTypes comparison_types;
-        bool has_missing_key = false;
         for (size_t idx = 0; idx < filter.field_ids.size(); ++idx) {
             if (filter.key_types[idx]->is_null_literal()) {
-                // Current Iceberg UNKNOWN is NULL even when a same-ID 
physical field exists.
-                // Compare a typed NULL against the tombstones, never the 
ignored physical key.
-                // Dropped historical UNKNOWN keys retain a STRING carrier for 
physical resolution.
-                const auto comparison_type = 
remove_nullable(filter.delete_key_types[idx]);
-                key_exprs.push_back(
-                        
VLiteral::create_shared(make_nullable(comparison_type), Field {}));
-                comparison_types.push_back(comparison_type);
-                has_missing_key = true;
                 continue;
             }
-            EqualityDeleteColumnPath data_path;
-            bool complete_path = false;
+            EqualityDeleteColumnPath path;
+            bool complete = false;
             RETURN_IF_ERROR(_find_equality_delete_data_field(filter, idx, 
_data_reader.file_schema,
-                                                             &data_path, 
&complete_path));
-            VExprSPtr key_expr;
-            DataTypePtr comparison_type;
-            if (!complete_path) {
-                RETURN_IF_ERROR(_build_missing_equality_delete_key_expr(
-                        filter, idx, data_path, request, &key_expr, 
&comparison_type));
-                has_missing_key = true;
-            } else {
-                const auto* root = data_path.front();
-                const auto field_column_id = 
format::LocalColumnId(root->file_local_id());
-                // A hidden key, like the missing key's ancestor above and the 
delete file's keys,
-                // has no ColumnMapping to carry the timestamp marker 
annotate_file_schema() put on
-                // its file column. Without it Parquet decodes an INT96 
timestamptz key as
-                // DATETIMEV2 while the key expression below, built from the 
annotated file schema,
-                // expects TIMESTAMPTZ. A projected key, or a projected 
ancestor of a missing key,
-                // moves into the predicate columns and must keep the marker 
its mapping carried.
+                                                             &path, 
&complete));
+            if (!path.empty()) {
+                roots.try_emplace(path.front()->file_local_id(), path.front());
+                // Missing keys still read their existing ancestor for its 
NULL state. Present
+                // keys need only the leaf; merge every filter before binding 
child ordinals.
                 
RETURN_IF_ERROR(format::FileScanRequestBuilder(request).add_predicate_column(
-                        equality_delete_root_projection(*root)));
-                const auto block_position = 
request->local_positions.at(field_column_id).value();
-                RETURN_IF_ERROR(
-                        build_equality_delete_key_expr(data_path, 
block_position, &key_expr));
-                RETURN_IF_ERROR(equality_delete_comparison_type(
-                        filter.field_ids[idx], filter.delete_key_types[idx], 
key_expr->data_type(),
-                        filter.key_types[idx], _data_file_path(), 
&comparison_type));
-                key_expr = cast_equality_delete_key(std::move(key_expr), 
comparison_type);
+                        complete ? equality_delete_key_projection(path)
+                                 : 
equality_delete_root_projection(*path.front())));

Review Comment:
   [P2] Read only ancestor nullability for a missing nested equality key
   
   Consider an older Iceberg v3 Avro data file with `id` and optional 
`payload{t: timestamptz_ns}`. A later schema adds `payload.k` with initial 
default `7`, and a later equality delete matches `k=7`. `SELECT id` now reaches 
the incomplete-path arm, which requests the whole physical `payload`; 
`_build_missing_equality_delete_key_expr()` also re-adds that full root. Avro 
then rejects the unused `t` with `Avro timestamp-nanos is unsupported`. The 
delete only needs to distinguish a null parent from a present parent with 
default `7`. Keep just the ancestor null state and add an Avro case to the 
existing missing-key/default test. [Iceberg field 
defaults](https://iceberg.apache.org/spec/#default-values).



##########
be/src/format_v2/table_reader.cpp:
##########
@@ -1577,6 +1580,17 @@ Status 
TableReader::create_file_reader(std::unique_ptr<FileReader>* reader) {
                 _current_task->format_split_id, 
_current_task->format_split_id_end);
         return Status::OK();
     }
+    if (_format == FileFormat::AVRO) {
+        // Unlike Parquet and ORC, Avro still selects its binary mapping from 
the scan parameters.
+        const bool enable_mapping_varbinary = _scan_params != nullptr &&
+                                              
_scan_params->__isset.enable_mapping_varbinary &&
+                                              
_scan_params->enable_mapping_varbinary;
+        *reader = std::make_unique<format::avro::AvroReader>(

Review Comment:
   [P2] Normalize default ViewFS paths for ordinary Avro reads
   
   An Iceberg data file can reach this branch with 
`path=viewfs:/warehouse/data.avro` and `fs_name=viewfs://`. The FE preserves 
that URI, and the normal reader passes both fields directly to `FileFactory`. 
Even if it obtains an HDFS handler, `convert_path()` cannot strip `viewfs://` 
from the single-slash URI and hands `/viewfs:/warehouse/data.avro` to the file 
open. Apply `FileFactory::resolve_file_location` to the physical data 
description as the `$position_deletes` reader does, preserving the original 
Iceberg file identity used for delete matching.



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