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


##########
be/src/format_v2/table/load_reader.cpp:
##########
@@ -96,7 +96,10 @@ Status LoadTableReader::init(TableReadOptions&& options) {
                               .scanner_profile = options.scanner_profile,
                               .file_slot_descs = &_source_file_slots,
                               .push_down_agg_type = TPushAggOp::NONE,
-                              .condition_cache_digest = 0});
+                              .condition_cache_digest = 0,
+                              // This wrapper owns the VARCHAR source tuple; 
preserve that fact
+                              // when rebuilding options instead of inheriting 
query cast rules.
+                              .is_load_source = true});

Review Comment:
   [P1] Preserve nested string values through Avro loads
   
   Load an Avro field of type `array<string>` containing one string whose 
characters are `a","b` into an `ARRAY<STRING>` column. The FE uses a VARCHAR 
source slot, so `LoadTableReader` casts the decoded array to text before the 
destination cast. The nested string serializer writes the raw bytes between 
quotes, producing `["a","b"]`. The destination parser accepts that as two 
elements and the load can commit the altered row even in strict mode. Preserve 
the nested value through a typed source slot or a lossless encoding that the 
destination parser understands, and cover this case through the load entry 
point.



##########
be/src/format_v2/avro/avro_reader.cpp:
##########
@@ -0,0 +1,1450 @@
+// 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, bool iceberg_compatible) {
+    // Outside Iceberg, field-id and element-id are arbitrary Avro application 
metadata.
+    // A string label must not reject a valid ordinary Avro file.
+    if (!iceberg_compatible) {
+        return Status::OK();
+    }
+    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 iceberg_compatible,
+                    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, 
iceberg_compatible,
+                                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 (!iceberg_compatible) {
+            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,
+                                             iceberg_compatible, ancestors, 
&child));
+                RETURN_IF_ERROR(set_identifier(node, i, "field-id", &child, 
iceberg_compatible));
+                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);
+            if (is_logical_map(node)) {
+                const auto entry = resolved_node(node->leafAt(0));
+                if (entry->type() != ::avro::AVRO_RECORD || entry->leaves() != 
2 ||
+                    entry->nameAt(0) != "key" || entry->nameAt(1) != "value") {
+                    return Status::InvalidArgument("Invalid Avro logical map 
entry schema");
+                }
+                ColumnDefinition entries;
+                RETURN_IF_ERROR(build_schema(entry, "entry", 0, timestamp_tz, 
varbinary,
+                                             iceberg_compatible, ancestors, 
&entries));
+                column->children = std::move(entries.children);
+            } else {
+                for (size_t i = 0; std::cmp_less(i, (map ? 2 : 1)); ++i) {
+                    ColumnDefinition child;
+                    RETURN_IF_ERROR(build_schema(node->leafAt(i),
+                                                 map ? (i == 0 ? "key" : 
"value") : "element",
+                                                 static_cast<int32_t>(i), 
timestamp_tz, varbinary,
+                                                 iceberg_compatible, 
ancestors, &child));
+                    RETURN_IF_ERROR(set_identifier(
+                            node, 0, map ? (i == 0 ? "key-id" : "value-id") : 
"element-id", &child,
+                            iceberg_compatible));
+                    column->children.push_back(std::move(child));
+                }
+            }
+            type = map ? 
DataTypePtr(std::make_shared<DataTypeMap>(column->children[0].type,
+                                                                   
column->children[1].type))
+                       : 
DataTypePtr(std::make_shared<DataTypeArray>(column->children[0].type));
+            break;
+        }
+        default:
+            return Status::NotSupported("Unsupported Avro schema type");
+        }
+    }
+    column->type = make_nullable(type);
+    return Status::OK();
+}
+
+Status validate_materialized_schema(const ::avro::NodePtr& input) {
+    const auto node = resolved_node(input);
+    if (node->logicalType().type() == ::avro::LogicalType::TIMESTAMP_NANOS) {
+        return Status::NotSupported("Avro timestamp-nanos is unsupported");
+    }
+    for (size_t i = 0; i < node->leaves(); ++i) {
+        RETURN_IF_ERROR(validate_materialized_schema(node->leafAt(i)));
+    }
+    return Status::OK();
+}
+
+const LocalColumnIndex* find_avro_child_projection(const LocalColumnIndex* 
projection,
+                                                   int32_t local_id) {
+    if (projection == nullptr || projection->project_all_children || 
projection->children.empty()) {
+        return nullptr;
+    }
+    const auto found = std::ranges::find_if(
+            projection->children,
+            [local_id](const LocalColumnIndex& child) { return 
child.local_id() == local_id; });
+    return found == projection->children.end() ? nullptr : &*found;
+}
+
+void normalize_avro_map_projection(const ::avro::NodePtr& input, 
LocalColumnIndex* projection) {
+    if (projection->project_all_children || projection->children.empty()) {
+        return;
+    }
+    const auto source = resolved_node(input);
+    if (source->type() == ::avro::AVRO_UNION) {
+        for (size_t i = 0; i < source->leaves(); ++i) {
+            if (source->leafAt(i)->type() != ::avro::AVRO_NULL) {
+                normalize_avro_map_projection(source->leafAt(i), projection);
+            }
+        }
+        return;
+    }
+    const bool logical_map = is_logical_map(source);
+    if (source->type() == ::avro::AVRO_MAP || logical_map) {
+        // MAP keys define entries and retain their complete original type, 
even when only a
+        // value leaf is selected. Keep their schema in the datum and the 
materialization tree.
+        auto key = std::ranges::find_if(projection->children, [](const 
LocalColumnIndex& child) {
+            return child.local_id() == 0;
+        });
+        if (key == projection->children.end()) {
+            projection->children.insert(projection->children.begin(), 
LocalColumnIndex::local(0));
+        } else {
+            key->project_all_children = true;
+        }
+    }
+    if (logical_map) {
+        normalize_avro_map_projection(source->leafAt(0), projection);
+        return;
+    }
+    for (auto& child : projection->children) {
+        normalize_avro_map_projection(source->leafAt(child.local_id()), 
&child);
+    }
+}
+
+struct AvroProjectionContext {
+    std::unordered_map<const ::avro::Node*,
+                       std::unordered_map<const LocalColumnIndex*, 
::avro::NodePtr>>
+            copies;
+    size_t next_name = 0;
+};
+
+::avro::NodePtr clone_projected_schema(const ::avro::NodePtr& input, 
AvroProjectionContext* context,
+                                       const LocalColumnIndex* projection = 
nullptr,
+                                       bool root = false);
+
+void clone_projected_children(const ::avro::NodePtr& source, const 
::avro::NodePtr& result,
+                              AvroProjectionContext* context, const 
LocalColumnIndex* projection) {
+    if (source->type() == ::avro::AVRO_RECORD) {
+        const auto add = [&](size_t i, const LocalColumnIndex* child) {
+            result->addLeaf(clone_projected_schema(source->leafAt(i), context, 
child));
+            result->addName(source->nameAt(i));
+        };
+        if (projection != nullptr) {
+            for (const auto& child : projection->children) {
+                add(child.local_id(), &child);
+            }
+        } else {
+            for (size_t i = 0; i < source->leaves(); ++i) {
+                add(i, nullptr);
+            }
+        }
+    } else if (source->type() == ::avro::AVRO_UNION) {
+        // Null-first datum schemas avoid constructing a large value just to 
read a NULL.
+        const bool swap = source->leaves() == 2 && source->leafAt(1)->type() 
== ::avro::AVRO_NULL;
+        for (size_t i = 0; i < source->leaves(); ++i) {
+            result->addLeaf(
+                    clone_projected_schema(source->leafAt(swap ? 1 - i : i), 
context, projection));
+        }
+    } else if (source->type() == ::avro::AVRO_ARRAY) {
+        result->addLeaf(clone_projected_schema(
+                source->leafAt(0), context,
+                is_logical_map(source) ? projection : 
find_avro_child_projection(projection, 0)));
+    } else if (source->type() == ::avro::AVRO_MAP) {
+        result->addLeaf(clone_projected_schema(source->leafAt(1), context,
+                                               
find_avro_child_projection(projection, 1)));
+    }
+}
+
+::avro::NodePtr clone_projected_schema(const ::avro::NodePtr& input, 
AvroProjectionContext* context,
+                                       const LocalColumnIndex* projection, 
bool root) {
+    const auto source = resolved_node(input);
+    if (!root && (projection == nullptr || projection->project_all_children ||
+                  (projection->children.empty() && 
!projection->read_null_only))) {
+        projection = nullptr;
+    }
+    auto& copies = context->copies[source.get()];
+    if (const auto found = copies.find(projection); found != copies.end()) {
+        return found->second;
+    }
+    ::avro::NodePtr result;
+    switch (source->type()) {
+    case ::avro::AVRO_RECORD:
+        result = std::make_shared<::avro::NodeRecord>();
+        break;
+    case ::avro::AVRO_ENUM:
+        result = std::make_shared<::avro::NodeEnum>();
+        break;
+    case ::avro::AVRO_FIXED:
+        result = std::make_shared<::avro::NodeFixed>();
+        break;
+    case ::avro::AVRO_ARRAY:
+        result = std::make_shared<::avro::NodeArray>();
+        break;
+    case ::avro::AVRO_MAP:
+        result = std::make_shared<::avro::NodeMap>();
+        break;
+    case ::avro::AVRO_UNION:
+        result = std::make_shared<::avro::NodeUnion>();
+        break;
+    default:
+        result = std::make_shared<::avro::NodePrimitive>(source->type());
+        break;
+    }
+    copies.emplace(projection, result);
+    if (source->hasName()) {
+        // Avro's validator aliases equal fullnames to the first definition. 
One writer record
+        // reused as a.x and b.y needs two distinct decoder shapes, so give 
clones internal names.
+        result->setName(::avro::Name(source->name().fullname() + 
"__doris_projection_" +
+                                     std::to_string(context->next_name++)));
+    }
+    if (source->type() == ::avro::AVRO_FIXED) {
+        result->setFixedSize(source->fixedSize());
+    }
+    clone_projected_children(source, result, context, projection);
+    if (source->type() == ::avro::AVRO_ENUM) {
+        for (size_t i = 0; i < source->names(); ++i) {
+            result->addName(source->nameAt(i));
+        }
+    }
+    result->setLogicalType(source->logicalType());
+    return result;
+}
+
+void apply_timestamp_projection(ColumnDefinition* column, const 
LocalColumnIndex& projection) {
+    if (projection.timestamp_is_adjusted_to_utc.has_value()) {
+        column->timestamp_is_adjusted_to_utc = 
projection.timestamp_is_adjusted_to_utc;
+    }
+    for (const auto& child_projection : projection.children) {
+        for (auto& child : column->children) {
+            if (child.local_id == child_projection.local_id()) {
+                apply_timestamp_projection(&child, child_projection);
+                break;
+            }
+        }
+    }
+}
+
+Status append_decimal(const std::vector<uint8_t>& bytes, const DataTypePtr& 
type, IColumn* column) {
+    // Avro decimals are signed, big-endian two's-complement integers, 
including FIXED values.
+    size_t start = 0;
+    // FIXED may be wider than its precision requires; discard only redundant 
sign extension.
+    while (start + 1 < bytes.size() && ((bytes[start] == 0 && (bytes[start + 
1] & 0x80) == 0) ||
+                                        (bytes[start] == 255 && (bytes[start + 
1] & 0x80) != 0))) {
+        ++start;
+    }
+    if (bytes.empty() || bytes.size() - start > 32) {
+        return Status::InvalidArgument("Invalid Avro decimal width");
+    }
+    Int256 value = (bytes[start] & 0x80) != 0 ? -1 : 0;
+    for (; start < bytes.size(); ++start) {
+        value = value * 256 + bytes[start];
+    }
+    Int256 limit = 1;
+    for (unsigned i = 0; i < type->get_precision(); ++i) {
+        limit *= 10;
+    }
+    if (value <= -limit || value >= limit) {
+        return Status::InvalidArgument("Avro decimal exceeds its precision");
+    }
+    switch (type->get_primitive_type()) {
+    case TYPE_DECIMAL32:
+        
column->insert(Field::create_field<TYPE_DECIMAL32>(Decimal32(static_cast<int32_t>(value))));
+        break;
+    case TYPE_DECIMAL64:
+        
column->insert(Field::create_field<TYPE_DECIMAL64>(Decimal64(static_cast<int64_t>(value))));
+        break;
+    case TYPE_DECIMAL128I:
+        column->insert(
+                
Field::create_field<TYPE_DECIMAL128I>(Decimal128V3(static_cast<int128_t>(value))));
+        break;
+    case TYPE_DECIMAL256:
+        
column->insert(Field::create_field<TYPE_DECIMAL256>(Decimal256(value)));
+        break;
+    default:
+        return Status::InternalError("Invalid Avro decimal output type");
+    }
+    return Status::OK();
+}
+
+Status rebase_hybrid_day(int64_t* day) {
+    if (*day >= -141427) {
+        return Status::OK();
+    }
+    // Hive's hybrid 1582-10-04 is epoch day -141428. Reinterpret its Julian 
civil date;
+    // subtracting ten days would be wrong for older centuries and Julian leap 
years.
+    if (*day < -719530) {
+        return Status::InvalidArgument("Avro date is out of range");
+    }
+    const int64_t c = *day + 2440588 + 32082;
+    const int64_t d = (4 * c + 3) / 1461;
+    const int64_t e = c - 1461 * d / 4;
+    const int64_t m = (5 * e + 2) / 153;
+    const int64_t year = d - 4800 + m / 10;
+    const int64_t month = m + 3 - 12 * (m / 10);
+    const int64_t dom = e - (153 * m + 2) / 5 + 1;
+    DateV2Value<DateV2ValueType> first;
+    if (!first.check_range_and_set_time(static_cast<uint16_t>(year), 
static_cast<uint8_t>(month), 1,
+                                        0, 0, 0, 0)) {
+        return Status::InvalidArgument("Avro date is out of range");
+    }
+    // Hive normalizes Julian-only leap days through a lenient Gregorian 
calendar.
+    *day = first.daynr() + dom - 1 - 719528;
+    return Status::OK();
+}
+
+// One visitor preserves the same null/child-offset rules for all Avro value 
alternatives.
+// 
NOLINTNEXTLINE(readability-function-size,readability-function-cognitive-complexity)
+Status append_value(const ::avro::GenericDatum& datum, const ColumnDefinition& 
schema,
+                    IColumn* output, const DataTypePtr& output_type,
+                    const AvroTemporalPolicy& temporal) {
+    if (datum.type() == ::avro::AVRO_NULL) {
+        output->insert_default();
+        return Status::OK();
+    }
+    auto& nullable = assert_cast<ColumnNullable&>(*output);
+    auto* column = &nullable.get_nested_column();
+    // A load and an Iceberg scan may carry the same adjusted marker but use 
different physical
+    // types. Insert the representation selected by the actual file block, 
including nested leaves.
+    const auto type = remove_nullable(output_type);
+    const auto& timezone = temporal.timezone;
+    const bool legacy_calendar = temporal.legacy_calendar;
+    using Logical = ::avro::LogicalType;
+    const auto logical = datum.logicalType().type();
+    if (logical == Logical::DECIMAL) {
+        const auto& bytes = datum.type() == ::avro::AVRO_FIXED
+                                    ? 
datum.value<::avro::GenericFixed>().value()
+                                    : datum.value<std::vector<uint8_t>>();
+        // Hive 3 exposes FIXED decimals as BINARY; the adapter selects that 
raw file-block
+        // type before mapping. Other decimal projections retain logical 
decimal decoding.
+        if (temporal.hive_compatible && datum.type() == ::avro::AVRO_FIXED &&
+            type->get_primitive_type() == TYPE_VARBINARY) {
+            column->insert_data(reinterpret_cast<const char*>(bytes.data()), 
bytes.size());
+        } else {
+            RETURN_IF_ERROR(append_decimal(bytes, type, column));
+        }
+    } else if (logical == Logical::UUID) {
+        UUIDValueType value;
+        if (datum.type() == ::avro::AVRO_FIXED) {
+            const auto& bytes = datum.value<::avro::GenericFixed>().value();
+            if (bytes.size() != UUIDValue::BINARY_LENGTH) {
+                return Status::InvalidArgument("Invalid Avro UUID width");
+            }
+            value = UUIDValue::from_big_endian(bytes.data());
+        } else if (!UUIDValue::from_string(value, datum.value<std::string>())) 
{
+            return Status::InvalidArgument("Invalid Avro UUID value");
+        }
+        column->insert(Field::create_field<TYPE_UUID>(value));
+    } else if (logical == Logical::DATE) {
+        DateV2Value<DateV2ValueType> date;
+        int64_t day = datum.value<int32_t>();
+        // Day -141428 means 1582-10-14 in standard Avro and 1582-10-04 in 
Hive 2.
+        // Without a writer marker, rebasing either interpretation can 
silently change the date.
+        if (temporal.ambiguous_calendar && day < -141427) {
+            return Status::NotSupported(
+                    "Ambiguous Hive Avro date calendar without writer 
metadata");
+        }
+        if (legacy_calendar) {
+            RETURN_IF_ERROR(rebase_hybrid_day(&day));
+        }
+        day += 719528;
+        if (day < 0 || !date.get_date_from_daynr(day)) {
+            return Status::InvalidArgument("Avro date is out of range");
+        }
+        column->insert(Field::create_field<TYPE_DATEV2>(date));
+    } else if (logical == Logical::TIME_MILLIS || logical == 
Logical::TIME_MICROS) {
+        const int64_t micros = logical == Logical::TIME_MILLIS
+                                       ? 
static_cast<int64_t>(datum.value<int32_t>()) * 1000
+                                       : datum.value<int64_t>();
+        if (micros < 0 || micros >= 86400000000LL) {
+            return Status::InvalidArgument("Avro time is out of range");
+        }
+        
column->insert(Field::create_field<TYPE_TIMEV2>(static_cast<double>(micros)));
+    } else if (logical == Logical::TIMESTAMP_NANOS) {
+        // An unsupported instant must never reach civil nanosecond 
materialization.
+        return Status::NotSupported("Avro timestamp-nanos is unsupported");
+    } else if (logical == Logical::LOCAL_TIMESTAMP_NANOS) {
+        column->insert(
+                
Field::create_field<TYPE_TIMESTAMP_NS>(TimeStampNsValue(datum.value<int64_t>())));
+    } else if (logical == Logical::TIMESTAMP_MILLIS || logical == 
Logical::TIMESTAMP_MICROS ||
+               logical == Logical::LOCAL_TIMESTAMP_MILLIS ||
+               logical == Logical::LOCAL_TIMESTAMP_MICROS) {
+        const int64_t units =
+                logical == Logical::TIMESTAMP_MILLIS || logical == 
Logical::LOCAL_TIMESTAMP_MILLIS
+                        ? 1000
+                        : 1000000;
+        const auto raw = datum.value<int64_t>();
+        int64_t seconds = raw / units;
+        int64_t fraction = raw % units;
+        if (fraction < 0) {
+            --seconds;
+            fraction += units;
+        }
+        const bool adjusted = schema.timestamp_is_adjusted_to_utc.value_or(
+                logical == Logical::TIMESTAMP_MILLIS || logical == 
Logical::TIMESTAMP_MICROS);
+        // Unread timestamps, NULLs and COUNT carriers never perform the 
unsupported conversion.
+        if (temporal.legacy_conversion && adjusted) {
+            return Status::NotSupported("Legacy Hive Avro timezone conversion 
is unsupported");
+        }
+        if (temporal.legacy_timezone && adjusted && seconds < -2208988800LL) {
+            // Metadata-free Hive 2 timestamps use Java's pre-1900 raw-offset 
rules; applying
+            // historical tzdb LMT would silently change the civil clock (e.g. 
by 238s in New York).
+            return Status::NotSupported(
+                    "Hive Avro timestamps before 1900 without writer timezone 
are unsupported");
+        }
+        // Hive's fallback zone belongs to its reader JVM, not the Doris query 
session.
+        // An unmarked epoch-zero timestamp needs an explicit policy to select 
civil midnight.
+        if (temporal.ambiguous_timezone && adjusted) {
+            return Status::NotSupported(
+                    "Hive Avro timestamp timezone requires writer metadata or "
+                    "hive.avro.timestamp.skip.conversion=true");
+        }
+        if (seconds < -62167305600LL || seconds > 253402387199LL) {
+            return Status::InvalidArgument("Avro timestamp is out of range");
+        }
+        DateV2Value<DateTimeV2ValueType> value;
+        // Local timestamps encode a civil clock. UTC is only its arithmetic 
epoch anchor;
+        // applying the session zone would change that clock (for example 
00:00 into 08:00).
+        const auto zone = adjusted && type->get_primitive_type() != 
TYPE_TIMESTAMPTZ
+                                  ? timezone
+                                  : cctz::utc_time_zone();
+        // DateTimeV2's fractional argument is nanoseconds, even when the 
output scale is six.
+        value.from_unixtime(seconds, static_cast<int32_t>(fraction * 
(1000000000 / units)), zone,
+                            6);
+        if (!value.is_valid_date()) {
+            return Status::InvalidArgument("Avro timestamp is out of range");
+        }
+        // A known UTC timezone does not establish the writer's pre-cutover 
calendar.
+        if (temporal.ambiguous_calendar && value.daynr() - 719528 < -141427) {
+            return Status::NotSupported(
+                    "Ambiguous Hive Avro timestamp calendar requires writer 
metadata");
+        }
+        if (legacy_calendar) {
+            // Restore the writer-zone civil clock first, then rebase its 
calendar date.
+            int64_t day = value.daynr() - 719528;
+            RETURN_IF_ERROR(rebase_hybrid_day(&day));
+            DateV2Value<DateV2ValueType> date;
+            if (!date.get_date_from_daynr(day + 719528)) {
+                return Status::InvalidArgument("Avro timestamp is out of 
range");
+            }
+            value.unchecked_set_time(date.year(), date.month(), date.day(), 
value.hour(),
+                                     value.minute(), value.second(), 
value.microsecond());
+        }
+        if (type->get_primitive_type() == TYPE_TIMESTAMPTZ) {
+            
column->insert(Field::create_field<TYPE_TIMESTAMPTZ>(TimestampTzValue(value)));
+        } else {
+            column->insert(Field::create_field<TYPE_DATETIMEV2>(value));
+        }
+    } else {
+        switch (datum.type()) {
+        case ::avro::AVRO_BOOL:
+            
column->insert(Field::create_field<TYPE_BOOLEAN>(datum.value<bool>()));
+            break;
+        case ::avro::AVRO_INT:
+            
column->insert(Field::create_field<TYPE_INT>(datum.value<int32_t>()));
+            break;
+        case ::avro::AVRO_LONG:
+            
column->insert(Field::create_field<TYPE_BIGINT>(datum.value<int64_t>()));
+            break;
+        case ::avro::AVRO_FLOAT:
+            
column->insert(Field::create_field<TYPE_FLOAT>(datum.value<float>()));
+            break;
+        case ::avro::AVRO_DOUBLE:
+            
column->insert(Field::create_field<TYPE_DOUBLE>(datum.value<double>()));
+            break;
+        case ::avro::AVRO_STRING: {
+            const auto& value = datum.value<std::string>();
+            column->insert_data(value.data(), value.size());
+            break;
+        }
+        case ::avro::AVRO_ENUM: {
+            const auto& value = datum.value<::avro::GenericEnum>().symbol();
+            column->insert_data(value.data(), value.size());
+            break;
+        }
+        case ::avro::AVRO_BYTES:
+        case ::avro::AVRO_FIXED: {
+            const auto& value = datum.type() == ::avro::AVRO_FIXED
+                                        ? 
datum.value<::avro::GenericFixed>().value()
+                                        : datum.value<std::vector<uint8_t>>();
+            column->insert_data(reinterpret_cast<const char*>(value.data()), 
value.size());
+            break;
+        }
+        case ::avro::AVRO_RECORD: {
+            const auto& record = datum.value<::avro::GenericRecord>();
+            // A missing payload.k may need only payload's presence. Its empty 
decoder record
+            // skips every sibling value; the scalar carrier preserves just 
the parent null map.
+            if (type->get_primitive_type() == TYPE_BOOLEAN) {
+                DCHECK_EQ(record.fieldCount(), 0);
+                column->insert_default();
+                break;
+            }
+            auto& target = assert_cast<ColumnStruct&>(*column);
+            for (size_t i = 0; i < schema.children.size(); ++i) {
+                RETURN_IF_ERROR(append_value(
+                        record.fieldAt(i), schema.children[i], 
&target.get_column(i),
+                        assert_cast<const 
DataTypeStruct&>(*type).get_elements()[i], temporal));
+            }
+            break;
+        }
+        case ::avro::AVRO_ARRAY: {
+            const auto& values = datum.value<::avro::GenericArray>().value();
+            if (type->get_primitive_type() == TYPE_MAP) {
+                auto& target = assert_cast<ColumnMap&>(*column);
+                for (const auto& entry : values) {
+                    const auto& record = entry.value<::avro::GenericRecord>();
+                    RETURN_IF_ERROR(append_value(
+                            record.fieldAt(0), schema.children[0], 
&target.get_keys(),
+                            assert_cast<const 
DataTypeMap&>(*type).get_key_type(), temporal));
+                    RETURN_IF_ERROR(append_value(
+                            record.fieldAt(1), schema.children[1], 
&target.get_values(),
+                            assert_cast<const 
DataTypeMap&>(*type).get_value_type(), temporal));
+                }
+                target.get_offsets().push_back(target.get_keys().size());
+            } else {
+                auto& target = assert_cast<ColumnArray&>(*column);
+                for (const auto& value : values) {
+                    RETURN_IF_ERROR(append_value(
+                            value, schema.children[0], &target.get_data(),
+                            assert_cast<const 
DataTypeArray&>(*type).get_nested_type(), temporal));
+                }
+                target.get_offsets().push_back(target.get_data().size());
+            }
+            break;
+        }
+        case ::avro::AVRO_MAP: {
+            auto& target = assert_cast<ColumnMap&>(*column);
+            for (const auto& [key, value] : 
datum.value<::avro::GenericMap>().value()) {
+                auto& keys = assert_cast<ColumnNullable&>(target.get_keys());
+                keys.get_nested_column().insert_data(key.data(), key.size());
+                keys.get_null_map_data().push_back(0);
+                RETURN_IF_ERROR(append_value(
+                        value, schema.children[1], &target.get_values(),
+                        assert_cast<const 
DataTypeMap&>(*type).get_value_type(), temporal));
+            }
+            target.get_offsets().push_back(target.get_keys().size());
+            break;
+        }
+        default:
+            return Status::NotSupported("Unsupported Avro value type");
+        }
+    }
+    nullable.get_null_map_data().push_back(0);
+    return Status::OK();
+}
+
+size_t datum_scratch_bytes(const ::avro::GenericDatum& datum) {
+    // type()/value() unwrap a union, but its std::any-owned wrapper remains 
allocated.
+    const size_t wrapper = datum.isUnion() ? sizeof(::avro::GenericUnion) : 0;
+    switch (datum.type()) {
+    case ::avro::AVRO_STRING:
+        return wrapper + sizeof(std::string) +
+               (datum.value<std::string>().capacity() > 
std::string().capacity()
+                        ? datum.value<std::string>().capacity() + 1
+                        : 0);
+    case ::avro::AVRO_BYTES:
+        return wrapper + sizeof(std::vector<uint8_t>) +
+               datum.value<std::vector<uint8_t>>().capacity();
+    case ::avro::AVRO_FIXED:
+        return wrapper + sizeof(::avro::GenericFixed) +
+               datum.value<::avro::GenericFixed>().value().capacity();
+    case ::avro::AVRO_RECORD: {
+        const auto& record = datum.value<::avro::GenericRecord>();
+        size_t bytes =
+                wrapper + sizeof(record) + record.fieldCount() * 
sizeof(::avro::GenericDatum);
+        for (size_t i = 0; i < record.fieldCount(); ++i) {
+            bytes += datum_scratch_bytes(record.fieldAt(i));
+        }
+        return bytes;
+    }
+    case ::avro::AVRO_ARRAY: {
+        const auto& array = datum.value<::avro::GenericArray>().value();
+        size_t bytes = wrapper + sizeof(::avro::GenericArray) +
+                       array.capacity() * sizeof(::avro::GenericDatum);
+        for (const auto& value : array) {
+            bytes += datum_scratch_bytes(value);
+        }
+        return bytes;
+    }
+    case ::avro::AVRO_MAP: {
+        const auto& map = datum.value<::avro::GenericMap>().value();
+        size_t bytes = wrapper + sizeof(::avro::GenericMap) +
+                       map.capacity() * 
sizeof(std::remove_reference_t<decltype(map)>::value_type);
+        for (const auto& [key, value] : map) {
+            bytes += key.capacity() + datum_scratch_bytes(value);
+        }
+        return bytes;
+    }
+    case ::avro::AVRO_ENUM:
+        return wrapper + sizeof(::avro::GenericEnum);
+    default:
+        return wrapper;
+    }
+}
+
+} // namespace
+
+struct AvroReader::Impl {
+    std::shared_ptr<MemTrackerLimiter> memory_tracker;
+    DorisVector<ReservedMemoryToken> reservations;
+    int64_t accounted_scratch = 0;
+    size_t schema_scratch = 0;
+    RuntimeProfile::Counter* scratch_accounting_passes = nullptr;
+    RuntimeProfile::Counter* total_time = nullptr;
+    RuntimeProfile::Counter* decode_materialize_time = nullptr;
+    RuntimeProfile::Counter* filter_time = nullptr;
+    size_t small_reservation_available = 0;
+    size_t collection_scratch_before_reset = 0;
+
+    static void reserve_callback(void* context, size_t bytes) {
+        auto* self = static_cast<Impl*>(context);
+        if (bytes > static_cast<size_t>(std::numeric_limits<int64_t>::max())) {
+            throw Exception(ErrorCode::MEM_LIMIT_EXCEEDED, "Avro allocation 
exceeds Int64");
+        }
+        if (bytes <= self->small_reservation_available) {
+            self->small_reservation_available -= bytes;
+            return;
+        }
+        // Batch tiny std::any allocations so large nullable arrays do not 
acquire one token per item.
+        const size_t reservation = std::max(bytes, size_t(64 * 1024));
+        auto* manager = thread_context()->thread_mem_tracker_mgr.get();
+        // Preserve the scanner's existing reservation; each Avro growth owns 
an independent token.
+        auto previous = manager->take_reserved_memory();
+        Defer restore([&] { 
manager->adopt_reserved_memory(std::move(previous)); });
+        const auto status = 
manager->try_reserve(static_cast<int64_t>(reservation));
+        if (!status.ok()) {
+            throw Exception(status);
+        }
+        self->reservations.push_back(manager->take_reserved_memory());
+        if (bytes < reservation) {
+            self->small_reservation_available = reservation - bytes;
+        }
+    }
+
+    static std::shared_ptr<void> reserve_workspace(size_t bytes) {
+        if (bytes > static_cast<size_t>(std::numeric_limits<int64_t>::max())) {
+            throw Exception(ErrorCode::MEM_LIMIT_EXCEEDED, "Avro codec 
workspace exceeds Int64");
+        }
+        auto* manager = thread_context()->thread_mem_tracker_mgr.get();
+        auto previous = manager->take_reserved_memory();
+        Defer restore([&] { 
manager->adopt_reserved_memory(std::move(previous)); });
+        const auto status = manager->try_reserve(static_cast<int64_t>(bytes));
+        if (!status.ok()) {
+            throw Exception(status);
+        }
+        // Codec contexts die at block/frame boundaries, including when no row 
is produced.
+        return 
std::make_shared<ReservedMemoryToken>(manager->take_reserved_memory());
+    }
+
+    static void checkpoint_callback(void* context, const ::avro::GenericDatum& 
collection,
+                                    bool before) {
+        auto* self = static_cast<Impl*>(context);
+        const size_t retained = datum_scratch_bytes(collection);
+        if (before) {
+            self->collection_scratch_before_reset = retained;
+        } else {
+            // Collection resets and switches to null release 
previously-accounted children.
+            // The decoder suppresses union checkpoints for newly constructed 
branches.
+            const auto released =
+                    static_cast<int64_t>(self->collection_scratch_before_reset 
- retained);
+            DCHECK_LE(released, self->accounted_scratch);
+            self->memory_tracker->release(released);
+            self->accounted_scratch -= released;
+        }
+    }
+
+    void reconcile_scratch() {
+        if (scratch_accounting_passes != nullptr) {
+            COUNTER_UPDATE(scratch_accounting_passes, 1);
+        }
+        const size_t retained =
+                schema_scratch + (reader ? reader->scratchBytes() : 0) +
+                (datum ? sizeof(::avro::GenericDatum) + 
datum_scratch_bytes(*datum) : 0);
+        // Replace conservative transient-growth reservations with retained 
capacities after every
+        // record. Retained codec and datum buffers remain charged between 
batches until close.
+        memory_tracker->consume(static_cast<int64_t>(retained) - 
accounted_scratch);
+        accounted_scratch = static_cast<int64_t>(retained);
+        reservations.clear();
+        small_reservation_available = 0;
+    }
+
+    Status prepare_projection(const FileScanRequest& request, 
::avro::ValidSchema* result) {
+        projected_ordinals.clear();
+        projected_fields.clear();
+        auto root_projection = LocalColumnIndex::partial_local(-1);
+        std::unordered_map<int32_t, LocalColumnIndex> projections;
+        for (const auto* columns : {&request.predicate_columns, 
&request.non_predicate_columns}) {
+            for (const auto& candidate : *columns) {
+                auto [found, inserted] = 
projections.try_emplace(candidate.local_id(), candidate);
+                if (!inserted) {
+                    RETURN_IF_ERROR(merge_local_column_index(&found->second, 
candidate));
+                }
+            }
+        }
+        for (const auto& [id, position] : request.local_positions) {
+            if (id.value() >= 0 && !count_placeholders.contains(id.value())) {
+                if (static_cast<size_t>(id.value()) >= schema.size()) {
+                    return Status::InvalidArgument("Unknown Avro file-local 
column");
+                }
+                // Position-only requests predate nested projection and retain 
a complete root.
+                const auto projection = projections.find(id.value());
+                auto selected = projection == projections.end()
+                                        ? LocalColumnIndex::local(id.value())
+                                        : projection->second;
+                ColumnDefinition field;
+                RETURN_IF_ERROR(project_column_definition(schema[id.value()], 
selected, &field));
+                
normalize_avro_map_projection(reader->dataSchema().root()->leafAt(id.value()),
+                                              &selected);
+                RETURN_IF_ERROR(project_column_definition(schema[id.value()], 
selected, &field));
+                projected_fields.emplace(id.value(), std::move(field));
+                root_projection.children.push_back(std::move(selected));
+            }
+        }
+        std::ranges::sort(root_projection.children, {}, 
&LocalColumnIndex::index);
+        for (size_t i = 0; i < root_projection.children.size(); ++i) {
+            projected_ordinals.emplace(root_projection.children[i].local_id(), 
i);
+        }
+        AvroProjectionContext projection_context;
+        ::avro::ValidSchema projected_schema(clone_projected_schema(
+                reader->dataSchema().root(), &projection_context, 
&root_projection, true));
+        // Admission follows required leaves, including for empty files. A 
full user STRUCT still
+        // requests every child; hidden equality keys may omit unrelated 
unsupported siblings.
+        RETURN_IF_ERROR(validate_materialized_schema(projected_schema.root()));

Review Comment:
   [P2] Read only parent presence for default-only Iceberg output structs
   
   An old Iceberg v3 Avro file can have a nullable `payload` containing only 
`clock: timestamptz_ns`. Drop `clock` and add `payload.k INT` with initial 
default 7. `SELECT payload` should return a struct with `k=7` for present 
parents and NULL for absent parents. With no matching child, 
`TableColumnMapper` keeps the full old file subtree. This validation then 
rejects the dropped `clock` field. Use a nullability-only projection for 
ordinary default-only STRUCT outputs when the reader supports it, and test both 
present and NULL parents. This path needs no equality delete.



##########
be/src/format_v2/avro/avro_container_reader.cpp:
##########
@@ -0,0 +1,1312 @@
+// 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());
+    // 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));
+    // Unread roots never materialize Hive's truncation or padding semantics.
+    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");
+}
+
+// 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;
+    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_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) {
+            if (stream.avail_in == 0) {
+                const size_t length = 
std::min<size_t>(std::numeric_limits<uInt>::max(),
+                                                       compressed.size() - 
offset);
+                stream.next_in = compressed.data() + offset;
+                stream.avail_in = static_cast<uInt>(length);
+                offset += length;
+            }
+            stream.next_out = chunk.data();
+            stream.avail_out = chunk.size();
+            const auto before = stream.avail_in;
+            result = inflate(&stream, Z_NO_FLUSH);
+            require(result == Z_OK || result == Z_STREAM_END || result == 
Z_BUF_ERROR,
+                    "Invalid Avro deflate block");
+            const auto produced = chunk.size() - stream.avail_out;
+            append(chunk.data(), produced);
+            // zlib can consume the last input byte while a MATCH still has 
pending output.
+            // Only completion or a no-progress iteration can terminate the 
drain.
+            require(result == Z_STREAM_END || before != stream.avail_in || 
produced != 0,
+                    "Truncated Avro deflate block");
+        }
+        require(result == Z_STREAM_END && stream.avail_in == 0 && offset == 
compressed.size(),
+                "Truncated Avro deflate block");
+    }
+
+    void decompress() {
+        SCOPED_TIMER(decompress_time);
+        const auto found = metadata.find("avro.codec");
+        const auto codec = found == metadata.end() ? "null" : found->second;
+        uncompressed.clear();
+        if (codec == "null") {
+            compressed.swap(uncompressed);
+        } else if (codec == "snappy") {
+            decompress_snappy();
+        } else if (codec == "zstandard") {
+            decompress_zstandard();
+        } else if (codec == "deflate") {
+            decompress_deflate();
+        } else {
+            throw Exception(ErrorCode::NOT_IMPLEMENTED_ERROR, "Unsupported 
Avro codec: {}", codec);
+        }
+        data = {.data = uncompressed.data(), .length = uncompressed.size(), 
.position = 0};
+    }
+
+    void append(const uint8_t* bytes, size_t count) {
+        require(count <= std::numeric_limits<size_t>::max() - 
uncompressed.size(),
+                "Avro decompression size overflows");
+        grow_buffer(uncompressed, uncompressed.size() + count);
+        uncompressed.insert(uncompressed.end(), bytes, bytes + count);
+    }
+
+    // Decode only selected values; skipping a writer field never constructs 
GenericDatum trees.
+    // 
NOLINTNEXTLINE(readability-function-size,readability-function-cognitive-complexity)
+    void read_value(const ::avro::NodePtr& input, ::avro::GenericDatum* datum, 
bool retained = true,
+                    const ::avro::NodePtr* projected_node = nullptr) {
+        const auto node = resolved(input);
+        switch (node->type()) {
+        case ::avro::AVRO_NULL:
+            break;
+        case ::avro::AVRO_BOOL: {
+            const auto value = data.byte();
+            require(value <= 1, "Invalid Avro boolean");
+            if (datum) {
+                datum->value<bool>() = value;
+            }
+            break;
+        }
+        case ::avro::AVRO_INT: {
+            const auto value = read_long(data);
+            require(value >= std::numeric_limits<int32_t>::min() &&
+                            value <= std::numeric_limits<int32_t>::max(),
+                    "Avro int overflows");
+            if (datum) {
+                datum->value<int32_t>() = static_cast<int32_t>(value);
+            }
+            break;
+        }
+        case ::avro::AVRO_LONG: {
+            const auto value = read_long(data);
+            if (datum) {
+                datum->value<int64_t>() = value;
+            }
+            break;
+        }
+        case ::avro::AVRO_FLOAT:
+        case ::avro::AVRO_DOUBLE: {
+            uint64_t bits = 0;
+            const size_t length = node->type() == ::avro::AVRO_FLOAT ? 4 : 8;
+            for (size_t i = 0; i < length; ++i) {
+                bits |= uint64_t(data.byte()) << (8 * i);
+            }
+            if (datum) {
+                if (length == 4) {
+                    datum->value<float>() = 
std::bit_cast<float>(static_cast<uint32_t>(bits));
+                } else {
+                    datum->value<double>() = std::bit_cast<double>(bits);
+                }
+            }
+            break;
+        }
+        case ::avro::AVRO_STRING:
+        case ::avro::AVRO_BYTES:
+        case ::avro::AVRO_FIXED: {
+            const int64_t length = node->type() == ::avro::AVRO_FIXED
+                                           ? 
static_cast<int64_t>(node->fixedSize())
+                                           : read_long(data);
+            require(length >= 0, "Invalid Avro value length");
+            if (datum == nullptr) {
+                data.skip(length);
+            } else if (node->type() == ::avro::AVRO_STRING) {
+                auto& value = datum->value<std::string>();
+                growth(value.capacity(), length);
+                require(static_cast<uint64_t>(length) <= data.remaining(), 
"Truncated Avro string");
+                value.resize(length);
+                data.read(value.data(), length);
+            } else {
+                auto& value = node->type() == ::avro::AVRO_FIXED
+                                      ? 
datum->value<::avro::GenericFixed>().value()
+                                      : datum->value<std::vector<uint8_t>>();
+                growth(value.capacity(), length);
+                require(static_cast<uint64_t>(length) <= data.remaining(), 
"Truncated Avro bytes");
+                value.resize(length);
+                data.read(value.data(), length);
+            }
+            break;
+        }
+        case ::avro::AVRO_ENUM: {
+            const auto index = read_long(data);
+            require(index >= 0 && static_cast<uint64_t>(index) < node->names(),
+                    "Invalid Avro enum");
+            if (datum) {
+                datum->value<::avro::GenericEnum>().set(index);
+            }
+            break;
+        }
+        case ::avro::AVRO_UNION: {
+            const auto index = read_long(data);
+            require(index >= 0 && static_cast<uint64_t>(index) < 
node->leaves(),
+                    "Invalid Avro union");
+            // Projected datum unions are null-first; encoded indices always 
belong to the
+            // writer schema, including for nested collection elements and 
named records.
+            const auto datum_index =
+                    node->leaves() == 2 && node->leafAt(1)->type() == 
::avro::AVRO_NULL ? 1 - index
+                                                                               
         : index;
+            if (datum && datum->unionBranch() != 
static_cast<size_t>(datum_index)) {
+                const bool releases_old =
+                        retained && node->leafAt(index)->type() == 
::avro::AVRO_NULL;
+                if (releases_old) {
+                    checkpoint(*datum, true);
+                }
+                // Selecting a nullable projected STRUCT constructs only its 
requested children.
+                // Charging the writer's full branch would reject an unused 
large FIXED sibling.
+                reserve(datum_size((*projected_node)->leafAt(datum_index)));
+                datum->selectBranch(datum_index);
+                if (releases_old) {
+                    checkpoint(*datum, false);
+                }
+                retained = false;
+            }
+            read_value(node->leafAt(index), datum, retained,
+                       datum == nullptr ? nullptr : 
&(*projected_node)->leafAt(datum_index));
+            break;
+        }
+        case ::avro::AVRO_RECORD: {
+            const auto* projection =
+                    datum == nullptr
+                            ? nullptr
+                            : &record_projections.at(
+                                      
datum->value<::avro::GenericRecord>().schema().get());
+            for (size_t i = 0; i < node->leaves(); ++i) {
+                const auto ordinal = projection == nullptr ? -1 : 
(*projection)[i];
+                read_value(node->leafAt(i),
+                           ordinal < 0 ? nullptr
+                                       : 
&datum->value<::avro::GenericRecord>().fieldAt(ordinal),
+                           retained,
+                           ordinal < 0 ? nullptr
+                                       : 
&datum->value<::avro::GenericRecord>().schema()->leafAt(
+                                                 ordinal));
+            }
+            break;
+        }
+        case ::avro::AVRO_ARRAY:
+        case ::avro::AVRO_MAP: {
+            const bool map = node->type() == ::avro::AVRO_MAP;
+            const auto child = node->leafAt(map ? 1 : 0);
+            auto projected_child = child;
+            if (datum != nullptr) {
+                projected_child = map ? 
datum->value<::avro::GenericMap>().schema()->leafAt(1)
+                                      : 
datum->value<::avro::GenericArray>().schema()->leafAt(0);
+            }
+            if (datum) {
+                checkpoint(*datum, true);
+                if (map) {
+                    datum->value<::avro::GenericMap>().value().clear();
+                } else {
+                    datum->value<::avro::GenericArray>().value().clear();
+                }
+                checkpoint(*datum, false);
+            }
+            std::optional<bool> zero_width_child;
+            for (int64_t count = read_long(data); count != 0; count = 
read_long(data)) {
+                std::optional<size_t> block_end;
+                if (count < 0) {
+                    require(count != std::numeric_limits<int64_t>::min(),
+                            "Invalid Avro collection count");
+                    count = -count;
+                    const auto bytes = read_long(data);
+                    require(bytes >= 0 && static_cast<uint64_t>(bytes) <= 
data.remaining(),
+                            "Invalid Avro collection block size");
+                    block_end = data.position + bytes;
+                    if (datum == nullptr) {
+                        data.skip(bytes);
+                        continue;
+                    }
+                }
+                // A 128-null-field record can span millions of positive 
blocks with the same
+                // item schema. Cache its zero-width result lazily so empty 
arrays and negative
+                // blocks with byte extents still skip without traversing that 
schema.
+                if (datum == nullptr && !map) {
+                    if (!zero_width_child.has_value()) {
+                        zero_width_child = zero_width(child);
+                    }
+                    if (*zero_width_child) {
+                        continue;
+                    }
+                }
+                if (datum == nullptr) {
+                    require(static_cast<uint64_t>(count) <= data.remaining(),
+                            "Truncated Avro collection");
+                }
+                if (datum) {
+                    growth(0, count, std::max(size_t(1), 
datum_size(projected_child)));
+                    auto admit = [&](auto& values) {
+                        using Value =
+                                typename 
std::remove_reference_t<decltype(values)>::value_type;
+                        
static_assert(std::is_nothrow_move_constructible_v<Value>);
+                        const auto maximum = std::min(
+                                values.max_size(),
+                                size_t(std::numeric_limits<int64_t>::max()) / 
2 / sizeof(Value));
+                        require(static_cast<uint64_t>(count) <= maximum - 
values.size(),
+                                "Avro collection count overflows");
+                        const auto size = values.size() + count;
+                        // Thousands of one-item blocks must not copy and 
admit the entire prefix
+                        // on each append. Retain only the capacity delta; the 
temporary old-buffer
+                        // lease covers overlap during reallocation and 
expires when it is freed.
+                        if (size > values.capacity()) {
+                            const auto capacity =
+                                    values.capacity() +
+                                    std::min(values.capacity(), maximum - 
values.capacity());
+                            const auto target = std::max(size, capacity);
+                            const auto old_bytes = values.capacity() * 
sizeof(Value);
+                            auto old_buffer = old_bytes == 0 ? nullptr : 
workspace(old_bytes);
+                            reserve((target - values.capacity()) * 
sizeof(Value));
+                            values.reserve(target);
+                        }
+                    };
+                    if (map) {
+                        admit(datum->value<::avro::GenericMap>().value());
+                    } else {
+                        admit(datum->value<::avro::GenericArray>().value());
+                    }
+                }
+                for (int64_t i = 0; i < count; ++i) {
+                    if (map) {
+                        if (datum) {
+                            auto& values = 
datum->value<::avro::GenericMap>().value();
+                            auto key = read_string(data);
+                            values.emplace_back(std::move(key),
+                                                
::avro::GenericDatum(projected_child));
+                            read_value(child, &values.back().second, false, 
&projected_child);
+                        } else {
+                            const auto length = read_long(data);
+                            require(length >= 0, "Invalid Avro map key 
length");
+                            data.skip(length);
+                            read_value(child, nullptr);
+                        }
+                    } else if (datum) {
+                        auto& values = 
datum->value<::avro::GenericArray>().value();
+                        values.emplace_back(projected_child);
+                        read_value(child, &values.back(), false, 
&projected_child);
+                    } else {
+                        read_value(child, nullptr);
+                    }
+                }
+                require(!block_end || *block_end == data.position,
+                        "Avro collection block size mismatch");
+            }
+            break;
+        }
+        default:
+            throw Exception(ErrorCode::INVALID_ARGUMENT, "Unsupported Avro 
value");
+        }
+    }
+};
+
+AvroContainerReader::AvroContainerReader(io::FileReaderSPtr file,
+                                         std::shared_ptr<io::IOContext> 
context, Reserve reserve,
+                                         Checkpoint checkpoint, Workspace 
workspace,
+                                         RuntimeProfile* profile, bool 
iceberg_compatible)
+        : _impl(std::make_unique<Impl>(std::move(file), std::move(context), 
std::move(reserve),
+                                       std::move(checkpoint), 
std::move(workspace), profile,
+                                       iceberg_compatible)) {}
+AvroContainerReader::~AvroContainerReader() = default;
+
+const ::avro::ValidSchema& AvroContainerReader::dataSchema() const {
+    return _impl->schema;
+}
+
+void AvroContainerReader::validate_read_schema(const std::string& json,
+                                               const std::string& 
projected_schema) const {
+    const auto limit = (std::numeric_limits<size_t>::max() - 
_impl->schema_charge) / 32;
+    require(json.size() <= limit && projected_schema.size() <= limit - 
json.size(),
+            "Avro reader schema allocation overflows");
+    // Hold admission through compilation AND comparison, including temporary 
field-name indexes.
+    auto workspace =
+            _impl->workspace((json.size() + projected_schema.size()) * 32 + 
_impl->schema_charge);
+    const auto projected =
+            compile_physical_schema(projected_schema.empty() ? json : 
projected_schema, true);
+    require(projected.root()->type() == ::avro::AVRO_RECORD,
+            "Hive Avro projection must be a record");
+    std::unordered_set<std::string> required_fields;
+    for (size_t i = 0; i < projected.root()->leaves(); ++i) {
+        // HMS may retain name STRING after ALTER installs a literal Name 
VARCHAR(2).
+        // Annotation admission follows normalized slot selection; Avro 
resolution stays exact.
+        required_fields.insert(folded_name(projected.root()->nameAt(i)));
+    }
+    // Coercion belongs to the effective reader. Writer-only CHAR annotations 
do not truncate
+    // an HMS STRING ("abcd" remains "abcd"); physical/logical compatibility 
is checked below.
+    const auto reader_schema =
+            projected_schema.empty() ? projected
+                                     : compile_physical_schema(json, true, 
false, &required_fields);
+    // An implicit Hive foo has a NULL default when the writer only has Foo. 
Folding this
+    // boundary would bind the writer value before the normalized slot mapper 
can see it.
+    validate_schema_pair(_impl->schema.root(), reader_schema.root(), 0, false, 
false);
+    if (!projected_schema.empty()) {
+        // Skipping a reader INT->FLOAT promotion before a DOUBLE output would 
skip rounding.
+        // Every projected field must exist with the same value interpretation 
in the reader.
+        validate_schema_pair(reader_schema.root(), projected.root(), 0, true, 
true);
+    }
+}
+
+std::optional<std::string> AvroContainerReader::metadata(const std::string& 
key) const {
+    const auto found = _impl->metadata.find(key);
+    return found == _impl->metadata.end() ? std::nullopt : 
std::optional(found->second);
+}
+
+size_t AvroContainerReader::scratchBytes() const {
+    size_t bytes = sizeof(Impl) + _impl->compressed.capacity() + 
_impl->uncompressed.capacity() +
+                   _impl->schema_charge + _impl->datum_sizes.size() * 64 +
+                   _impl->projection_charge + _impl->file.scratch_bytes();
+    for (const auto& [key, value] : _impl->metadata) {

Review Comment:
   [P2] Account for immutable Avro header metadata once
   
   `AvroReader::get_block` calls `reconcile_scratch()` after each decoded row, 
including physical COUNT scans. This loop walks every metadata entry each time. 
A valid one-million-row OCF with 1,000 small user metadata keys therefore makes 
about a billion metadata visits after parsing its header once. The constructor 
is the only writer of the map. Cache the header’s retained byte total there and 
reuse it in `scratchBytes()`.



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