Gabriel39 commented on code in PR #70808:
URL: https://github.com/apache/doris/pull/70808#discussion_r4662308526
##########
fe/fe-core/src/main/java/org/apache/doris/datasource/property/fileformat/FileFormatProperties.java:
##########
@@ -96,7 +96,7 @@ public static FileFormatProperties
createFileFormatProperties(String formatStrin
case FORMAT_JSON:
return new JsonFileFormatProperties();
case FORMAT_AVRO:
- throw new AnalysisException("Avro file reads are no longer
supported");
+ return new AvroFileFormatProperties();
Review Comment:
Fixed in 66777d0c2a. Reject Avro in the HTTP-stream TVF before planning: its
live pipe cannot provide the seekable, sized file required by the reader.
Seekable Avro inputs and staged ordinary Stream Load remain enabled. Regression
tests cover Avro rejection and existing CSV/JSON support.
##########
be/src/format_v2/avro/avro_container_reader.cpp:
##########
@@ -0,0 +1,1007 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "format_v2/avro/avro_container_reader.h"
+
+#include <rapidjson/document.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+#include <snappy.h>
+#include <zlib.h>
+#define ZSTD_STATIC_LINKING_ONLY
+#include <zstd.h>
+
+#include <algorithm>
+#include <array>
+#include <avro/Compiler.hh>
+#include <avro/Generic.hh>
+#include <avro/NodeImpl.hh>
+#include <bit>
+#include <cstring>
+#include <limits>
+#include <string_view>
+#include <type_traits>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include "common/exception.h"
+#include "io/fs/file_reader.h"
+#include "io/io_common.h"
+#include "runtime/runtime_profile.h"
+
+namespace doris::format::avro {
+namespace {
+
+void require(bool condition, const char* message) {
+ if (!condition) {
+ throw Exception(ErrorCode::INVALID_ARGUMENT, message);
+ }
+}
+
+std::string folded_name(std::string name) {
+ for (auto& c : name) {
+ if (c >= 'A' && c <= 'Z') {
+ c += 'a' - 'A';
+ }
+ }
+ return name;
+}
+
+// Writer defaults never appear on the wire. Avro C++ eagerly builds their
GenericDatum values
+// and assumes union branch zero, rejecting legal null defaults on later
branches. Strip only
+// record-field defaults before compiling a physical schema; retain all types
and logical metadata.
+void strip_field_defaults(rapidjson::Value& value, bool hive_validation) {
+ if (value.IsArray()) {
+ for (auto& child : value.GetArray()) {
+ strip_field_defaults(child, hive_validation);
+ }
+ } else if (value.IsObject()) {
+ if (hive_validation && value.HasMember("logicalType") &&
value["logicalType"].IsString()) {
+ const std::string_view logical(value["logicalType"].GetString(),
+
value["logicalType"].GetStringLength());
+ // Hive compares decimal/char/varchar with Java equalsIgnoreCase.
Reject non-ASCII
+ // spellings too, whose Unicode case equivalence the native
compiler does not share.
+ require(std::ranges::all_of(logical, [](unsigned char c) { return
c < 128; }),
+ "Non-ASCII Hive Avro logical annotation is unsupported");
+ const auto folded = folded_name(std::string(logical));
+ require(folded != "char" && folded != "varchar",
+ "Hive Avro char/varchar coercion is unsupported");
+ require(folded != "decimal" || logical == "decimal",
+ "Noncanonical Hive Avro decimal annotation is
unsupported");
+ }
+ if (value.HasMember("fields") && value["fields"].IsArray()) {
+ for (auto& field : value["fields"].GetArray()) {
+ if (field.IsObject()) {
+ field.RemoveMember("default");
+ if (field.HasMember("type")) {
+ strip_field_defaults(field["type"], hive_validation);
+ }
+ }
+ }
+ }
+ for (const auto* key : {"type", "items", "values"}) {
+ if (value.HasMember(key)) {
+ strip_field_defaults(value[key], hive_validation);
+ }
+ }
+ }
+}
+
+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);
+ }
+ }
+}
+
+rapidjson::Document physical_schema_document(const std::string& json, bool
hive_validation) {
+ // Bound recursion before either JSON parser runs, including header-only
files.
+ size_t depth = 0;
+ bool quoted = false, escaped = false;
+ for (const char c : json) {
+ 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(json.data(), json.size());
+ require(!document.HasParseError(), "Invalid Avro schema JSON");
+ validate_json_keys(document);
+ strip_field_defaults(document, hive_validation);
+ return document;
+}
+
+::avro::ValidSchema compile_physical_schema(const std::string& json, bool
hive_validation = false) {
+ auto document = physical_schema_document(json, hive_validation);
+ rapidjson::StringBuffer output;
+ rapidjson::Writer<rapidjson::StringBuffer> writer(output);
+ require(document.Accept(writer), "Cannot serialize Avro physical schema");
+ return ::avro::compileJsonSchemaFromString(std::string(output.GetString(),
output.GetSize()));
+}
+
+::avro::NodePtr physical_node(const ::avro::NodePtr& input) {
+ return input->type() == ::avro::AVRO_SYMBOLIC ?
::avro::resolveSymbol(input) : input;
+}
+
+::avro::NodePtr non_null_branch(const ::avro::NodePtr& input, bool* nullable) {
+ auto node = physical_node(input);
+ *nullable = node->type() == ::avro::AVRO_NULL;
+ if (node->type() != ::avro::AVRO_UNION) {
+ return node;
+ }
+ ::avro::NodePtr value;
+ for (size_t i = 0; i < node->leaves(); ++i) {
+ auto child = physical_node(node->leafAt(i));
+ if (child->type() == ::avro::AVRO_NULL) {
+ *nullable = true;
+ } else {
+ require(!value, "Reader schema requires unsupported Avro union
resolution");
+ value = std::move(child);
+ }
+ }
+ return value;
+}
+
+void validate_schema_pair(const ::avro::NodePtr& writer, const
::avro::NodePtr& reader,
+ bool match_record_names, size_t depth = 0,
+ bool exact_value_types = false);
+
+void validate_record_pair(const ::avro::NodePtr& from, const ::avro::NodePtr&
to,
+ bool match_record_names, size_t depth, bool
exact_value_types) {
+ require(!match_record_names || from->name() == to->name(),
+ "Avro reader record name resolution is unsupported");
+ std::unordered_set<std::string> reader_names;
+ std::unordered_set<std::string> 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;
+ if (from->nameIndex(to->nameAt(i), writer_index)) {
+ validate_schema_pair(from->leafAt(writer_index), to->leafAt(i),
match_record_names,
+ depth + 1, exact_value_types);
+ continue;
+ }
+ // The mapper is case-insensitive, whereas Avro resolution is exact.
Do not let a
+ // missing nullable reader field bind to a differently-cased writer
field later.
+ if (!indexed_writer_names) {
+ for (size_t j = 0; j < from->leaves(); ++j) {
+ writer_names.insert(folded_name(from->nameAt(j)));
+ }
+ indexed_writer_names = true;
+ }
+ require(!writer_names.contains(folded), "Avro reader field differs
only by case");
+ 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,
+ bool match_record_names, size_t depth, bool
exact_value_types) {
+ 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();
+ // 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");
+ }
+ const auto source = from->type(), target = to->type();
+ 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, match_record_names, depth,
exact_value_types);
+ } 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),
match_record_names,
+ depth + 1, exact_value_types);
+ } 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;
+};
+
+::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<size_t, size_t> selected;
+ 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;
+
+ Impl(io::FileReaderSPtr input, std::shared_ptr<io::IOContext> context,
Reserve allocation,
+ Checkpoint reset, Workspace codec_workspace, RuntimeProfile* profile)
+ : 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)) {
+ 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(),
Review Comment:
Fixed in 66777d0c2a. Bound negative metadata-map blocks while decoding
key/value varints and strings, check lengths before allocation, and require
exact consumption before the next block. A raw-header regression covers
undersized, oversized and valid negative blocks followed by positive metadata.
##########
fe/fe-core/src/main/java/org/apache/doris/common/util/Util.java:
##########
@@ -406,6 +406,9 @@ public static TFileFormatType
getFileFormatTypeFromPath(String path) {
return TFileFormatType.FORMAT_PARQUET;
} else if (lowerCasePath.contains(".orc")) {
return TFileFormatType.FORMAT_ORC;
+ } else if (lowerCasePath.endsWith(".avro")) {
Review Comment:
Fixed in 66777d0c2a. Check the final Avro suffix before the legacy
Parquet/ORC substring branches. Regressions cover both format-like directory
names and earlier suffixes, including mixed-case .AVRO, while existing non-Avro
fallbacks remain covered.
##########
be/src/exec/scan/file_scanner_v2.cpp:
##########
@@ -1111,6 +1111,9 @@ Status
FileScannerV2::_to_file_format(TFileFormatType::type format_type,
case TFileFormatType::FORMAT_ORC:
*file_format = format::FileFormat::ORC;
return Status::OK();
+ case TFileFormatType::FORMAT_AVRO:
Review Comment:
Fixed in 66777d0c2a. Enroll Avro in the existing adaptive-batch allowlist.
The scanner regression verifies its initial probe, learned narrow/wide row
predictions and disabled-setting behavior.
--
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]