Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/iceberg/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ set(ICEBERG_SOURCES
util/mumbling_bitmap.cc
util/murmurhash3_internal.cc
util/property_util.cc
util/reachable_file_util.cc
util/retry_util.cc
util/scheduled_executor.cc
util/snapshot_util.cc
Expand Down
36 changes: 33 additions & 3 deletions src/iceberg/arrow/arrow_io.cc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/

#include <algorithm>
#include <cerrno>
#include <chrono>
#include <limits>
#include <mutex>
Expand All @@ -30,6 +31,7 @@
#include <arrow/io/interfaces.h>
#include <arrow/result.h>
#include <arrow/status.h>
#include <arrow/util/io_util.h>
#include <arrow/util/uri.h>

#include "iceberg/arrow/arrow_io_internal.h"
Expand Down Expand Up @@ -411,6 +413,25 @@ class ArrowPositionOutputStream : public PositionOutputStream {
int64_t closed_position_ = 0;
};

/// \brief True if a status reports that a file does not exist.
///
/// Arrow file systems report a missing file as an IOError with ENOENT, or ENOTDIR if a
/// parent of the path is a file. On Windows,
/// Arrow also maps other errors to ENOENT, such as an unavailable drive or network
/// share, so only the errors for a missing file or path count there.
bool IsFileNotFound(const ::arrow::Status& status) {
const int errnum = ::arrow::internal::ErrnoFromStatus(status);
// ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND and ERROR_DIRECTORY, which Arrow maps to
// ENOENT or ENOTDIR. 0 if there is no Windows error.
const int win_error = ::arrow::internal::WinErrorFromStatus(status);
if (win_error != 0) {
return win_error == 2 || win_error == 3 || win_error == 267;
}
// ENOTDIR reports that a parent of the path is not a directory, so the file
// cannot exist either.
return errnum == ENOENT || errnum == ENOTDIR;
}

class ArrowInputFile : public InputFile {
public:
ArrowInputFile(std::shared_ptr<::arrow::fs::FileSystem> fs, std::string location,
Expand All @@ -427,9 +448,18 @@ class ArrowInputFile : public InputFile {
return *file_size_;
}
::arrow::fs::FileInfo file_info(path_, ::arrow::fs::FileType::File);
ICEBERG_ARROW_ASSIGN_OR_RETURN(auto input, fs_->OpenInputFile(file_info));
ICEBERG_ARROW_ASSIGN_OR_RETURN(auto size, input->GetSize());
return size;
auto input = fs_->OpenInputFile(file_info);
// Callers need to tell a missing file apart from other failures.
if (!input.ok() && IsFileNotFound(input.status())) {
return NotFound("{}", input.status().ToString());
}
ICEBERG_ARROW_RETURN_NOT_OK(input.status());
auto size = input.ValueUnsafe()->GetSize();
if (!size.ok() && IsFileNotFound(size.status())) {
return NotFound("{}", size.status().ToString());
}
ICEBERG_ARROW_RETURN_NOT_OK(size.status());
return size.ValueUnsafe();
}

Result<std::unique_ptr<SeekableInputStream>> Open() override {
Expand Down
156 changes: 142 additions & 14 deletions src/iceberg/avro/avro_reader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ class AvroReadBackend {
const arrow::MetadataColumnContext& metadata_context,
::arrow::ArrayBuilder* builder) = 0;
virtual bool IsPastSync(int64_t split_end) const = 0;
virtual int64_t PreviousSync() const = 0;
virtual const ::avro::Metadata& GetMetadata() const = 0;
virtual const ::avro::ValidSchema& GetReaderSchema() const = 0;
virtual void Close() = 0;
Expand Down Expand Up @@ -145,6 +146,8 @@ class DirectDecoderBackend : public AvroReadBackend {
return reader_->pastSync(split_end);
}

int64_t PreviousSync() const override { return reader_->previousSync(); }

const ::avro::Metadata& GetMetadata() const override { return reader_->metadata(); }

const ::avro::ValidSchema& GetReaderSchema() const override {
Expand All @@ -171,13 +174,16 @@ class GenericDatumBackend : public AvroReadBackend {
public:
Result<::avro::ValidSchema> Init(
std::unique_ptr<AvroInputStream> input_stream) override {
reader_ = std::make_unique<::avro::DataFileReader<::avro::GenericDatum>>(
std::move(input_stream));
return reader_->dataSchema();
// Only read the header here. Avro reads the first block when the reader is
// created, which is deferred to InitWithSchema().
base_ = std::make_unique<::avro::DataFileReaderBase>(std::move(input_stream));
return base_->dataSchema();
}

Status InitWithSchema(const ::avro::ValidSchema& /*file_schema*/,
const std::optional<Split>& split) override {
reader_ =
std::make_unique<::avro::DataFileReader<::avro::GenericDatum>>(std::move(base_));
if (split) {
reader_->sync(split->offset);
}
Expand All @@ -204,6 +210,8 @@ class GenericDatumBackend : public AvroReadBackend {
return reader_->pastSync(split_end);
}

int64_t PreviousSync() const override { return reader_->previousSync(); }

const ::avro::Metadata& GetMetadata() const override { return reader_->metadata(); }

const ::avro::ValidSchema& GetReaderSchema() const override {
Expand All @@ -215,11 +223,14 @@ class GenericDatumBackend : public AvroReadBackend {
reader_->close();
reader_.reset();
}
// Set if opening failed before the reader was created.
base_.reset();
}

bool Closed() const override { return reader_ == nullptr; }

private:
std::unique_ptr<::avro::DataFileReaderBase> base_;
std::unique_ptr<::avro::DataFileReader<::avro::GenericDatum>> reader_;
// Reusable GenericDatum for reading records
std::unique_ptr<::avro::GenericDatum> datum_;
Expand Down Expand Up @@ -317,6 +328,7 @@ class AvroReader::Impl {
auto input_stream,
CreateInputStream(options,
options.properties.Get(ReaderProperties::kAvroBufferSize)));
read_error_ = input_stream->read_error();

// Create the appropriate backend based on configuration
if (options.properties.Get(ReaderProperties::kAvroSkipDatum)) {
Expand All @@ -325,7 +337,17 @@ class AvroReader::Impl {
backend_ = std::make_unique<GenericDatumBackend>();
}

ICEBERG_ASSIGN_OR_RAISE(auto file_schema, backend_->Init(std::move(input_stream)));
// Reading the header throws if the stream fails, so report a read error as such
// instead of as a malformed file.
Result<::avro::ValidSchema> init_result =
InvalidSchema("Avro reader not initialized");
try {
init_result = backend_->Init(std::move(input_stream));
} catch (...) {
ICEBERG_RETURN_UNEXPECTED(CheckOpenReadError(options.path));
throw;
}
ICEBERG_ASSIGN_OR_RAISE(auto file_schema, std::move(init_result));

// Validate field ids in the file schema.
HasIdVisitor has_id_visitor;
Expand Down Expand Up @@ -354,7 +376,41 @@ class AvroReader::Impl {
/*prune_source=*/false, options.id_to_constant,
/*ids_from_name_mapping=*/has_id_visitor.HasNoIds()));

ICEBERG_RETURN_UNEXPECTED(backend_->InitWithSchema(file_schema, options.split));
// Avro reads the first block before seeking to the split, which the split may
// not need, so the stream reports the end of the file until the seek. A split
// of no bytes holds no block, so it is not read at all.
split_done_ = options.split && options.split->length == 0;
if (options.split) {
read_error_->skip_reads = true;
}

// Reading a block throws if the stream fails inside it. That ends the split if
// the block starts past its end, as Avro's pastSync() decides.
try {
ICEBERG_RETURN_UNEXPECTED(backend_->InitWithSchema(
file_schema, split_done_ ? std::nullopt : options.split));
} catch (...) {
const bool next_split =
options.split && !read_error_->status.ok() &&
backend_->PreviousSync() >=
static_cast<int64_t>(options.split->offset + options.split->length) +
::avro::SyncSize &&
static_cast<int64_t>(read_error_->position) >= backend_->PreviousSync();
if (!next_split) {
ICEBERG_RETURN_UNEXPECTED(CheckOpenReadError(options.path));
throw;
}
split_done_ = true;
}
// Avro found the first block of the split if it recorded a block start after a
// sync marker that starts in the split, before the failed read. Otherwise the
// read failed while searching for one, and the block start is still the one from
// before the search, which can be just inside the split.
found_block_ =
split_done_ || read_error_->status.ok() || !options.split ||
(backend_->PreviousSync() >=
static_cast<int64_t>(options.split->offset) + ::avro::SyncSize &&
static_cast<int64_t>(read_error_->position) >= backend_->PreviousSync());

if (options.split) {
split_end_ = options.split->offset + options.split->length;
Expand Down Expand Up @@ -383,17 +439,27 @@ class AvroReader::Impl {
ICEBERG_RETURN_UNEXPECTED(InitReadContext());
}

while (context_->builder_->length() < batch_size_) {
if (IsPastSync()) {
break;
}
if (!backend_->HasMore()) {
break;
// Avro throws if the stream fails inside a block, so report a read error as such
// instead of as a malformed file.
try {
while (context_->builder_->length() < batch_size_) {
if (split_done_ || IsPastSyncOrNextSplit()) {
break;
}
if (!backend_->HasMore()) {
break;
}
ICEBERG_RETURN_UNEXPECTED(backend_->DecodeNext(
projection_, *read_schema_, metadata_context_, context_->builder_.get()));
metadata_context_.next_file_pos++;
}
ICEBERG_RETURN_UNEXPECTED(backend_->DecodeNext(
projection_, *read_schema_, metadata_context_, context_->builder_.get()));
metadata_context_.next_file_pos++;
} catch (...) {
// Avro throws only where it needs the bytes, so the error is reported even past
// the end of the split, where a block of the split can still continue.
ICEBERG_RETURN_UNEXPECTED(CheckOpenReadError(metadata_context_.file_path));
throw;
}
ICEBERG_RETURN_UNEXPECTED(CheckReadError());

return ConvertBuilderToArrowArray();
}
Expand Down Expand Up @@ -484,6 +550,61 @@ class AvroReader::Impl {
return arrow_array;
}

// Report a read error that made Avro throw.
Status CheckOpenReadError(std::string_view path) const {
if (read_error_->status.ok()) {
return {};
}
return IOError("Failed to read {}: {}", path, read_error_->status.ToString());
}

// Avro treats a failed read as the end of the file, which would return the records
// read before it as if they were complete. Report the failure, unless it occurred
// where a block past the end of the split starts, as Avro's pastSync() decides.
Status CheckReadError() const {
if (read_error_ == nullptr || read_error_->status.ok()) {
return {};
}
if (!split_end_) {
return IOError("Failed to read {}: {}", metadata_context_.file_path,
read_error_->status.ToString());
}
const auto position = static_cast<int64_t>(read_error_->position);
// While searching for the first block of the split, Avro has read every sync
// marker that can start in the split once it reads past split_end + SyncSize - 1.
if (!found_block_ && position >= split_end_.value() + ::avro::SyncSize - 1) {
return {};
}
// Otherwise a failed read ends the stream for Avro without an error only where a
// block would start. Ignore it if that block belongs to the next split. A block of
// this split can extend past its end, so the failure position alone does not show
// that.
if (found_block_ &&
backend_->PreviousSync() >= split_end_.value() + ::avro::SyncSize &&
position >= backend_->PreviousSync()) {
return {};
}
return IOError("Failed to read {}: {}", metadata_context_.file_path,
read_error_->status.ToString());
}

// Avro reads the start of the next block to decide whether it belongs to the
// split, so a failed read there throws. That block belongs to the next split if it
// starts past the end of this one, as Avro's pastSync() decides, so the failure
// ends the split instead.
bool IsPastSyncOrNextSplit() {
try {
return IsPastSync();
} catch (...) {
if (split_end_ && !read_error_->status.ok() &&
backend_->PreviousSync() >= split_end_.value() + ::avro::SyncSize) {
split_done_ = true;
return true;
}
throw;
}
}

bool IsPastSync() const {
if (!split_end_) {
return false;
Expand All @@ -496,6 +617,11 @@ class AvroReader::Impl {
int64_t batch_size_{};
// The end of the split to read and used to terminate the reading.
std::optional<int64_t> split_end_;
// Whether reading the next block failed after the end of the split.
bool split_done_ = false;
// Whether Avro found a block when opening the file, so that PreviousSync() is the
// start of a block.
bool found_block_ = true;
// The schema to read.
std::shared_ptr<::iceberg::Schema> read_schema_;
// The projection result to apply to the read schema.
Expand All @@ -504,6 +630,8 @@ class AvroReader::Impl {
arrow::MetadataColumnContext metadata_context_;
// The read backend to read data into Arrow.
std::unique_ptr<AvroReadBackend> backend_;
// The read error of the input stream.
std::shared_ptr<AvroInputStream::ReadError> read_error_;
// The context to keep track of the reading progress.
std::unique_ptr<ReadContext> context_;
};
Expand Down
27 changes: 22 additions & 5 deletions src/iceberg/avro/avro_stream_internal.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ AvroInputStream::AvroInputStream(
AvroInputStream::~AvroInputStream() = default;

bool AvroInputStream::next(const uint8_t** data, size_t* len) {
if (read_error_->skip_reads) {
return false;
}
// Return all unconsumed data in the buffer
if (buffer_pos_ < available_bytes_) {
*data = buffer_.data() + buffer_pos_;
Expand All @@ -45,10 +48,16 @@ bool AvroInputStream::next(const uint8_t** data, size_t* len) {

// Read from the input stream when the buffer is empty
auto result = input_stream_->Read(buffer_.size(), buffer_.data());
// TODO(xiao.dong) Avro interface requires to return false if an error has occurred or
// reach EOF, so error message can not be raised to the caller, add some log after we
// have a logging system
if (!result.ok() || result.ValueUnsafe() <= 0) {
// Avro requires returning false on both an error and the end of the stream, so the
// error is kept for the reader to report.
if (!result.ok()) {
if (read_error_->status.ok()) {
read_error_->status = result.status();
read_error_->position = byte_count_;
}
return false;
}
if (result.ValueUnsafe() <= 0) {
return false;
}
available_bytes_ = result.ValueUnsafe();
Expand Down Expand Up @@ -80,12 +89,20 @@ void AvroInputStream::skip(size_t len) {
return;
}

seek(byte_count_ + len);
SeekTo(byte_count_ + len);
}

size_t AvroInputStream::byteCount() const { return byte_count_; }

void AvroInputStream::seek(int64_t position) {
// Avro seeks to start reading elsewhere, for example to the start of a split after
// reading the first block, so a failure of the reads before it does not matter,
// and reads resume.
*read_error_ = {};
SeekTo(position);
}

void AvroInputStream::SeekTo(int64_t position) {
auto status = input_stream_->Seek(position);
ICEBERG_CHECK_OR_DIE(status.ok(), "Failed to seek to {}, got {}", position,
status.ToString());
Expand Down
Loading