diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index f9604e257..57cc382d7 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -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 diff --git a/src/iceberg/arrow/arrow_io.cc b/src/iceberg/arrow/arrow_io.cc index 998f8c5ce..0f550770b 100644 --- a/src/iceberg/arrow/arrow_io.cc +++ b/src/iceberg/arrow/arrow_io.cc @@ -18,6 +18,7 @@ */ #include +#include #include #include #include @@ -30,6 +31,7 @@ #include #include #include +#include #include #include "iceberg/arrow/arrow_io_internal.h" @@ -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, @@ -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> Open() override { diff --git a/src/iceberg/avro/avro_reader.cc b/src/iceberg/avro/avro_reader.cc index 6f254100c..5eb563a2c 100644 --- a/src/iceberg/avro/avro_reader.cc +++ b/src/iceberg/avro/avro_reader.cc @@ -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; @@ -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 { @@ -171,13 +174,16 @@ class GenericDatumBackend : public AvroReadBackend { public: Result<::avro::ValidSchema> Init( std::unique_ptr 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) override { + reader_ = + std::make_unique<::avro::DataFileReader<::avro::GenericDatum>>(std::move(base_)); if (split) { reader_->sync(split->offset); } @@ -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 { @@ -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_; @@ -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)) { @@ -325,7 +337,17 @@ class AvroReader::Impl { backend_ = std::make_unique(); } - 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; @@ -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(options.split->offset + options.split->length) + + ::avro::SyncSize && + static_cast(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(options.split->offset) + ::avro::SyncSize && + static_cast(read_error_->position) >= backend_->PreviousSync()); if (options.split) { split_end_ = options.split->offset + options.split->length; @@ -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(); } @@ -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(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; @@ -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 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. @@ -504,6 +630,8 @@ class AvroReader::Impl { arrow::MetadataColumnContext metadata_context_; // The read backend to read data into Arrow. std::unique_ptr backend_; + // The read error of the input stream. + std::shared_ptr read_error_; // The context to keep track of the reading progress. std::unique_ptr context_; }; diff --git a/src/iceberg/avro/avro_stream_internal.cc b/src/iceberg/avro/avro_stream_internal.cc index ffc96fed6..65230e066 100644 --- a/src/iceberg/avro/avro_stream_internal.cc +++ b/src/iceberg/avro/avro_stream_internal.cc @@ -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_; @@ -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(); @@ -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()); diff --git a/src/iceberg/avro/avro_stream_internal.h b/src/iceberg/avro/avro_stream_internal.h index 9aee7199c..fc8191e45 100644 --- a/src/iceberg/avro/avro_stream_internal.h +++ b/src/iceberg/avro/avro_stream_internal.h @@ -19,6 +19,8 @@ #pragma once +#include + #include #include @@ -33,9 +35,26 @@ class AvroInputStream : public ::avro::SeekableInputStream { /// \brief Returns some of available data. /// \return true if some data is available, false if no more data is available or an - /// error has occurred. + /// error has occurred. Use read_error() to tell the two apart. bool next(const uint8_t** data, size_t* len) override; + /// \brief A failed read of the input stream. + struct ReadError { + ::arrow::Status status; + size_t position = 0; // stream position of the failed read + // Report the end of the stream without reading, until the next seek(). Avro + // reads the first block when opening a file, which a split may not need. + bool skip_reads = false; + }; + + /// \brief The first error from reading the input stream since the last seek(). + /// + /// Avro treats a false return from next() as the end of the stream, so readers + /// must check this to avoid returning the records read before an error as if they + /// were complete. It is shared, so that it can be checked after Avro destroyed the + /// stream, for example when reading the header throws. + const std::shared_ptr& read_error() const { return read_error_; } + /// \brief "Returns" back some of the data to the stream. The returned data must be less /// than what was obtained in the last call to next(). void backup(size_t len) override; @@ -54,11 +73,14 @@ class AvroInputStream : public ::avro::SeekableInputStream { void seek(int64_t position) override; private: + void SeekTo(int64_t position); + std::shared_ptr<::arrow::io::RandomAccessFile> input_stream_; std::vector buffer_; size_t byte_count_ = 0; // bytes read from the input stream size_t buffer_pos_ = 0; // next position to read in the buffer size_t available_bytes_ = 0; // bytes available in the buffer + std::shared_ptr read_error_ = std::make_shared(); }; class AvroOutputStream : public ::avro::OutputStream { diff --git a/src/iceberg/cpp20_compatibility_internal.h b/src/iceberg/cpp20_compatibility_internal.h index 93d716e95..a803bd5e2 100644 --- a/src/iceberg/cpp20_compatibility_internal.h +++ b/src/iceberg/cpp20_compatibility_internal.h @@ -199,6 +199,7 @@ #include "iceberg/util/macros.h" #include "iceberg/util/partition_value_util.h" #include "iceberg/util/property_util.h" +#include "iceberg/util/reachable_file_util.h" #include "iceberg/util/retry_util.h" #include "iceberg/util/snapshot_util.h" #include "iceberg/util/stream.h" diff --git a/src/iceberg/file_io.h b/src/iceberg/file_io.h index 79faaacbb..9d41cbf41 100644 --- a/src/iceberg/file_io.h +++ b/src/iceberg/file_io.h @@ -99,6 +99,10 @@ class ICEBERG_EXPORT InputFile { virtual std::string_view location() const = 0; /// \brief Return the total file size in bytes. + /// + /// If the size was not given when the file was created, it is looked up and fails + /// with ErrorKind::kNotFound if the file does not exist. Callers rely on this to + /// tell a missing file from other failures, such as a storage outage. virtual Result Size() const = 0; /// \brief Open a new independent input stream. diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index 125ba128a..91aaec26c 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -332,6 +332,7 @@ if(ICEBERG_BUILD_BUNDLE) update_sort_order_test.cc update_statistics_test.cc overwrite_files_test.cc + reachable_file_util_test.cc replace_partitions_test.cc) add_iceberg_test(data_test diff --git a/src/iceberg/test/arrow_io_test.cc b/src/iceberg/test/arrow_io_test.cc index 7bc9ebba5..d924b3226 100644 --- a/src/iceberg/test/arrow_io_test.cc +++ b/src/iceberg/test/arrow_io_test.cc @@ -345,8 +345,13 @@ class LocalFileIOTest : public TempFileTestBase { TEST_F(LocalFileIOTest, ReadWriteFile) { auto read_res = file_io_->ReadFile(temp_filepath_, std::nullopt); - EXPECT_THAT(read_res, IsError(ErrorKind::kIOError)); + EXPECT_THAT(read_res, IsError(ErrorKind::kNotFound)); EXPECT_THAT(read_res, HasErrorMessage("Failed to open local file")); + // So is a path below a file, which cannot exist either. + ASSERT_THAT(file_io_->WriteFile(temp_filepath_, "file"), IsOk()); + EXPECT_THAT(file_io_->ReadFile(temp_filepath_ + "/child", std::nullopt), + IsError(ErrorKind::kNotFound)); + ASSERT_THAT(file_io_->DeleteFile(temp_filepath_), IsOk()); auto write_res = file_io_->WriteFile(temp_filepath_, "hello world"); EXPECT_THAT(write_res, IsOk()); @@ -377,9 +382,10 @@ TEST_F(LocalFileIOTest, DeleteFiles) { std::vector paths = {first_path, second_path}; EXPECT_THAT(file_io_->DeleteFiles(paths), IsOk()); - EXPECT_THAT(file_io_->ReadFile(first_path, std::nullopt), IsError(ErrorKind::kIOError)); + EXPECT_THAT(file_io_->ReadFile(first_path, std::nullopt), + IsError(ErrorKind::kNotFound)); EXPECT_THAT(file_io_->ReadFile(second_path, std::nullopt), - IsError(ErrorKind::kIOError)); + IsError(ErrorKind::kNotFound)); } void VerifyReadFullyReadsFromAbsolutePosition(const std::shared_ptr& file_io, diff --git a/src/iceberg/test/arrow_s3_file_io_test.cc b/src/iceberg/test/arrow_s3_file_io_test.cc index f7aa6ce68..8f8647145 100644 --- a/src/iceberg/test/arrow_s3_file_io_test.cc +++ b/src/iceberg/test/arrow_s3_file_io_test.cc @@ -1299,7 +1299,7 @@ TEST_F(ArrowS3FileIOTest, DeleteFilesAttemptsEveryFile) { [](const LogMessage& record) { return record.level == LogLevel::kWarn; }), 2); EXPECT_THAT(io->ReadFile(allowed, std::nullopt), - ::testing::AllOf(IsError(ErrorKind::kIOError), + ::testing::AllOf(IsError(ErrorKind::kNotFound), HasErrorMessage("Path does not exist"))); // The denied files remain: Arrow fails to delete a missing object. diff --git a/src/iceberg/test/avro_test.cc b/src/iceberg/test/avro_test.cc index 5d04a6251..878f90444 100644 --- a/src/iceberg/test/avro_test.cc +++ b/src/iceberg/test/avro_test.cc @@ -17,6 +17,7 @@ * under the License. */ +#include #include #include #include @@ -442,6 +443,9 @@ TEST_F(AvroReaderTest, ReadMissingFieldsWithDefaults) { TEST_F(AvroReaderTest, RoundTripWithGenericFileIO) { file_io_ = std::make_shared(); temp_avro_file_ = CreateNewTempFilePathWithSuffix(".avro"); + // The size of a missing file is reported as kNotFound, as InputFile requires. + ICEBERG_UNWRAP_OR_FAIL(auto missing, file_io_->NewInputFile(temp_avro_file_)); + EXPECT_THAT(missing->Size(), IsError(ErrorKind::kNotFound)); auto schema = std::make_shared(std::vector{ SchemaField::MakeRequired(1, "id", std::make_shared()), SchemaField::MakeOptional(2, "name", std::make_shared())}); @@ -449,6 +453,265 @@ TEST_F(AvroReaderTest, RoundTripWithGenericFileIO) { ASSERT_NO_FATAL_FAILURE(WriteAndVerify(schema, R"([[1, "Foo"], [2, "Bar"]])")); } +TEST_F(AvroReaderTest, ReadErrorIsNotEndOfFile) { + // Input streams that fail at a given position, as a storage error would. + class FailingStream final : public SeekableInputStream { + public: + FailingStream(std::unique_ptr stream, int64_t fail_from, + int64_t fail_to) + : stream_(std::move(stream)), fail_from_(fail_from), fail_to_(fail_to) {} + Result Position() const override { return stream_->Position(); } + Status Seek(int64_t position) override { return stream_->Seek(position); } + Result Read(std::span out) override { + ICEBERG_ASSIGN_OR_RAISE(auto position, stream_->Position()); + if (position >= fail_from_ && position < fail_to_) { + return IOError("injected read failure"); + } + if (position < fail_from_) { + out = out.first(std::min(out.size(), static_cast(fail_from_ - position))); + } + return stream_->Read(out); + } + Status ReadFully(int64_t position, std::span out) override { + return stream_->ReadFully(position, out); + } + Status Close() override { return stream_->Close(); } + + private: + std::unique_ptr stream_; + int64_t fail_from_; + int64_t fail_to_; + }; + class FailingFile final : public InputFile { + public: + FailingFile(std::unique_ptr file, int64_t fail_from, int64_t fail_to) + : file_(std::move(file)), fail_from_(fail_from), fail_to_(fail_to) {} + std::string_view location() const override { return file_->location(); } + Result Size() const override { return file_->Size(); } + Result> Open() override { + ICEBERG_ASSIGN_OR_RAISE(auto stream, file_->Open()); + return std::make_unique(std::move(stream), fail_from_, fail_to_); + } + + private: + std::unique_ptr file_; + int64_t fail_from_; + int64_t fail_to_; + }; + class FailingFileIO final : public test::StdFileIO { + public: + FailingFileIO(int64_t fail_from, int64_t fail_to) + : fail_from_(fail_from), fail_to_(fail_to) {} + Result> NewInputFile(std::string location) override { + ICEBERG_ASSIGN_OR_RAISE(auto file, StdFileIO::NewInputFile(std::move(location))); + return std::make_unique(std::move(file), fail_from_, fail_to_); + } + + private: + int64_t fail_from_; + int64_t fail_to_; + }; + + // Write one block per record, then find where the blocks start: after each sync + // marker, which also ends the file. + file_io_ = std::make_shared(); + temp_avro_file_ = CreateNewTempFilePathWithSuffix(".avro"); + auto schema = std::make_shared(std::vector{ + SchemaField::MakeRequired(1, "id", std::make_shared()), + SchemaField::MakeRequired(2, "pad", std::make_shared())}); + ArrowSchema arrow_c_schema; + ASSERT_THAT(ToArrowSchema(*schema, &arrow_c_schema), IsOk()); + auto arrow_schema = ::arrow::ImportType(&arrow_c_schema).ValueOrDie(); + const std::string pad(64, 'x'); + auto array = + ::arrow::json::ArrayFromJSONString(::arrow::struct_(arrow_schema->fields()), + std::format(R"([[1, "{0}"], [2, "{0}"]])", pad)) + .ValueOrDie(); + ArrowArray arrow_array; + ASSERT_TRUE(::arrow::ExportArray(*array, &arrow_array).ok()); + WriterOptions writer_options{.path = temp_avro_file_, .schema = schema, .io = file_io_}; + writer_options.properties.Set(WriterProperties::kAvroSyncInterval, int64_t{32}); + // Uncompressed, so that a failure lands at a known place in a block. + writer_options.properties.Set(WriterProperties::kAvroCompression, + std::string("uncompressed")); + ICEBERG_UNWRAP_OR_FAIL( + auto writer, WriterFactoryRegistry::Open(FileFormatType::kAvro, writer_options)); + ASSERT_THAT(writer->Write(&arrow_array), IsOk()); + ASSERT_THAT(writer->Close(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto content, file_io_->ReadFile(temp_avro_file_, std::nullopt)); + const auto sync = content.substr(content.size() - ::avro::SyncSize); + std::vector block_starts; + for (auto pos = content.find(sync); pos + ::avro::SyncSize < content.size(); + pos = content.find(sync, pos + 1)) { + block_starts.push_back(static_cast(pos + ::avro::SyncSize)); + } + ASSERT_EQ(block_starts.size(), 2U); + + for (bool skip_datum : {true, false}) { + auto open = [&](int64_t fail_from, int64_t fail_to, std::optional split) { + ReaderOptions options{ + .path = temp_avro_file_, + .split = split, + .io = std::make_shared(fail_from, fail_to), + .projection = std::make_shared(std::vector{ + SchemaField::MakeRequired(1, "id", std::make_shared())})}; + options.properties.Set(ReaderProperties::kAvroSkipDatum, skip_datum); + return ReaderFactoryRegistry::Open(FileFormatType::kAvro, options); + }; + + const auto end = static_cast(content.size()); + const auto second_sync = block_starts[1] - ::avro::SyncSize; + + // A failure while reading the header is a read error, not a malformed file. + EXPECT_THAT(open(0, end, std::nullopt), IsError(ErrorKind::kIOError)) << skip_datum; + + // So is a failure while reading the count of the first block. + EXPECT_THAT(open(block_starts[0] + 1, end, std::nullopt), + IsError(ErrorKind::kIOError)) + << skip_datum; + + // And a failure inside the second block, where Avro throws. + ICEBERG_UNWRAP_OR_FAIL(auto mid_block, open(block_starts[1] + 8, end, std::nullopt)); + EXPECT_THAT(mid_block->Next(), IsError(ErrorKind::kIOError)) << skip_datum; + + // A failure before the second block is an error, not the end of the file. + ICEBERG_UNWRAP_OR_FAIL(auto reader, open(block_starts[1], end, std::nullopt)); + EXPECT_THAT(reader->Next(), IsError(ErrorKind::kIOError)) << skip_datum; + + // A split that ends before the second block does not need to read it. + ICEBERG_UNWRAP_OR_FAIL( + auto first_split, + open(block_starts[1], end, + Split{.offset = 0, .length = static_cast(block_starts[0])})); + ASSERT_NO_FATAL_FAILURE(VerifyNextBatch(*first_split, "[[1]]")); + VerifyExhausted(*first_split); + + // It still needs the sync marker that ends its block, which extends past the + // point where a block would belong to the next split. + ICEBERG_UNWRAP_OR_FAIL( + auto first_split_sync, + open(block_starts[1] - 1, end, + Split{.offset = 0, .length = static_cast(block_starts[0])})); + EXPECT_THAT(first_split_sync->Next(), IsError(ErrorKind::kIOError)) << skip_datum; + + // A failure inside a block of the split is an error, even past the point where a + // block would belong to the next split. + const auto payload_failure = block_starts[0] + ::avro::SyncSize + 4; + ASSERT_LT(payload_failure, second_sync); + ICEBERG_UNWRAP_OR_FAIL( + auto first_split_payload, + open(payload_failure, end, + Split{.offset = 0, .length = static_cast(block_starts[0])})); + EXPECT_THAT(first_split_payload->Next(), IsError(ErrorKind::kIOError)) << skip_datum; + + // Nor the start of the next block, which Avro reads to find the end of the split. + ICEBERG_UNWRAP_OR_FAIL( + auto first_split_lookahead, + open(block_starts[1] + 1, end, + Split{.offset = 0, .length = static_cast(block_starts[0])})); + ASSERT_NO_FATAL_FAILURE(VerifyNextBatch(*first_split_lookahead, "[[1]]")); + VerifyExhausted(*first_split_lookahead); + + // A split that holds no block start can fail while Avro searches for one, inside + // the next sync marker and past the bytes that could complete a marker in the + // split. + for (int64_t fail_at : + {block_starts[0] + 1 + 4 + ::avro::SyncSize - 1, block_starts[1] - 3}) { + ICEBERG_UNWRAP_OR_FAIL( + auto empty_split, + open(fail_at, end, + Split{.offset = static_cast(block_starts[0] + 1), .length = 4})); + VerifyExhausted(*empty_split); + } + + // A split of no bytes needs none of them, even where Avro reads the first block + // when opening the file. + for (int64_t fail_at : {block_starts[0], block_starts[1]}) { + ICEBERG_UNWRAP_OR_FAIL( + auto zero_split, + open(fail_at, end, + Split{.offset = static_cast(block_starts[1]), .length = 0})); + VerifyExhausted(*zero_split); + } + + // The same holds for a split that starts inside the sync marker ending the + // header, which Avro then misses while searching. + ICEBERG_UNWRAP_OR_FAIL( + auto header_split, + open(block_starts[1] - 3, end, + Split{.offset = static_cast(block_starts[0] - 4), .length = 8})); + VerifyExhausted(*header_split); + + // Nor the first block, which Avro reads before seeking to a later split. + ICEBERG_UNWRAP_OR_FAIL(auto second_split_only, + open(block_starts[0] + 1, block_starts[0] + 2, + Split{.offset = static_cast(second_sync), + .length = static_cast(end - second_sync)})); + ASSERT_NO_FATAL_FAILURE(VerifyNextBatch(*second_split_only, "[[2]]")); + VerifyExhausted(*second_split_only); + + // Nor a block that the search for the split's first block finds past its end. + ICEBERG_UNWRAP_OR_FAIL( + auto split_before_block, + open(block_starts[1] + 1, end, + Split{.offset = static_cast(block_starts[0] + 1), .length = 4})); + VerifyExhausted(*split_before_block); + + // Neither does a split that starts after the first block, which Avro reads + // before seeking to the split. + ICEBERG_UNWRAP_OR_FAIL(auto second_split, + open(block_starts[0], second_sync, + Split{.offset = static_cast(second_sync), + .length = static_cast(end - second_sync)})); + ASSERT_NO_FATAL_FAILURE(VerifyNextBatch(*second_split, "[[2]]")); + VerifyExhausted(*second_split); + } + + // A compressed block of the split that extends past the point where a block would + // belong to the next split: inflating stops at the failed read without an error, + // and Avro decodes the records it got. The read error is still reported. + temp_avro_file_ = CreateNewTempFilePathWithSuffix(".avro"); + std::string rows = "["; + for (int i = 0; i < 64; ++i) { + rows += std::format(R"({}[{}, "{}"])", i == 0 ? "" : ",", i, + std::string(64, 'a' + i % 26)); + } + rows += "]"; + auto big = + ::arrow::json::ArrayFromJSONString(::arrow::struct_(arrow_schema->fields()), rows) + .ValueOrDie(); + ASSERT_TRUE(::arrow::ExportArray(*big, &arrow_array).ok()); + WriterOptions deflate_options{ + .path = temp_avro_file_, .schema = schema, .io = file_io_}; + deflate_options.properties.Set(WriterProperties::kAvroCompression, std::string("gzip")); + ICEBERG_UNWRAP_OR_FAIL( + auto deflate_writer, + WriterFactoryRegistry::Open(FileFormatType::kAvro, deflate_options)); + ASSERT_THAT(deflate_writer->Write(&arrow_array), IsOk()); + ASSERT_THAT(deflate_writer->Close(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto deflated, + file_io_->ReadFile(temp_avro_file_, std::nullopt)); + const auto deflate_sync = deflated.substr(deflated.size() - ::avro::SyncSize); + const auto data_start = + static_cast(deflated.find(deflate_sync) + ::avro::SyncSize); + const auto data_end = static_cast(deflated.size()) - ::avro::SyncSize; + ASSERT_GT(data_end - data_start, 4 * ::avro::SyncSize); + for (bool skip_datum : {true, false}) { + ReaderOptions options{ + .path = temp_avro_file_, + .split = Split{.offset = 0, .length = static_cast(data_start)}, + .io = std::make_shared((data_start + data_end) / 2, data_end), + .projection = std::make_shared(std::vector{ + SchemaField::MakeRequired(1, "id", std::make_shared())})}; + options.properties.Set(ReaderProperties::kAvroSkipDatum, skip_datum); + // A batch that fills before the failed read is not returned as complete. + options.properties.Set(ReaderProperties::kBatchSize, int64_t{1}); + ICEBERG_UNWRAP_OR_FAIL(auto reader, + ReaderFactoryRegistry::Open(FileFormatType::kAvro, options)); + EXPECT_THAT(reader->Next(), IsError(ErrorKind::kIOError)) << skip_datum; + } +} + TEST_F(AvroReaderTest, ReadReorderedFieldsWithNulls) { CreateSimpleAvroFile(); auto schema = std::make_shared(std::vector{ diff --git a/src/iceberg/test/cherry_pick_operation_test.cc b/src/iceberg/test/cherry_pick_operation_test.cc index bb0069552..00505c71f 100644 --- a/src/iceberg/test/cherry_pick_operation_test.cc +++ b/src/iceberg/test/cherry_pick_operation_test.cc @@ -684,7 +684,7 @@ TEST_F(CherryPickOperationTest, CherryPickReplayedAsFastForwardAfterRollback) { ExpectFastForward(before, staged_id); ICEBERG_UNWRAP_OR_FAIL(auto snapshot, table_->current_snapshot()); EXPECT_THAT(file_io_->ReadFile(draft->manifest_list, std::nullopt), - IsError(ErrorKind::kIOError)); + IsError(ErrorKind::kNotFound)); EXPECT_THAT(file_io_->ReadFile(snapshot->manifest_list, std::nullopt), IsOk()); ICEBERG_UNWRAP_OR_FAIL(auto live, LiveDataFilePaths()); EXPECT_THAT(live, diff --git a/src/iceberg/test/expire_snapshots_test.cc b/src/iceberg/test/expire_snapshots_test.cc index 9695b4a85..08f122e25 100644 --- a/src/iceberg/test/expire_snapshots_test.cc +++ b/src/iceberg/test/expire_snapshots_test.cc @@ -19,12 +19,16 @@ #include "iceberg/update/expire_snapshots.h" +#include #include #include #include +#include #include #include +#include #include +#include #include #include @@ -32,6 +36,7 @@ #include "iceberg/avro/avro_register.h" #include "iceberg/manifest/manifest_entry.h" #include "iceberg/manifest/manifest_writer.h" +#include "iceberg/partition_field.h" #include "iceberg/partition_spec.h" #include "iceberg/schema.h" #include "iceberg/snapshot.h" @@ -43,13 +48,84 @@ #include "iceberg/test/mock_catalog.h" #include "iceberg/test/update_test_base.h" #include "iceberg/transaction.h" +#include "iceberg/transform.h" +#include "iceberg/type.h" #include "iceberg/update/fast_append.h" #include "iceberg/update/set_snapshot.h" +#include "iceberg/update/update_partition_spec.h" namespace iceberg { class ExpireSnapshotsTest : public UpdateTestBase {}; +/// Reports the given files as kNotFound, as some FileIO implementations do, and +/// fails to read the unreadable files with kIOError, as a storage outage would. +class NotFoundFileIO final : public FileIO { + public: + NotFoundFileIO(std::shared_ptr io, std::unordered_set missing, + std::unordered_set unreadable = {}) + : io_(std::move(io)), + missing_(std::move(missing)), + unreadable_(std::move(unreadable)) {} + + Result> NewInputFile(std::string location) override { + if (missing_.contains(location)) { + return NotFound("File does not exist: {}", location); + } + return Wrap(io_->NewInputFile(std::move(location))); + } + Result> NewInputFile(std::string location, + size_t length) override { + if (missing_.contains(location)) { + return NotFound("File does not exist: {}", location); + } + return Wrap(io_->NewInputFile(std::move(location), length)); + } + Result> NewOutputFile(std::string location) override { + return io_->NewOutputFile(std::move(location)); + } + Result ReadFile(const std::string& location, + std::optional length) override { + return io_->ReadFile(location, length); + } + Status WriteFile(const std::string& location, std::string_view content) override { + return io_->WriteFile(location, content); + } + Status DeleteFile(const std::string& location) override { + return io_->DeleteFile(location); + } + + private: + class UnreadableFile final : public InputFile { + public: + explicit UnreadableFile(std::unique_ptr file) : file_(std::move(file)) {} + std::string_view location() const override { return file_->location(); } + // Checking the size fails too, as in a storage outage, which does not show that + // the file is missing. + Result Size() const override { + return IOError("Injected size failure: {}", file_->location()); + } + Result> Open() override { + return IOError("Injected read failure: {}", file_->location()); + } + + private: + std::unique_ptr file_; + }; + + Result> Wrap(Result> file) { + if (!file.has_value() || + !unreadable_.contains(std::string(file.value()->location()))) { + return file; + } + return std::make_unique(std::move(file).value()); + } + + std::shared_ptr io_; + std::unordered_set missing_; + std::unordered_set unreadable_; +}; + class ExpireSnapshotsCleanupTest : public UpdateTestBase { protected: static constexpr int64_t kExpiredSnapshotId = 3051729675574597004; @@ -443,7 +519,14 @@ TEST_F(ExpireSnapshotsTest, CommitWithCleanupNone) { EXPECT_EQ(metadata->snapshots.at(0)->snapshot_id, 3055729675574597004); } -TEST_F(ExpireSnapshotsCleanupTest, IgnoresExpiredDeleteManifestReadFailures) { +class IgnoresExpiredManifestReadFailuresTest + : public ExpireSnapshotsCleanupTest, + public ::testing::WithParamInterface {}; + +// A missing expired manifest is skipped whether FileIO reports it as kIOError or +// kNotFound. +TEST_P(IgnoresExpiredManifestReadFailuresTest, IgnoresExpiredDeleteManifestReadFailures) { + const bool not_found = GetParam(); const auto expired_data_file_path = table_location_ + "/data/expired-data.parquet"; const auto expired_delete_file_path = table_location_ + "/data/expired-delete.parquet"; const auto expired_data_manifest_path = table_location_ + "/metadata/expired-data.avro"; @@ -471,6 +554,15 @@ TEST_F(ExpireSnapshotsCleanupTest, IgnoresExpiredDeleteManifestReadFailures) { WriteManifestList(current_manifest_list_path, kCurrentSnapshotId, kExpiredSnapshotId, kCurrentSequenceNumber, {}); RewriteTableWithManifestLists(expired_manifest_list_path, current_manifest_list_path); + if (not_found) { + auto io = std::make_shared( + file_io_, std::unordered_set{missing_delete_manifest_path}); + ICEBERG_UNWRAP_OR_FAIL(catalog_, + InMemoryCatalog::Make("not_found", io, "/warehouse/", {})); + ICEBERG_UNWRAP_OR_FAIL( + table_, catalog_->RegisterTable(table_ident_, + std::string(table_->metadata_file_location()))); + } std::vector deleted_files; ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); @@ -486,6 +578,261 @@ TEST_F(ExpireSnapshotsCleanupTest, IgnoresExpiredDeleteManifestReadFailures) { expired_manifest_list_path)); } +INSTANTIATE_TEST_SUITE_P(MissingFileErrors, IgnoresExpiredManifestReadFailuresTest, + ::testing::Bool()); + +TEST_F(ExpireSnapshotsCleanupTest, PlanningFailuresPreserveExpiredFiles) { + // An expired manifest that fails to decode, has an unknown partition spec or + // exists but cannot be read, or a retained manifest that cannot be read, leaves + // the files to delete unknown, so cleanup deletes nothing. + for (std::string_view failure : {"corrupt", "no-spec", "unreadable", "missing"}) { + const auto prefix = std::format("{}/{}-", table_location_, failure); + const auto expired_manifest_path = prefix + "expired.avro"; + const auto expired_manifest_list_path = prefix + "expired-list.avro"; + const auto current_manifest_list_path = prefix + "current-list.avro"; + auto expired_manifest = WriteDataManifest( + expired_manifest_path, kExpiredSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kExpiredSnapshotId, kExpiredSequenceNumber, + MakeDataFile(prefix + "expired.parquet"))}); + auto retained_manifest = WriteDataManifest( + prefix + "retained.avro", kCurrentSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kCurrentSnapshotId, kCurrentSequenceNumber, + MakeDataFile(prefix + "retained.parquet"))}); + if (failure == "corrupt") { + ASSERT_THAT(file_io_->WriteFile(expired_manifest_path, "Obj\x01 not avro"), IsOk()); + } else if (failure == "no-spec") { + expired_manifest.partition_spec_id = 99; + } else if (failure == "missing") { + retained_manifest.manifest_path = prefix + "absent.avro"; + } + WriteManifestList(expired_manifest_list_path, kExpiredSnapshotId, + /*parent_snapshot_id=*/0, kExpiredSequenceNumber, + {expired_manifest}); + WriteManifestList(current_manifest_list_path, kCurrentSnapshotId, kExpiredSnapshotId, + kCurrentSequenceNumber, {retained_manifest}); + RewriteTableWithManifestLists(expired_manifest_list_path, current_manifest_list_path); + if (failure == "unreadable") { + auto io = std::make_shared( + file_io_, std::unordered_set{}, + std::unordered_set{expired_manifest_path}); + ICEBERG_UNWRAP_OR_FAIL(catalog_, + InMemoryCatalog::Make("unreadable", io, "/warehouse/", {})); + ICEBERG_UNWRAP_OR_FAIL( + table_, catalog_->RegisterTable(table_ident_, + std::string(table_->metadata_file_location()))); + } + + std::vector deleted_files; + ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); + update->ExpireSnapshotId(kExpiredSnapshotId); + update->DeleteWith( + [&deleted_files](const std::string& path) { deleted_files.push_back(path); }); + EXPECT_THAT(update->Commit(), IsOk()); + EXPECT_THAT(deleted_files, testing::IsEmpty()) << failure; + RegisterTableFromResource(MetadataResource()); + } + + // The same holds for incremental cleanup when reading a manifest to scan throws + // on a planning thread or returns an error, when a retained manifest list or a + // retained manifest to scan is missing, or when an expired manifest list exists + // but cannot be read. + for (std::string_view failure : + {"corrupt", "no-spec", "missing-list", "missing-scan", "unreadable-list"}) { + const auto prefix = std::format("{}/{}-", table_location_, failure); + const auto scan_manifest_path = prefix + "scan.avro"; + const auto expired_manifest_list_path = prefix + "scan-ml-1.avro"; + const auto current_manifest_list_path = prefix + "scan-ml-2.avro"; + auto scan_manifest = AssignManifestSequenceNumber( + WriteDataManifest( + scan_manifest_path, kExpiredSnapshotId, + {MakeEntry(ManifestStatus::kDeleted, kExpiredSnapshotId, + kExpiredSequenceNumber, MakeDataFile(prefix + "scan.parquet"))}), + kExpiredSequenceNumber); + if (failure == "corrupt") { + ASSERT_THAT(file_io_->WriteFile(scan_manifest_path, "Obj\x01 not avro"), IsOk()); + } else if (failure == "no-spec") { + scan_manifest.partition_spec_id = 99; + } else if (failure == "missing-scan") { + scan_manifest.manifest_path = prefix + "absent-scan.avro"; + } + WriteManifestList(expired_manifest_list_path, kExpiredSnapshotId, + /*parent_snapshot_id=*/0, kExpiredSequenceNumber, {scan_manifest}); + WriteManifestList(current_manifest_list_path, kCurrentSnapshotId, kExpiredSnapshotId, + kCurrentSequenceNumber, {scan_manifest}); + RewriteTableWithManifestLists( + expired_manifest_list_path, + failure == "missing-list" ? prefix + "absent.avro" : current_manifest_list_path); + if (failure == "unreadable-list") { + auto io = std::make_shared( + file_io_, std::unordered_set{}, + std::unordered_set{expired_manifest_list_path}); + ICEBERG_UNWRAP_OR_FAIL(catalog_, + InMemoryCatalog::Make("unreadable", io, "/warehouse/", {})); + ICEBERG_UNWRAP_OR_FAIL( + table_, catalog_->RegisterTable(table_ident_, + std::string(table_->metadata_file_location()))); + } + + std::vector deleted_files; + test::ThreadExecutor plan_executor; + ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); + update->PlanWith(plan_executor); + update->DeleteWith( + [&deleted_files](const std::string& path) { deleted_files.push_back(path); }); + EXPECT_THAT(update->Commit(), IsOk()); + EXPECT_FALSE(ReloadMetadata()->SnapshotById(kExpiredSnapshotId).has_value()); + EXPECT_THAT(deleted_files, testing::IsEmpty()) << failure; + RegisterTableFromResource(MetadataResource()); + } +} + +TEST_F(ExpireSnapshotsCleanupTest, IncrementalCleanupKeepsLiveFiles) { + // Incremental cleanup reads only the file paths of manifests to scan, so partition + // values that the reader cannot decode, such as fixed values, do not stop it. A + // path that was deleted by an expired snapshot but is live again in a retained one + // is kept. + auto metadata = ReloadMetadata(); + ICEBERG_UNWRAP_OR_FAIL(auto current_schema, metadata->Schema()); + auto fields = current_schema->fields() | std::ranges::to>(); + fields.push_back(SchemaField::MakeOptional(4, "f", fixed(4))); + auto schema = std::make_shared(std::move(fields), /*schema_id=*/2); + ICEBERG_UNWRAP_OR_FAIL( + auto spec, + PartitionSpec::Make(*schema, /*spec_id=*/1, + {PartitionField(4, 1001, "f", Transform::Identity())}, + /*allow_missing_fields=*/false)); + metadata->schemas.push_back(schema); + metadata->current_schema_id = schema->schema_id(); + metadata->last_column_id = 4; + metadata->partition_specs.push_back(std::move(spec)); + metadata->default_spec_id = 1; + metadata->last_partition_id = 1001; + RewriteTable(metadata); + + const auto gone_path = table_location_ + "/data/gone.parquet"; + const auto readded_path = table_location_ + "/data/readded.parquet"; + const auto expired_list = table_location_ + "/metadata/live-ml-1.avro"; + const auto current_list = table_location_ + "/metadata/live-ml-2.avro"; + auto make_file = [&](const std::string& path) { + auto file = MakeDataFile(path); + file->partition = PartitionValues({Literal::Fixed({1, 2, 3, 4})}); + return file; + }; + auto deleted_manifest = AssignManifestSequenceNumber( + WriteDataManifest(table_location_ + "/metadata/deleted.avro", kExpiredSnapshotId, + {MakeEntry(ManifestStatus::kDeleted, kExpiredSnapshotId, + kExpiredSequenceNumber, make_file(gone_path)), + MakeEntry(ManifestStatus::kDeleted, kExpiredSnapshotId, + kExpiredSequenceNumber, make_file(readded_path))}), + kExpiredSequenceNumber); + auto readded_manifest = AssignManifestSequenceNumber( + WriteDataManifest(table_location_ + "/metadata/readded.avro", kCurrentSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kCurrentSnapshotId, + kCurrentSequenceNumber, make_file(readded_path))}), + kCurrentSequenceNumber); + WriteManifestList(expired_list, kExpiredSnapshotId, 0, kExpiredSequenceNumber, + {deleted_manifest}); + // A retained manifest without added or existing entries is not read, even if it + // could not be. + ManifestFile no_live = deleted_manifest; + no_live.manifest_path = table_location_ + "/metadata/no-live.avro"; + no_live.added_snapshot_id = kCurrentSnapshotId; + no_live.added_files_count = 0; + no_live.existing_files_count = 0; + WriteManifestList(current_list, kCurrentSnapshotId, kExpiredSnapshotId, + kCurrentSequenceNumber, + {deleted_manifest, readded_manifest, no_live}); + RewriteTableWithManifestLists(expired_list, current_list); + + std::vector deleted_files; + ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); + update->DeleteWith( + [&deleted_files](const std::string& path) { deleted_files.push_back(path); }); + EXPECT_THAT(update->Commit(), IsOk()); + EXPECT_THAT(deleted_files, testing::UnorderedElementsAre(gone_path, expired_list)); +} + +TEST_F(ExpireSnapshotsCleanupTest, IncrementalCleanupStopsWhenAllCandidatesLive) { + // Once every candidate is live in a retained manifest, a retained manifest that + // cannot be read does not matter, whichever is read first, and the expired + // manifest list is deleted. + const auto readded_path = table_location_ + "/data/readded.parquet"; + const auto expired_list = table_location_ + "/metadata/stop-ml-1.avro"; + const auto current_list = table_location_ + "/metadata/stop-ml-2.avro"; + auto deleted_manifest = AssignManifestSequenceNumber( + WriteDataManifest(table_location_ + "/metadata/stop-deleted.avro", + kExpiredSnapshotId, + {MakeEntry(ManifestStatus::kDeleted, kExpiredSnapshotId, + kExpiredSequenceNumber, MakeDataFile(readded_path))}), + kExpiredSequenceNumber); + auto readded_manifest = AssignManifestSequenceNumber( + WriteDataManifest(table_location_ + "/metadata/stop-readded.avro", + kCurrentSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kCurrentSnapshotId, + kCurrentSequenceNumber, MakeDataFile(readded_path))}), + kCurrentSequenceNumber); + // Without an executor, manifests are read in path order, so these are first: one + // that is missing, and one that fails to decode. + ManifestFile absent = readded_manifest; + absent.manifest_path = table_location_ + "/metadata/stop-a-absent.avro"; + ManifestFile corrupt = readded_manifest; + corrupt.manifest_path = table_location_ + "/metadata/stop-b-corrupt.avro"; + ASSERT_THAT(file_io_->WriteFile(corrupt.manifest_path, "Obj\x01 not avro"), IsOk()); + WriteManifestList(expired_list, kExpiredSnapshotId, 0, kExpiredSequenceNumber, + {deleted_manifest}); + WriteManifestList(current_list, kCurrentSnapshotId, kExpiredSnapshotId, + kCurrentSequenceNumber, + {deleted_manifest, readded_manifest, absent, corrupt}); + RewriteTableWithManifestLists(expired_list, current_list); + + std::vector deleted_files; + ICEBERG_UNWRAP_OR_FAIL(auto update, table_->NewExpireSnapshots()); + update->DeleteWith( + [&deleted_files](const std::string& path) { deleted_files.push_back(path); }); + EXPECT_THAT(update->Commit(), IsOk()); + EXPECT_THAT(deleted_files, testing::UnorderedElementsAre(expired_list)); +} + +TEST_F(ExpireSnapshotsCleanupTest, RetainedManifestsUseCommittedSpecs) { + // A transaction adds a partition spec after expiring, and a retained manifest + // uses it. Reading the retained manifest needs the committed metadata. + const auto expired_data_path = table_location_ + "/data/expired.parquet"; + const auto expired_manifest_path = table_location_ + "/metadata/expired.avro"; + const auto expired_list = table_location_ + "/metadata/expired-list.avro"; + const auto current_list = table_location_ + "/metadata/current-list.avro"; + auto expired_manifest = WriteDataManifest( + expired_manifest_path, kExpiredSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kExpiredSnapshotId, kExpiredSequenceNumber, + MakeDataFile(expired_data_path))}); + WriteManifestList(expired_list, kExpiredSnapshotId, 0, kExpiredSequenceNumber, + {expired_manifest}); + WriteManifestList(current_list, kCurrentSnapshotId, kExpiredSnapshotId, + kCurrentSequenceNumber, {}); + RewriteTableWithManifestLists(expired_list, current_list); + + ICEBERG_UNWRAP_OR_FAIL(auto txn, table_->NewTransaction()); + ICEBERG_UNWRAP_OR_FAIL(auto expire, txn->NewExpireSnapshots()); + expire->ExpireSnapshotId(kExpiredSnapshotId); + std::vector deleted_files; + expire->DeleteWith( + [&deleted_files](const std::string& path) { deleted_files.push_back(path); }); + ASSERT_THAT(expire->Commit(), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto update_spec, txn->NewUpdatePartitionSpec()); + update_spec->AddField("y"); + ASSERT_THAT(update_spec->Commit(), IsOk()); + auto new_spec_file = MakeDataFile(table_location_ + "/data/new-spec.parquet"); + new_spec_file->partition = PartitionValues({Literal::Long(1), Literal::Long(2)}); + new_spec_file->partition_spec_id = 1; + ICEBERG_UNWRAP_OR_FAIL(auto append, txn->NewFastAppend()); + append->AppendFile(new_spec_file); + ASSERT_THAT(append->Commit(), IsOk()); + ASSERT_THAT(txn->Commit(), IsOk()); + ASSERT_EQ(ReloadMetadata()->default_spec_id, 1); + + EXPECT_THAT(deleted_files, testing::UnorderedElementsAre( + expired_data_path, expired_manifest_path, expired_list)); +} + TEST_F(ExpireSnapshotsCleanupTest, DeletesExpiredFiles) { const auto expired_data_file_path = table_location_ + "/data/expired-data.parquet"; const auto expired_delete_file_path = table_location_ + "/data/expired-delete.parquet"; diff --git a/src/iceberg/test/reachable_file_util_test.cc b/src/iceberg/test/reachable_file_util_test.cc new file mode 100644 index 000000000..958eca5fe --- /dev/null +++ b/src/iceberg/test/reachable_file_util_test.cc @@ -0,0 +1,267 @@ +/* + * 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 "iceberg/util/reachable_file_util.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "iceberg/avro/avro_register.h" +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/manifest/manifest_writer.h" +#include "iceberg/partition_spec.h" +#include "iceberg/schema.h" +#include "iceberg/snapshot.h" +#include "iceberg/statistics_file.h" +#include "iceberg/table_metadata.h" +#include "iceberg/test/executor.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/update_test_base.h" + +namespace iceberg { + +namespace { + +using ::testing::ElementsAre; +using ::testing::UnorderedElementsAre; + +constexpr int64_t kFirstSnapshotId = 3051729675574597004; +constexpr int64_t kSecondSnapshotId = 3055729675574597004; + +std::unordered_set ManifestPaths( + const std::unordered_set& manifests) { + std::unordered_set paths; + for (const auto& manifest : manifests) { + paths.insert(manifest.manifest_path); + } + return paths; +} + +} // namespace + +class ReachableFileUtilTest : public UpdateTestBase { + protected: + void SetUp() override { + UpdateTestBase::SetUp(); + avro::RegisterAll(); + metadata_ = ReloadMetadata(); + } + + std::shared_ptr MakeDataFile(const std::string& path) const { + return std::make_shared(DataFile{ + .file_path = path, + .file_format = FileFormatType::kParquet, + .partition = PartitionValues({Literal::Long(1)}), + .record_count = 1, + .file_size_in_bytes = 10, + .sort_order_id = 0, + }); + } + + ManifestEntry MakeEntry(ManifestStatus status, int64_t snapshot_id, + std::shared_ptr file) const { + return ManifestEntry{ + .status = status, + .snapshot_id = snapshot_id, + .sequence_number = 0, + .file_sequence_number = 0, + .data_file = std::move(file), + }; + } + + ManifestFile WriteDataManifest(const std::string& path, int64_t snapshot_id, + const std::vector& entries) { + ICEBERG_ASSIGN_OR_THROW(auto schema, metadata_->Schema()); + ICEBERG_ASSIGN_OR_THROW(auto spec, + metadata_->PartitionSpecById(metadata_->default_spec_id)); + auto writer_result = ManifestWriter::MakeWriter( + metadata_->format_version, snapshot_id, path, file_io_, spec, schema, + ManifestContent::kData, /*first_row_id=*/std::nullopt); + EXPECT_THAT(writer_result, IsOk()); + auto writer = std::move(writer_result.value()); + for (const auto& entry : entries) { + EXPECT_THAT(writer->WriteEntry(entry), IsOk()); + } + EXPECT_THAT(writer->Close(), IsOk()); + auto manifest_result = writer->ToManifestFile(); + EXPECT_THAT(manifest_result, IsOk()); + // Committed manifests carry the sequence number assigned by their snapshot. + auto manifest = std::move(manifest_result.value()); + manifest.sequence_number = 0; + manifest.min_sequence_number = 0; + return manifest; + } + + void WriteManifestList(const std::string& path, int64_t snapshot_id, + int64_t parent_snapshot_id, + const std::vector& manifests) { + auto writer_result = ManifestListWriter::MakeWriter( + metadata_->format_version, snapshot_id, parent_snapshot_id, path, file_io_, + /*sequence_number=*/std::optional(0), + /*first_row_id=*/std::nullopt); + ASSERT_THAT(writer_result, IsOk()); + auto writer = std::move(writer_result.value()); + ASSERT_THAT(writer->AddAll(manifests), IsOk()); + ASSERT_THAT(writer->Close(), IsOk()); + } + + /// \brief Point both snapshots at manifest lists written to the mock file system. + void WriteSnapshotManifests() { + const auto metadata_dir = table_location_ + "/metadata/"; + shared_manifest_ = WriteDataManifest( + metadata_dir + "shared.avro", kFirstSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kFirstSnapshotId, + MakeDataFile(table_location_ + "/data/shared.parquet"))}); + second_manifest_ = WriteDataManifest( + metadata_dir + "second.avro", kSecondSnapshotId, + {MakeEntry(ManifestStatus::kAdded, kSecondSnapshotId, + MakeDataFile(table_location_ + "/data/live.parquet")), + MakeEntry(ManifestStatus::kDeleted, kSecondSnapshotId, + MakeDataFile(table_location_ + "/data/removed.parquet"))}); + + const auto first_manifest_list = metadata_dir + "snap-1.avro"; + const auto second_manifest_list = metadata_dir + "snap-2.avro"; + WriteManifestList(first_manifest_list, kFirstSnapshotId, 0, {shared_manifest_}); + WriteManifestList(second_manifest_list, kSecondSnapshotId, kFirstSnapshotId, + {shared_manifest_, second_manifest_}); + + metadata_->snapshots.at(0)->manifest_list = first_manifest_list; + metadata_->snapshots.at(1)->manifest_list = second_manifest_list; + } + + std::shared_ptr metadata_; + ManifestFile shared_manifest_; + ManifestFile second_manifest_; +}; + +TEST_F(ReachableFileUtilTest, LocationsFromMetadata) { + EXPECT_THAT(ReachableFileUtil::ManifestListLocations(*metadata_), + UnorderedElementsAre("s3://a/b/1.avro", "s3://a/b/2.avro")); + EXPECT_THAT(ReachableFileUtil::ManifestListLocations(*metadata_, {kSecondSnapshotId}), + ElementsAre("s3://a/b/2.avro")); + EXPECT_TRUE(ReachableFileUtil::ManifestListLocations(*metadata_, {}).empty()); + + auto stats = std::make_shared(); + stats->snapshot_id = kFirstSnapshotId; + stats->path = "s3://a/b/stats-1.puffin"; + auto partition_stats = std::make_shared(); + partition_stats->snapshot_id = kSecondSnapshotId; + partition_stats->path = "s3://a/b/partition-stats-2.parquet"; + metadata_->statistics = {stats}; + metadata_->partition_statistics = {partition_stats}; + + EXPECT_THAT(ReachableFileUtil::StatisticsFilesLocations(*metadata_), + UnorderedElementsAre("s3://a/b/stats-1.puffin", + "s3://a/b/partition-stats-2.parquet")); + EXPECT_THAT(ReachableFileUtil::StatisticsFilesLocationsForSnapshots( + *metadata_, {kSecondSnapshotId}), + ElementsAre("s3://a/b/partition-stats-2.parquet")); +} + +TEST_F(ReachableFileUtilTest, MetadataFileLocations) { + // Previous metadata files are listed but not read. + metadata_->metadata_log = { + {.timestamp_ms = TimePointMsFromUnixMs(1), .metadata_file = "s3://a/m/v1.json"}, + {.timestamp_ms = TimePointMsFromUnixMs(2), .metadata_file = "s3://a/m/v2.json"}, + }; + EXPECT_THAT( + ReachableFileUtil::MetadataFileLocations(*metadata_, "s3://a/m/v3.json"), + UnorderedElementsAre("s3://a/m/v1.json", "s3://a/m/v2.json", "s3://a/m/v3.json")); + EXPECT_THAT(ReachableFileUtil::MetadataFileLocations(*metadata_, ""), + UnorderedElementsAre("s3://a/m/v1.json", "s3://a/m/v2.json")); +} + +TEST_F(ReachableFileUtilTest, Manifests) { + WriteSnapshotManifests(); + + ICEBERG_UNWRAP_OR_FAIL(auto first, ReachableFileUtil::ManifestsForSnapshots( + *metadata_, {kFirstSnapshotId}, file_io_)); + EXPECT_THAT(ManifestPaths(first), UnorderedElementsAre(shared_manifest_.manifest_path)); + + test::InlineExecutor executor; + ICEBERG_UNWRAP_OR_FAIL(auto all, ReachableFileUtil::ReachableManifests( + *metadata_, file_io_, std::ref(executor))); + EXPECT_THAT(ManifestPaths(all), UnorderedElementsAre(shared_manifest_.manifest_path, + second_manifest_.manifest_path)); + EXPECT_EQ(executor.submit_count(), 2); + + EXPECT_THAT(ReachableFileUtil::ManifestsForSnapshots(*metadata_, {12345}, file_io_), + IsError(ErrorKind::kNotFound)); + + // A manifest list that fails to decode is reported with its location. + metadata_->snapshots.at(0)->manifest_list = table_location_ + "/metadata/corrupt.avro"; + ASSERT_THAT( + file_io_->WriteFile(metadata_->snapshots.at(0)->manifest_list, "Obj\x01 not avro"), + IsOk()); + auto corrupt = ReachableFileUtil::ReachableManifests(*metadata_, file_io_); + EXPECT_THAT(corrupt, IsError(ErrorKind::kInvalidManifestList)); + EXPECT_THAT(corrupt, HasErrorMessage("corrupt.avro")); +} + +TEST_F(ReachableFileUtilTest, LiveFileLocations) { + WriteSnapshotManifests(); + + // Deleted entries are excluded. + ICEBERG_UNWRAP_OR_FAIL(auto second, ReachableFileUtil::LiveFileLocations( + second_manifest_, *metadata_, file_io_)); + EXPECT_THAT(second, UnorderedElementsAre(table_location_ + "/data/live.parquet")); + + ICEBERG_UNWRAP_OR_FAIL(auto all, + ReachableFileUtil::LiveFileLocationsForManifests( + {shared_manifest_, second_manifest_}, *metadata_, file_io_)); + EXPECT_THAT(all, UnorderedElementsAre(table_location_ + "/data/shared.parquet", + table_location_ + "/data/live.parquet")); + + ICEBERG_UNWRAP_OR_FAIL(auto none, ReachableFileUtil::LiveFileLocationsForManifests( + {}, *metadata_, file_io_)); + EXPECT_TRUE(none.empty()); + + ManifestFile missing = second_manifest_; + missing.manifest_path = table_location_ + "/metadata/missing.avro"; + EXPECT_THAT(ReachableFileUtil::LiveFileLocationsForManifests( + {shared_manifest_, missing}, *metadata_, file_io_), + IsError(ErrorKind::kIOError)); + + // Exceptions from a reader of a corrupt manifest are reported as errors, also on + // executor threads. + ManifestFile corrupt = second_manifest_; + corrupt.manifest_path = table_location_ + "/metadata/corrupt.avro"; + ASSERT_THAT(file_io_->WriteFile(corrupt.manifest_path, "Obj\x01 not avro"), IsOk()); + test::ThreadExecutor executor; + EXPECT_THAT(ReachableFileUtil::LiveFileLocationsForManifests( + {shared_manifest_, corrupt}, *metadata_, file_io_, std::ref(executor)), + IsError(ErrorKind::kInvalidManifest)); + + // Results read on executor threads are merged into one set. + test::ThreadExecutor threads; + ICEBERG_UNWRAP_OR_FAIL(auto threaded, ReachableFileUtil::LiveFileLocationsForManifests( + {shared_manifest_, second_manifest_}, + *metadata_, file_io_, std::ref(threads))); + EXPECT_THAT(threaded, UnorderedElementsAre(table_location_ + "/data/shared.parquet", + table_location_ + "/data/live.parquet")); +} + +} // namespace iceberg diff --git a/src/iceberg/test/std_io.h b/src/iceberg/test/std_io.h index b5b2a617c..2c7f273c3 100644 --- a/src/iceberg/test/std_io.h +++ b/src/iceberg/test/std_io.h @@ -232,6 +232,9 @@ class StdInputFile : public InputFile { } std::error_code ec; auto size = std::filesystem::file_size(location_, ec); + if (ec == std::errc::no_such_file_or_directory) { + return NotFound("File does not exist: {}", location_); + } if (ec) { return IOError("Failed to get file size for {}: {}", location_, ec.message()); } diff --git a/src/iceberg/test/task_group_test.cc b/src/iceberg/test/task_group_test.cc index 0b04a333d..cb7bf0a2d 100644 --- a/src/iceberg/test/task_group_test.cc +++ b/src/iceberg/test/task_group_test.cc @@ -20,9 +20,12 @@ #include "iceberg/util/task_group.h" #include +#include #include #include #include +#include +#include #include #include @@ -259,6 +262,103 @@ TEST(TaskGroupTest, ParallelSubmitErrors) { EXPECT_EQ(executor.submit_count(), 2); } +TEST(TaskGroupTest, ParallelSubmitThrowWaitsForAcceptedTasks) { + // Accepts the first task on a thread and throws on later submissions. + class ThrowingExecutor final : public Executor { + public: + ~ThrowingExecutor() override { + if (thread_.joinable()) { + thread_.join(); + } + } + + Status Submit(ExecutorTask task) override { + if (thread_.joinable()) { + throw std::runtime_error("executor shut down"); + } + thread_ = std::thread(std::move(task)); + return {}; + } + + private: + std::thread thread_; + }; + + // Declared before the executor so that it outlives the worker thread. + std::atomic finished = false; + ThrowingExecutor executor; + TaskGroup group; + + group.SetExecutor(std::ref(executor)); + group.Submit([&]() -> Status { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + finished.store(true, std::memory_order_relaxed); + return {}; + }); + group.Submit([]() -> Status { return {}; }); + + auto status = std::move(group).Run(); + EXPECT_THAT(status, IsError(ErrorKind::kUnknownError)); + EXPECT_THAT(status, HasErrorMessage("executor shut down")); + EXPECT_TRUE(finished.load(std::memory_order_relaxed)); +} + +TEST(TaskGroupTest, TaskExceptionBecomesError) { + // An exception thrown by a task on a worker thread must not escape. It is reported + // as an error on the waiting thread. + test::ThreadExecutor executor; + TaskGroup group; + + group.SetExecutor(std::ref(executor)); + group.Submit([]() -> Status { throw std::runtime_error("task exploded"); }); + + auto status = std::move(group).Run(); + EXPECT_THAT(status, IsError(ErrorKind::kUnknownError)); + EXPECT_THAT(status, HasErrorMessage("task exploded")); +} + +TEST(TaskGroupTest, ParallelDroppedTaskWaitsForOtherTasks) { + // Drops the first task after accepting it and runs later tasks on a thread. + class DroppingExecutor final : public Executor { + public: + ~DroppingExecutor() override { + if (thread_.joinable()) { + thread_.join(); + } + } + + Status Submit(ExecutorTask task) override { + if (dropped_) { + thread_ = std::thread(std::move(task)); + } + dropped_ = true; + return {}; + } + + private: + bool dropped_ = false; + std::thread thread_; + }; + + // Declared before the executor so that it outlives the worker thread. + std::atomic finished = false; + DroppingExecutor executor; + TaskGroup group; + + group.SetExecutor(std::ref(executor)); + group.Submit([]() -> Status { return {}; }); + group.Submit([&]() -> Status { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + finished.store(true, std::memory_order_relaxed); + return {}; + }); + + auto status = std::move(group).Run(); + EXPECT_THAT(status, IsError(ErrorKind::kUnknownError)); + EXPECT_THAT(status, HasErrorMessage("Task did not complete")); + EXPECT_TRUE(finished.load(std::memory_order_relaxed)); +} + TEST(TaskGroupTest, RetriesTasks) { test::FakeRetryEnvironment fake_retry; ScopedRetryTestHooks retry_hooks(fake_retry.hooks()); diff --git a/src/iceberg/update/expire_snapshots.cc b/src/iceberg/update/expire_snapshots.cc index 541d16e45..c4bc8e641 100644 --- a/src/iceberg/update/expire_snapshots.cc +++ b/src/iceberg/update/expire_snapshots.cc @@ -20,12 +20,17 @@ #include "iceberg/update/expire_snapshots.h" #include +#include #include #include +#include #include +#include +#include #include #include #include +#include #include #include #include @@ -44,6 +49,7 @@ #include "iceberg/util/error_collector.h" #include "iceberg/util/executor_util_internal.h" #include "iceberg/util/macros.h" +#include "iceberg/util/reachable_file_util.h" #include "iceberg/util/retry_util.h" #include "iceberg/util/snapshot_util.h" #include "iceberg/util/string_util.h" @@ -62,6 +68,28 @@ Result> MakeManifestReader( return ManifestReader::Make(manifest, file_io, std::move(schema), specs_by_id.get()); } +/// \brief True if a manifest could not be read because its file is missing. +/// +/// FileIO implementations report a missing file as kNotFound, or as kIOError when it +/// is opened. kIOError also reports a failed read of a file that exists, which leaves +/// its entries unknown, so the file is skipped only if checking its size reports it +/// as missing. +bool IsMissingFile(const Error& error, const std::shared_ptr& io, + const std::string& location) { + if (error.kind == ErrorKind::kNotFound) { + return true; + } + if (error.kind != ErrorKind::kIOError) { + return false; + } + auto file = io->NewInputFile(location); + if (!file.has_value()) { + return file.error().kind == ErrorKind::kNotFound; + } + auto size = file.value()->Size(); + return !size.has_value() && size.error().kind == ErrorKind::kNotFound; +} + /// \brief Abstract strategy for cleaning up files after snapshot expiration. class FileCleanupStrategy { public: @@ -241,9 +269,13 @@ class ReachableFileCleanup : public FileCleanupStrategy { if (!manifests_to_delete.empty()) { if (level == CleanupLevel::kAll) { - // Deleting data and delete files. - auto files_to_delete = FindFilesToDelete( - metadata_before_expiration, manifests_to_delete, current_manifests); + // Deleting data and delete files. Stop before deleting any file if the files + // to delete cannot be determined. They stay in storage for orphan file + // cleanup, and the manifests that list them stay for inspection. + ICEBERG_ASSIGN_OR_RAISE( + auto files_to_delete, + FindFilesToDelete(metadata_before_expiration, metadata_after_expiration, + manifests_to_delete, current_manifests)); DeleteFiles(files_to_delete); } @@ -265,25 +297,11 @@ class ReachableFileCleanup : public FileCleanupStrategy { } private: - /// \brief Collect manifests for a snapshot into manifests. - Result> ReadManifestsForSnapshot( - const TableMetadata& metadata, int64_t snapshot_id) { - ICEBERG_ASSIGN_OR_RAISE(auto snapshot, metadata.SnapshotById(snapshot_id)); - - SnapshotReader snapshot_reader(snapshot.get()); - ICEBERG_ASSIGN_OR_RAISE(auto snapshot_manifests, snapshot_reader.Manifests(file_io_)); - - return snapshot_manifests | std::views::as_rvalue | - std::ranges::to>(); - } - /// \brief Collect manifests for a set of snapshots. Result> ReadManifests( const TableMetadata& metadata, const std::unordered_set& snapshot_ids) { - return ParallelCollect(plan_executor_, snapshot_ids, - [this, &metadata](int64_t snapshot_id) { - return ReadManifestsForSnapshot(metadata, snapshot_id); - }); + return ReachableFileUtil::ManifestsForSnapshots(metadata, snapshot_ids, file_io_, + plan_executor_); } /// \brief Remove manifests still referenced by retained snapshots. @@ -305,24 +323,6 @@ class ReachableFileCleanup : public FileCleanupStrategy { return manifests_to_delete; } - Result> ReadLiveFilePaths( - const TableMetadata& metadata, const ManifestFile& manifest) { - // TODO(shangxinli): optimize by only reading file paths - ICEBERG_ASSIGN_OR_RAISE(auto reader, - MakeManifestReader(manifest, file_io_, metadata)); - reader->Select({"file_path"}); - ICEBERG_ASSIGN_OR_RAISE(auto entries, reader->LiveEntries()); - - std::unordered_set file_paths; - for (const auto& entry : entries) { - if (entry.data_file) { - file_paths.insert(entry.data_file->file_path); - } - } - - return file_paths; - } - /// \brief Project manifests to manifest paths for deletion. std::unordered_set ManifestPaths( const std::unordered_set& manifests) const { @@ -335,40 +335,49 @@ class ReachableFileCleanup : public FileCleanupStrategy { } /// \brief Find files to delete from manifests being removed. - std::unordered_set FindFilesToDelete( - const TableMetadata& metadata, + /// + /// Expired manifests are resolved against the pre-expiration metadata, which may + /// still hold their partition specs, and retained manifests against the committed + /// metadata, which holds the specs that a transaction may have added. + Result> FindFilesToDelete( + const TableMetadata& expired_metadata, const TableMetadata& retained_metadata, const std::unordered_set& manifests_to_delete, const std::unordered_set& current_manifests) { + // Resolve the schema up front, so that a missing schema is not mistaken for a + // missing manifest below. + ICEBERG_RETURN_UNEXPECTED(expired_metadata.Schema()); + // Collect live file paths from manifests being deleted. auto live_file_results = ParallelCollect( plan_executor_, manifests_to_delete, - [this, &metadata]( + [this, &expired_metadata]( const ManifestFile& manifest) -> Result> { - auto result = ReadLiveFilePaths(metadata, manifest); - // Ignore expired-manifest read failures and keep scanning candidates. - if (!result.has_value()) { + ICEBERG_RETURN_UNEXPECTED( + expired_metadata.PartitionSpecById(manifest.partition_spec_id)); + auto result = + ReachableFileUtil::LiveFileLocations(manifest, expired_metadata, file_io_); + // Skip expired manifests that are missing and keep scanning candidates, so + // that the remaining expired files are still deleted. The missing manifest's + // data files stay in storage and can be found later by orphan file cleanup. + // This is what IgnoresExpiredDeleteManifestReadFailures asserts. Other + // failures, such as a manifest that fails to decode, stop the cleanup. + if (!result.has_value() && + IsMissingFile(result.error(), file_io_, manifest.manifest_path)) { return std::unordered_set{}; } - return std::move(result).value(); + return result; }); - if (!live_file_results.has_value()) { - return {}; - } + ICEBERG_RETURN_UNEXPECTED(live_file_results); auto files_to_delete = std::move(live_file_results).value(); if (files_to_delete.empty()) { return files_to_delete; } // Remove files still referenced by current manifests. - auto current_live_results = - ParallelCollect(plan_executor_, current_manifests, - [this, &metadata](const ManifestFile& manifest) { - return ReadLiveFilePaths(metadata, manifest); - }); + auto current_live_results = ReachableFileUtil::LiveFileLocationsForManifests( + current_manifests, retained_metadata, file_io_, plan_executor_); // Fail closed if any retained manifest cannot be read safely. - if (!current_live_results.has_value()) { - return std::unordered_set{}; - } + ICEBERG_RETURN_UNEXPECTED(current_live_results); for (const auto& file_path : current_live_results.value()) { files_to_delete.erase(file_path); } @@ -455,7 +464,10 @@ class IncrementalFileCleanup : public FileCleanupStrategy { // Find manifests still referenced by a valid snapshot but written by an // expired snapshot. Their deleted entries point at data files now safe to - // remove and become candidates for manifests_to_scan below. + // remove and become candidates for manifests_to_scan below. Full cleanup also + // keeps one descriptor per retained manifest, to keep paths that are live again. + std::mutex retained_mutex; + std::map retained_by_path; ICEBERG_ASSIGN_OR_RAISE( auto valid_manifest_results, ParallelCollect( @@ -466,15 +478,19 @@ class IncrementalFileCleanup : public FileCleanupStrategy { if (!snapshot) { return {}; } + // A retained manifest list that cannot be read would hide manifests + // still in use, so stop instead of deleting them. SnapshotReader snapshot_reader(snapshot.get()); - auto manifests_result = snapshot_reader.Manifests(file_io_); - if (!manifests_result.has_value()) { - // best-effort - return {}; - } - auto manifests = std::move(manifests_result).value(); + ICEBERG_ASSIGN_OR_RAISE(auto manifests, + snapshot_reader.Manifests(file_io_)); std::unordered_set valid_manifest_result; std::unordered_set scan_manifest_result; + if (level == CleanupLevel::kAll) { + std::lock_guard lock(retained_mutex); + for (const auto& manifest : manifests) { + retained_by_path.try_emplace(manifest.manifest_path, manifest); + } + } for (auto& manifest : manifests) { valid_manifest_result.insert(manifest.manifest_path); @@ -539,10 +555,16 @@ class IncrementalFileCleanup : public FileCleanupStrategy { return {}; } + // Skip a missing manifest list, but stop if one that exists cannot be + // read, since the files it lists are then unknown. SnapshotReader snapshot_reader(snapshot.get()); auto manifests_result = snapshot_reader.Manifests(file_io_); if (!manifests_result.has_value()) { - return {}; + if (IsMissingFile(manifests_result.error(), file_io_, + snapshot->manifest_list)) { + return {}; + } + return unexpected(std::move(manifests_result).error()); } auto manifests = std::move(manifests_result).value(); @@ -587,8 +609,14 @@ class IncrementalFileCleanup : public FileCleanupStrategy { // Manifests may reference partition specs that were pruned during expiration // when CleanExpiredMetadata is enabled, so resolve schemas/specs against the // pre-expiration metadata. - auto files_to_delete = FindFilesToDelete( - metadata_before_expiration, manifests_to_scan, manifests_to_revert, valid_ids); + // Stop before deleting any file if planning fails. The expired files stay in + // storage for orphan file cleanup, and the manifests that list them stay for + // inspection. + ICEBERG_ASSIGN_OR_RAISE( + auto files_to_delete, + FindFilesToDelete(metadata_before_expiration, metadata_after_expiration, + manifests_to_scan, manifests_to_revert, valid_ids, + valid_manifests, retained_by_path)); DeleteFiles(files_to_delete); } @@ -608,29 +636,51 @@ class IncrementalFileCleanup : public FileCleanupStrategy { } private: + /// \brief Read the entries of a manifest, or no entries if the manifest is missing + /// and no retained snapshot references it. + /// + /// Other failures are returned, so that cleanup stops before deleting metadata + /// whose data files could not be determined. + Result> ReadEntries( + const ManifestFile& manifest, const TableMetadata& metadata, + const std::unordered_set& retained_manifests) { + auto entries = [&]() -> Result> { + ICEBERG_ASSIGN_OR_RAISE(auto reader, + MakeManifestReader(manifest, file_io_, metadata)); + // Only the entry status, snapshot ID and file path are used, so partition + // values and metrics are not decoded. + reader->Select({"file_path"}); + return reader->Entries(); + }(); + if (!entries.has_value() && !retained_manifests.contains(manifest.manifest_path) && + IsMissingFile(entries.error(), file_io_, manifest.manifest_path)) { + return std::vector{}; + } + return entries; + } + /// \brief Resolve the data files that the incremental pass identified for deletion. /// /// For manifests_to_scan, read DELETED entries whose snapshot id is no longer valid. /// For manifests_to_revert, read every ADDED entry. - std::unordered_set FindFilesToDelete( - const TableMetadata& metadata, + Result> FindFilesToDelete( + const TableMetadata& metadata, const TableMetadata& retained_metadata, const std::unordered_set& manifests_to_scan, const std::unordered_set& manifests_to_revert, - const std::unordered_set& valid_ids) { + const std::unordered_set& valid_ids, + const std::unordered_set& retained_manifests, + const std::map& retained_manifest_files) { + // Resolve the schema up front, so that a missing schema is not mistaken for a + // missing manifest below. + ICEBERG_RETURN_UNEXPECTED(metadata.Schema()); auto files_to_delete = ParallelCollect( plan_executor_, manifests_to_scan, - [this, &metadata, &valid_ids]( + [this, &metadata, &valid_ids, &retained_manifests]( const ManifestFile& manifest) -> Result> { - auto reader_result = MakeManifestReader(manifest, file_io_, metadata); - if (!reader_result.has_value()) { - return {}; - } - auto entries_result = reader_result.value()->Entries(); - if (!entries_result.has_value()) { - return {}; - } + ICEBERG_ASSIGN_OR_RAISE(auto entries, + ReadEntries(manifest, metadata, retained_manifests)); std::unordered_set result; - for (const auto& entry : entries_result.value()) { + for (const auto& entry : entries) { if (entry.status == ManifestStatus::kDeleted && entry.snapshot_id.has_value() && !valid_ids.contains(entry.snapshot_id.value()) && entry.data_file) { @@ -640,29 +690,97 @@ class IncrementalFileCleanup : public FileCleanupStrategy { return result; }, manifests_to_revert, - [this, &metadata]( + [this, &metadata, &retained_manifests]( const ManifestFile& manifest) -> Result> { - auto reader_result = MakeManifestReader(manifest, file_io_, metadata); - if (!reader_result.has_value()) { - return {}; - } - auto entries_result = reader_result.value()->Entries(); - if (!entries_result.has_value()) { - return {}; - } + ICEBERG_ASSIGN_OR_RAISE(auto entries, + ReadEntries(manifest, metadata, retained_manifests)); std::unordered_set result; - for (const auto& entry : entries_result.value()) { + for (const auto& entry : entries) { if (entry.status == ManifestStatus::kAdded && entry.data_file) { result.insert(entry.data_file->file_path); } } return result; }); - if (!files_to_delete.has_value()) { - return {}; - } + ICEBERG_RETURN_UNEXPECTED(files_to_delete); auto [scan_results, revert_results] = std::move(files_to_delete).value(); scan_results.merge(revert_results); + if (scan_results.empty()) { + return scan_results; + } + + // A path can be live again in a retained snapshot, for example a file that was + // re-added, or a Puffin file that also holds live deletion vectors. Keep those. + // Entries are streamed and only matching candidates are kept, so memory stays + // proportional to the candidates. + // Manifests are skipped once every candidate is known to be live. A manifest + // that cannot be read only matters if some candidate is not, so read errors are + // reported after all manifests were read, independent of the order. + std::mutex live_mutex; + std::optional read_error; + std::unordered_set live_candidates; + std::atomic all_live = false; + TaskGroup group; + group.SetExecutor(plan_executor_); + for (const auto& manifest : retained_manifest_files | std::views::values) { + // A manifest without added or existing entries has no live entries. + if (!manifest.has_added_files() && !manifest.has_existing_files()) { + continue; + } + group.Submit([this, &manifest, &retained_metadata, &scan_results, &live_mutex, + &live_candidates, &all_live, &read_error]() -> Status { + if (all_live.load(std::memory_order_relaxed)) { + return {}; + } + auto read = [&]() -> Status { + ICEBERG_ASSIGN_OR_RAISE(auto schema, retained_metadata.Schema()); + ICEBERG_ASSIGN_OR_RAISE( + auto spec, retained_metadata.PartitionSpecById(manifest.partition_spec_id)); + ICEBERG_ASSIGN_OR_RAISE( + auto reader, ManifestReader::Make(manifest, file_io_, std::move(schema), + std::move(spec))); + reader->Select({"file_path"}); + ICEBERG_ASSIGN_OR_RAISE(auto entries, reader->LiveEntriesStream()); + while (true) { + ICEBERG_ASSIGN_OR_RAISE(auto entry, entries->Next()); + if (!entry.has_value() || all_live.load(std::memory_order_relaxed)) { + return {}; + } + if (entry->data_file && scan_results.contains(entry->data_file->file_path)) { + std::lock_guard lock(live_mutex); + live_candidates.insert(std::move(entry->data_file->file_path)); + if (live_candidates.size() == scan_results.size()) { + all_live.store(true, std::memory_order_relaxed); + } + } + } + }; + // Readers of malformed files may throw, which is a read error as well. + Status status; + try { + status = read(); + } catch (const std::exception& e) { + status = + InvalidManifest("Failed to read {}: {}", manifest.manifest_path, e.what()); + } catch (...) { + status = InvalidManifest("Failed to read {}", manifest.manifest_path); + } + if (!status.has_value()) { + std::lock_guard lock(live_mutex); + if (!read_error.has_value()) { + read_error = std::move(status).error(); + } + } + return {}; + }); + } + ICEBERG_RETURN_UNEXPECTED(std::move(group).Run()); + if (read_error.has_value() && !all_live.load(std::memory_order_relaxed)) { + return unexpected(std::move(read_error).value()); + } + for (const auto& path : live_candidates) { + scan_results.erase(path); + } return scan_results; } }; diff --git a/src/iceberg/util/reachable_file_util.cc b/src/iceberg/util/reachable_file_util.cc new file mode 100644 index 000000000..57cf74f58 --- /dev/null +++ b/src/iceberg/util/reachable_file_util.cc @@ -0,0 +1,272 @@ +/* + * 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 "iceberg/util/reachable_file_util.h" + +#include +#include +#include +#include +#include + +#include "iceberg/manifest/manifest_entry.h" +#include "iceberg/manifest/manifest_reader.h" +#include "iceberg/snapshot.h" +#include "iceberg/statistics_file.h" +#include "iceberg/table_metadata.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/task_group.h" + +namespace iceberg { + +namespace { + +/// \brief Run a read and report exceptions thrown by file readers as errors. +/// +/// Readers of malformed files may throw. Converting the exception keeps it from +/// escaping executor tasks. It is reported with the given kind instead of kIOError, +/// so that callers can tell a file that failed to decode from one that could not be +/// opened. The fallback message fits the small-string buffer, so it does not +/// allocate if formatting the message fails. +template +auto CatchReadExceptions(ErrorKind kind, std::string_view location, F&& read) + -> decltype(read()) { + try { + try { + return read(); + } catch (const std::exception& e) { + return unexpected( + Error{.kind = kind, + .message = std::format("Failed to read {}: {}", location, e.what())}); + } catch (...) { + return unexpected( + Error{.kind = kind, .message = std::format("Failed to read {}", location)}); + } + } catch (...) { + return unexpected(Error{.kind = kind, .message = "Read failed"}); + } +} + +/// \brief Return the snapshots with the given IDs, failing if any is missing. +Result>> SnapshotsByIds( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids) { + std::vector> snapshots; + if (snapshot_ids.empty()) { + return snapshots; + } + // One pass over the snapshots, keeping the first match for each requested ID. + snapshots.reserve(snapshot_ids.size()); + std::unordered_set found; + found.reserve(snapshot_ids.size()); + for (const auto& snapshot : metadata.snapshots) { + if (snapshot && snapshot_ids.contains(snapshot->snapshot_id) && + found.insert(snapshot->snapshot_id).second) { + snapshots.push_back(snapshot); + if (found.size() == snapshot_ids.size()) { + return snapshots; + } + } + } + for (int64_t snapshot_id : snapshot_ids) { + if (!found.contains(snapshot_id)) { + return NotFound("Snapshot with ID {} is not found", snapshot_id); + } + } + return snapshots; +} + +template +std::vector StatisticsFilesLocationsIf(const TableMetadata& metadata, + Predicate&& predicate) { + std::vector locations; + for (const auto& stats_file : metadata.statistics) { + if (stats_file && predicate(stats_file->snapshot_id)) { + locations.push_back(stats_file->path); + } + } + for (const auto& stats_file : metadata.partition_statistics) { + if (stats_file && predicate(stats_file->snapshot_id)) { + locations.push_back(stats_file->path); + } + } + return locations; +} + +template +std::vector ManifestListLocationsIf(const TableMetadata& metadata, + Predicate&& predicate) { + std::vector locations; + for (const auto& snapshot : metadata.snapshots) { + if (snapshot && !snapshot->manifest_list.empty() && + predicate(snapshot->snapshot_id)) { + locations.push_back(snapshot->manifest_list); + } + } + return locations; +} + +Result> ReadManifests( + const Snapshot& snapshot, const std::shared_ptr& io) { + return CatchReadExceptions(ErrorKind::kInvalidManifestList, snapshot.manifest_list, + [&]() -> Result> { + SnapshotReader snapshot_reader(&snapshot); + ICEBERG_ASSIGN_OR_RAISE(auto snapshot_manifests, + snapshot_reader.Manifests(io)); + + return snapshot_manifests | std::views::as_rvalue | + std::ranges::to>(); + }); +} + +/// \brief Run a read for each item and merge the resulting sets. +/// +/// Reads run on the executor if one is given, or serially otherwise. Each result is +/// merged as soon as it is read, since results usually overlap, and errors are +/// aggregated as TaskGroup does. +template +Result> CollectSets(OptionalExecutor executor, const Range& items, + Read&& read) { + std::unordered_set result; + std::mutex mutex; + // Set when merging fails. Reporting the failure allocates, so it is reported after + // the tasks finish rather than from an executor thread. + std::atomic merge_failed = false; + TaskGroup group; + group.SetExecutor(executor); + for (const auto& item : items) { + group.Submit([&result, &mutex, &merge_failed, &read, &item]() -> Status { + auto values = read(item); + if (!values.has_value()) { + // Move the error so that returning it does not allocate on an executor thread. + return unexpected(std::move(values).error()); + } + try { + std::lock_guard lock(mutex); + result.merge(*values); + } catch (...) { + merge_failed.store(true, std::memory_order_relaxed); + } + return {}; + }); + } + ICEBERG_RETURN_UNEXPECTED(std::move(group).Run()); + if (merge_failed.load(std::memory_order_relaxed)) { + return UnknownError("Failed to merge read results"); + } + return result; +} + +Result> ReadManifests( + const std::vector>& snapshots, + const std::shared_ptr& io, OptionalExecutor executor) { + return CollectSets(executor, snapshots, + [&io](const std::shared_ptr& snapshot) { + return ReadManifests(*snapshot, io); + }); +} + +} // namespace + +std::unordered_set ReachableFileUtil::MetadataFileLocations( + const TableMetadata& metadata, std::string_view metadata_file_location) { + std::unordered_set locations; + if (!metadata_file_location.empty()) { + locations.emplace(metadata_file_location); + } + for (const auto& entry : metadata.metadata_log) { + locations.insert(entry.metadata_file); + } + return locations; +} + +std::vector ReachableFileUtil::ManifestListLocations( + const TableMetadata& metadata) { + return ManifestListLocationsIf(metadata, [](int64_t) { return true; }); +} + +std::vector ReachableFileUtil::ManifestListLocations( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids) { + return ManifestListLocationsIf( + metadata, [&](int64_t snapshot_id) { return snapshot_ids.contains(snapshot_id); }); +} + +std::vector ReachableFileUtil::StatisticsFilesLocations( + const TableMetadata& metadata) { + return StatisticsFilesLocationsIf(metadata, [](int64_t) { return true; }); +} + +std::vector ReachableFileUtil::StatisticsFilesLocationsForSnapshots( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids) { + return StatisticsFilesLocationsIf( + metadata, [&](int64_t snapshot_id) { return snapshot_ids.contains(snapshot_id); }); +} + +Result> ReachableFileUtil::ReachableManifests( + const TableMetadata& metadata, const std::shared_ptr& io, + OptionalExecutor executor) { + auto snapshots = + metadata.snapshots | + std::views::filter([](const auto& snapshot) { return snapshot != nullptr; }) | + std::ranges::to>>(); + return ReadManifests(snapshots, io, executor); +} + +Result> ReachableFileUtil::ManifestsForSnapshots( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids, + const std::shared_ptr& io, OptionalExecutor executor) { + ICEBERG_ASSIGN_OR_RAISE(auto snapshots, SnapshotsByIds(metadata, snapshot_ids)); + return ReadManifests(snapshots, io, executor); +} + +Result> ReachableFileUtil::LiveFileLocations( + const ManifestFile& manifest, const TableMetadata& metadata, + const std::shared_ptr& io) { + return CatchReadExceptions( + ErrorKind::kInvalidManifest, manifest.manifest_path, + [&]() -> Result> { + ICEBERG_ASSIGN_OR_RAISE(auto schema, metadata.Schema()); + ICEBERG_ASSIGN_OR_RAISE(auto spec, + metadata.PartitionSpecById(manifest.partition_spec_id)); + ICEBERG_ASSIGN_OR_RAISE( + auto reader, + ManifestReader::Make(manifest, io, std::move(schema), std::move(spec))); + // TODO(shangxinli): optimize by only reading file paths + reader->Select({"file_path"}); + ICEBERG_ASSIGN_OR_RAISE(auto entries, reader->LiveEntries()); + + std::unordered_set file_paths; + for (const auto& entry : entries) { + if (entry.data_file) { + file_paths.insert(entry.data_file->file_path); + } + } + return file_paths; + }); +} + +Result> ReachableFileUtil::LiveFileLocationsForManifests( + const std::unordered_set& manifests, const TableMetadata& metadata, + const std::shared_ptr& io, OptionalExecutor executor) { + return CollectSets(executor, manifests, + [&metadata, &io](const ManifestFile& manifest) { + return LiveFileLocations(manifest, metadata, io); + }); +} + +} // namespace iceberg diff --git a/src/iceberg/util/reachable_file_util.h b/src/iceberg/util/reachable_file_util.h new file mode 100644 index 000000000..957d7002b --- /dev/null +++ b/src/iceberg/util/reachable_file_util.h @@ -0,0 +1,133 @@ +/* + * 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. + */ + +#pragma once + +/// \file iceberg/util/reachable_file_util.h +/// \brief Utility functions for locating files reachable from table metadata. + +#include +#include +#include +#include +#include +#include + +#include "iceberg/iceberg_export.h" +#include "iceberg/manifest/manifest_list.h" +#include "iceberg/result.h" +#include "iceberg/type_fwd.h" +#include "iceberg/util/executor.h" + +namespace iceberg { + +/// \brief Utility functions for locating files reachable from table metadata. +/// +/// The location functions mirror Java's org.apache.iceberg.ReachableFileUtil, except +/// that previous metadata files are not read. The manifest functions have no +/// counterpart there; they read manifest lists and manifests to find the manifests and +/// content files that snapshots reference. +class ICEBERG_EXPORT ReachableFileUtil { + public: + /// \brief Returns the locations of JSON metadata files of a table. + /// + /// These are the given metadata file and the files listed in its metadata log, as in + /// Java with recursive set to false. Previous metadata files are not read; files that + /// were pruned from the metadata log are therefore not returned. + /// + /// \param metadata The table metadata + /// \param metadata_file_location The location of the metadata file; skipped if empty + static std::unordered_set MetadataFileLocations( + const TableMetadata& metadata, std::string_view metadata_file_location); + + /// \brief Returns the manifest list locations of all snapshots. + static std::vector ManifestListLocations(const TableMetadata& metadata); + + /// \brief Returns the manifest list locations of the given snapshots. + /// + /// \param metadata The table metadata + /// \param snapshot_ids IDs of the snapshots whose manifest lists are returned + static std::vector ManifestListLocations( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids); + + /// \brief Returns the locations of all statistics and partition statistics files. + static std::vector StatisticsFilesLocations(const TableMetadata& metadata); + + /// \brief Returns the locations of statistics and partition statistics files for the + /// given snapshots. + /// + /// \param metadata The table metadata + /// \param snapshot_ids IDs of the snapshots whose statistics files are returned + static std::vector StatisticsFilesLocationsForSnapshots( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids); + + /// \brief Returns the manifests referenced by any snapshot. + /// + /// Manifests are deduplicated by path. When manifest lists describe the same + /// manifest differently, for example with different first row IDs after a v3 + /// upgrade, which descriptor is returned is unspecified; use the result for the + /// manifest's path and contents, and read per-snapshot descriptors from the snapshot. + /// + /// \param metadata The table metadata + /// \param io The FileIO used to read manifest lists + /// \param executor Executor to read manifest lists with, or std::nullopt to read them + /// serially + static Result> ReachableManifests( + const TableMetadata& metadata, const std::shared_ptr& io, + OptionalExecutor executor = std::nullopt); + + /// \brief Returns the manifests referenced by the given snapshots. + /// + /// Manifests are deduplicated by path, as in ReachableManifests. + /// + /// \param metadata The table metadata + /// \param snapshot_ids IDs of the snapshots to read; each must exist in metadata + /// \param io The FileIO used to read manifest lists + /// \param executor Executor to read manifest lists with, or std::nullopt to read them + /// serially + static Result> ManifestsForSnapshots( + const TableMetadata& metadata, const std::unordered_set& snapshot_ids, + const std::shared_ptr& io, OptionalExecutor executor = std::nullopt); + + /// \brief Returns the paths of data and delete files in live entries of a manifest. + /// + /// \param manifest The manifest to read + /// \param metadata Table metadata used for the current schema and the manifest's + /// partition spec + /// \param io The FileIO used to read the manifest + static Result> LiveFileLocations( + const ManifestFile& manifest, const TableMetadata& metadata, + const std::shared_ptr& io); + + /// \brief Returns the paths of data and delete files in live entries of manifests. + /// + /// Fails if any manifest cannot be read. + /// + /// \param manifests The manifests to read + /// \param metadata Table metadata used for the current schema and the manifests' + /// partition specs + /// \param io The FileIO used to read the manifests + /// \param executor Executor to read manifests with, or std::nullopt to read them + /// serially + static Result> LiveFileLocationsForManifests( + const std::unordered_set& manifests, const TableMetadata& metadata, + const std::shared_ptr& io, OptionalExecutor executor = std::nullopt); +}; + +} // namespace iceberg diff --git a/src/iceberg/util/task_group.cc b/src/iceberg/util/task_group.cc index 6e2cc8d80..98bf3d43c 100644 --- a/src/iceberg/util/task_group.cc +++ b/src/iceberg/util/task_group.cc @@ -19,6 +19,7 @@ #include "iceberg/util/task_group.h" +#include #include #include #include @@ -47,17 +48,32 @@ Status AggregateTaskErrors(std::vector errors) { } Result> SubmitTask(Executor& executor, FnOnce task) { - std::promise promise; - auto future = promise.get_future(); - - ExecutorTask executor_task( - [promise = std::move(promise), task = std::move(task)]() mutable { - promise.set_value(std::move(task)()); - }); - - ICEBERG_RETURN_UNEXPECTED(executor.Submit(std::move(executor_task))); - - return future; + // Submitting may throw, for example when allocating the promise or inside + // Executor::Submit. Report it as an error so that the caller still waits for tasks + // that were accepted earlier, which may reference its state. + try { + std::promise promise; + auto future = promise.get_future(); + + ExecutorTask executor_task( + [promise = std::move(promise), task = std::move(task)]() mutable { + // An executor may run the task inline, so an exception from the task itself + // must not escape either. It is converted to an error on the waiting thread, + // where reporting it may allocate. + try { + promise.set_value(std::move(task)()); + } catch (...) { + promise.set_exception(std::current_exception()); + } + }); + + ICEBERG_RETURN_UNEXPECTED(executor.Submit(std::move(executor_task))); + return future; + } catch (const std::exception& e) { + return UnknownError("Failed to submit task: {}", e.what()); + } catch (...) { + return UnknownError("Failed to submit task: unknown exception"); + } } } // namespace @@ -77,6 +93,19 @@ Status RunTasksParallel(Executor& executor, std::vector> tasks) std::vector> futures; futures.reserve(tasks.size()); + // Accepted tasks may reference the caller's state, so wait for all of them before + // returning, also when collecting errors below throws. + struct WaitForAll { + std::vector>& futures; + ~WaitForAll() { + for (auto& future : futures) { + if (future.valid()) { + future.wait(); + } + } + } + } wait_for_all{futures}; + std::vector errors; for (auto& task : tasks) { auto future = SubmitTask(executor, std::move(task)); @@ -88,7 +117,25 @@ Status RunTasksParallel(Executor& executor, std::vector> tasks) } for (auto& future : futures) { - auto status = future.get(); + // An executor may drop an accepted task, for example on shutdown, which breaks + // its promise. Report that as an error and keep waiting for the other tasks. + Status status; + try { + status = future.get(); + } catch (const std::future_error& e) { + // A task dropped by its executor breaks its promise. A task can also rethrow a + // broken promise of another future, so the failure is not attributed to the + // executor. + if (e.code() == std::make_error_code(std::future_errc::broken_promise)) { + status = UnknownError("Task did not complete: {}", e.what()); + } else { + status = UnknownError("Task threw: {}", e.what()); + } + } catch (const std::exception& e) { + status = UnknownError("Task threw: {}", e.what()); + } catch (...) { + status = UnknownError("Task threw an unknown exception"); + } if (!status.has_value()) { errors.push_back(std::move(status.error())); }