diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 285d0d8ed..ef736fe1c 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -26,6 +26,7 @@ set(ICEBERG_SOURCES catalog/memory/in_memory_catalog.cc catalog/session_catalog.cc catalog/session_context.cc + content_cache.cc data_table_scan.cc delete_file_index.cc deletes/dv_util.cc diff --git a/src/iceberg/content_cache.cc b/src/iceberg/content_cache.cc new file mode 100644 index 000000000..6f52970c1 --- /dev/null +++ b/src/iceberg/content_cache.cc @@ -0,0 +1,715 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include + +#include "iceberg/content_cache_internal.h" +#include "iceberg/exception.h" +#include "iceberg/file_io_internal.h" +#include "iceberg/util/cache_internal.h" +#include "iceberg/util/error_util_internal.h" +#include "iceberg/util/macros.h" +#include "iceberg/util/property_util.h" +#include "iceberg/util/string_util.h" + +namespace iceberg::internal { + +using CachedFiles = LruCache; + +// Owned by the table. The registry guards files and position under its mutex. +// A position is valid while files is non-null. +struct ContentCacheRegistration { + using Entries = std::list>; + ContentCacheRegistration(FileIO* io, const ContentCacheRegistration* inner) + : storage_io(inner ? inner->storage_io : io), inner(inner) {} + + bool IsLayeredOn(const ContentCacheRegistration& table) const { + for (auto* ancestor = this; ancestor; ancestor = ancestor->inner) { + if (ancestor == &table) { + return true; + } + } + return false; + } + + FileIO* const storage_io; + // The wrapped FileIO keeps the inner registration alive. + const ContentCacheRegistration* const inner; + // Protected by the shared storage mutex, including for inactive registrations. + uint64_t invalidations = 0; + Entries::iterator position; + std::shared_ptr files; + // Accessed under the per-table mutex. A miss needs no registry lock. + std::weak_ptr last_files; +}; + +// Adapters over one storage FileIO share mutation state. Each table still owns +// its own cached bytes. The registry mutex protects the list of bound caches. +struct ContentCacheStorage { + explicit ContentCacheStorage(FileIO* file_io) : io(file_io) {} + + void FinishMutation() { + std::lock_guard lock(mutex); + --active_mutations; + // Handles opened during the mutation cannot populate the cache after it ends. + ++finished_mutations; + } + + FileIO* const io; + std::vector registrations; + std::shared_mutex mutex; + size_t active_mutations = 0; + uint64_t finished_mutations = 0; +}; + +class ContentCacheRegistry { + public: + explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {} + + ContentCacheStorage& Bind(ContentCacheRegistration& entry) { + auto* io = entry.storage_io; + ICEBERG_CHECK_OR_DIE(io != nullptr, "Content cache requires a storage FileIO"); + std::lock_guard lock(mutex_); + auto& storage = storage_.try_emplace(io, io).first->second; + storage.registrations.push_back(&entry); + return storage; + } + + void Unbind(ContentCacheStorage& storage, ContentCacheRegistration& entry) { + std::shared_ptr evicted; + std::lock_guard lock(mutex_); + evicted = Erase(entry); + std::erase(storage.registrations, &entry); + if (storage.registrations.empty()) { + storage_.erase(storage.io); + } + } + + bool IsActive(const ContentCacheRegistration& entry, + const std::shared_ptr& files, bool promote) { + std::lock_guard lock(mutex_); + if (entry.files != files) { + return false; + } + if (promote) { + entries_.splice(entries_.begin(), entries_, entry.position); + } + return true; + } + + std::shared_ptr GetOrCreate( + const std::shared_ptr& entry, size_t max_total_bytes) { + std::shared_ptr evicted; + std::lock_guard lock(mutex_); + if (entry->files) { + entries_.splice(entries_.begin(), entries_, entry->position); + } else { + auto files = std::make_shared(static_cast(max_total_bytes)); + entry->position = entries_.emplace(entries_.begin(), entry); + entry->files = std::move(files); + if (std::cmp_greater(entries_.size(), capacity_)) { + evicted = PopLeastRecentlyUsed(); + } + } + return entry->files; + } + + // The caller holds the exclusive storage lock. A table clear also affects + // adapters layered on that table. A storage mutation affects every adapter. + void Invalidate(ContentCacheStorage& storage, + const ContentCacheRegistration* table = nullptr) { + std::vector> evicted; + std::lock_guard lock(mutex_); + evicted.reserve(std::min(storage.registrations.size(), entries_.size())); + for (auto* entry : storage.registrations) { + if (!table || entry->IsLayeredOn(*table)) { + ++entry->invalidations; + if (auto files = Erase(*entry)) { + evicted.push_back(std::move(files)); + } + } + } + } + + Result SetCapacity(int32_t capacity) { + ICEBERG_PRECHECK(capacity > 0, "Global manifest cache limit must be positive, got {}", + capacity); + std::vector> evicted; + std::lock_guard lock(mutex_); + if (std::cmp_greater(entries_.size(), capacity)) { + evicted.reserve(entries_.size() - static_cast(capacity)); + while (std::cmp_greater(entries_.size(), capacity)) { + evicted.push_back(PopLeastRecentlyUsed()); + } + } + return std::exchange(capacity_, capacity); + } + + private: + // Transfer ownership to the caller so destruction happens after unlocking. + std::shared_ptr Erase(ContentCacheRegistration& entry) { + if (entry.files) { + entries_.erase(entry.position); + } + return std::move(entry.files); + } + + std::shared_ptr PopLeastRecentlyUsed() { + auto entry = entries_.back().lock(); + entries_.pop_back(); + return entry ? std::move(entry->files) : nullptr; + } + + std::mutex mutex_; + int32_t capacity_; + ContentCacheRegistration::Entries entries_; + std::unordered_map storage_; +}; + +namespace { + +// Match Iceberg Java's default for iceberg.io.manifest.cache.fileio-max. +constexpr int32_t kDefaultMaxTableCaches = 8; + +std::shared_ptr GlobalContentCacheRegistry() { + // Handles keep the registry alive even when destroyed during static teardown. + static auto registry = std::make_shared(kDefaultMaxTableCaches); + return registry; +} + +class SizedInputStream : public SeekableInputStream { + public: + explicit SizedInputStream(MetadataContent content) + : size_(static_cast(content->size())), content_(std::move(content)) {} + SizedInputStream(std::unique_ptr input, int64_t size) + : size_(size), input_(std::move(input)) {} + + Result Position() const override { + return input_ ? input_->Position() : Result(position_); + } + + Status Seek(int64_t position) override { + ICEBERG_PRECHECK(!closed_, "Input stream is closed"); + ICEBERG_PRECHECK(position >= 0, "Position must not be negative: {}", position); + ICEBERG_PRECHECK(position <= size_, "Position {} exceeds file size {}", position, + size_); + if (input_) { + return input_->Seek(position); + } + position_ = position; + return {}; + } + + Result Read(std::span out) override { + ICEBERG_PRECHECK(!closed_, "Input stream is closed"); + if (input_) { + ICEBERG_ASSIGN_OR_RAISE(auto current, input_->Position()); + ICEBERG_PRECHECK(current >= 0 && current <= size_, "Invalid stream position {}", + current); + const auto remaining = size_ - current; + if (std::cmp_greater(out.size(), remaining)) { + out = out.first(static_cast(remaining)); + } + return input_->Read(out); + } + auto position = static_cast(position_); + auto bytes_to_read = std::min(out.size(), content_->size() - position); + if (bytes_to_read > 0) { + std::memcpy(out.data(), content_->data() + position, bytes_to_read); + position_ += static_cast(bytes_to_read); + } + return static_cast(bytes_to_read); + } + + Status ReadFully(int64_t position, std::span out) override { + ICEBERG_PRECHECK(!closed_, "Input stream is closed"); + ICEBERG_PRECHECK(position >= 0, "Position must not be negative: {}", position); + ICEBERG_PRECHECK(position <= size_, "Position {} exceeds file size {}", position, + size_); + ICEBERG_PRECHECK(std::cmp_less_equal(out.size(), size_ - position), + "Read out of bounds: offset {} + length {} exceeds file size {}", + position, out.size(), size_); + if (input_) { + return input_->ReadFully(position, out); + } + if (!out.empty()) { + std::memcpy(out.data(), content_->data() + position, out.size()); + } + return {}; + } + + Status Close() override { + closed_ = true; + return input_ ? input_->Close() : Status{}; + } + + private: + int64_t size_; + std::unique_ptr input_; + MetadataContent content_; + int64_t position_ = 0; + bool closed_ = false; +}; + +class CachedInputFile : public InputFile { + public: + CachedInputFile(std::unique_ptr input, std::shared_ptr cache, + int64_t size, uint64_t generation, + std::optional verify_location) + : input_(std::move(input)), + cache_(std::move(cache)), + location_(input_->location()), + size_(size), + generation_(generation), + verify_location_(std::move(verify_location)) {} + CachedInputFile(std::string location, MetadataContent content) + : location_(std::move(location)), + size_(static_cast(content->size())), + content_(std::move(content)) {} + std::string_view location() const override { return location_; } + Result Size() const override { return size_; } + Result> Open() override { + auto content = TryReadContent(); + if (content && *content) { + return std::make_unique(std::move(*content)); + } + if (!content && content.error().kind != ErrorKind::kIOError) { + return unexpected(std::move(content).error()); + } + + auto stream = OpenStorageStream(); + if (!stream && !content) { + auto error = std::move(content).error(); + error.message += "; fallback open failed: " + stream.error().message; + return unexpected(std::move(error)); + } + return stream; + } + + private: + Result> OpenStorageStream() { + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_->Open()); + if (auto status = ValidateStreamSize(*stream); !status) { + ICEBERG_RETURN_UNEXPECTED( + FinishWithCloseStatus(std::move(status), stream->Close())); + } + return std::make_unique(std::move(stream), size_); + } + + // A storage handle can resolve its path again at Open(). After a mutation, check + // the opened stream itself before applying the size captured by this handle. + Status ValidateStreamSize(SeekableInputStream& stream) const { + bool writing; + const auto generation = cache_->Generation(&writing); + if (!writing && generation == generation_) { + return {}; + } + // Some backends limit the stream itself to the hint, even for a longer file. + if (verify_location_ && !cache_->MatchesStorageSize(*verify_location_, size_)) { + return Invalid("Cannot verify size {} for invalidated input file {}", size_, + location_); + } + std::array byte; + if (size_ > 0) { + ICEBERG_RETURN_UNEXPECTED(stream.ReadFully(size_ - 1, byte)); + } + ICEBERG_RETURN_UNEXPECTED(stream.Seek(size_)); + ICEBERG_ASSIGN_OR_RAISE(auto count, stream.Read(byte)); + if (count != 0 || cache_->Generation() != generation) { + return Invalid("File changed since opening input file {}", location_); + } + return stream.Seek(0); + } + + // A null value means this handle should stream from storage. + Result TryReadContent() { + if (!cache_) { + return content_; + } + bool can_load; + if (auto cached = cache_->FindForHandle(location_, generation_, size_, &can_load)) { + return cached; + } + if (can_load && verify_location_) { + // A hinted Arrow stream can report EOF at the hint. Confirm the full length + // independently once, only if this handle actually needs to populate the cache. + std::call_once(verify_once_, [&] { + complete_ = cache_->MatchesStorageSize(*verify_location_, size_); + }); + can_load = complete_; + } + if (!can_load) { + return nullptr; + } + std::vector bytes(static_cast(size_)); + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_->Open()); + auto status = stream->ReadFully(/*position=*/0, bytes); + if (status) { + status = ValidateStreamSize(*stream); + } + ICEBERG_RETURN_UNEXPECTED(FinishWithCloseStatus(std::move(status), stream->Close())); + auto content = std::make_shared>(std::move(bytes)); + return cache_->Insert(location_, std::move(content), generation_); + } + + std::unique_ptr input_; + std::shared_ptr cache_; + std::string location_; + int64_t size_; + uint64_t generation_ = 0; + std::optional verify_location_; + std::once_flag verify_once_; + bool complete_ = false; + MetadataContent content_; +}; + +} // namespace + +class ContentCache::ManifestFileIO final : public FileIO { + public: + explicit ManifestFileIO(std::shared_ptr cache) + : cache_(std::move(cache)) {} + static const ContentCacheRegistration* GetRegistration(FileIO* io) { + const auto* adapter = dynamic_cast(io); + return adapter ? adapter->cache_->registration_.get() : nullptr; + } + Result> NewInputFile(std::string location) override { + return cache_->NewInputFile(std::move(location)); + } + Result> NewInputFile(std::string location, + size_t length) override { + return cache_->NewInputFile(std::move(location), length); + } + Result ReadFile(const std::string& location, + std::optional length) override { + // A requested byte count can cover only a prefix of an immutable file. + if (length) { + return cache_->io_->ReadFile(location, length); + } + uint64_t generation; + if (auto cached = cache_->Find(location, &generation)) { + return std::string(reinterpret_cast(cached->data()), cached->size()); + } + auto input = cache_->NewInputFileOnMiss(location, std::nullopt, generation); + if (input) { + ICEBERG_ASSIGN_OR_RAISE(auto size, (*input)->Size()); + return internal::ReadFile(**input, location, size); + } + if (input.error().kind != ErrorKind::kNotImplemented) { + return unexpected(std::move(input).error()); + } + + // Some backends implement only the whole-file operations. + ICEBERG_ASSIGN_OR_RAISE(auto content, cache_->io_->ReadFile(location, std::nullopt)); + if (cache_->CanCache(content.size())) { + auto bytes = std::as_bytes(std::span(content)); + cache_->Insert( + location, + std::make_shared>(bytes.begin(), bytes.end()), + generation); + } + return content; + } + Result> NewOutputFile(std::string location) override { + // Record each mutation once, even when the read adapters are nested. + ICEBERG_ASSIGN_OR_RAISE(auto output, + cache_->storage_.io->NewOutputFile(std::move(location))); + return std::make_unique(std::move(output), cache_); + } + Status WriteFile(const std::string& location, std::string_view content) override { + MutationGuard guard(cache_); + return cache_->storage_.io->WriteFile(location, content); + } + Status DeleteFile(const std::string& location) override { + MutationGuard guard(cache_); + return cache_->storage_.io->DeleteFile(location); + } + Status DeleteFiles(const std::vector& locations) override { + if (locations.empty()) { + return cache_->storage_.io->DeleteFiles(locations); + } + MutationGuard guard(cache_); + return cache_->storage_.io->DeleteFiles(locations); + } + const std::unordered_map& properties() const override { + return cache_->io_->properties(); + } + + private: + // A create may reuse a path removed outside this adapter, including a cached alias. + class MutationGuard { + public: + explicit MutationGuard(std::shared_ptr cache) + : cache_(std::move(cache)) { + std::lock_guard lock(cache_->storage_.mutex); + cache_->registry_->Invalidate(cache_->storage_); + ++cache_->storage_.active_mutations; + } + MutationGuard(const MutationGuard&) = delete; + MutationGuard& operator=(const MutationGuard&) = delete; + ~MutationGuard() { Finish(); } + + void Finish() { + if (auto cache = std::move(cache_)) { + cache->storage_.FinishMutation(); + } + } + + private: + std::shared_ptr cache_; + }; + + class WritingStream : public PositionOutputStream { + public: + explicit WritingStream(std::shared_ptr cache) + : mutation_(std::move(cache)) {} + + Status Open(OutputFile& output, bool overwrite) { + ICEBERG_ASSIGN_OR_RAISE(stream_, + overwrite ? output.CreateOrOverwrite() : output.Create()); + return {}; + } + + Result Position() const override { return stream_->Position(); } + Result StoredLength() const override { return stream_->StoredLength(); } + Status Write(std::span data) override { + return stream_->Write(data); + } + Status Flush() override { return stream_->Flush(); } + Status Close() override { + auto status = stream_->Close(); + if (status) { + mutation_.Finish(); + } + return status; + } + + private: + // Destroy the storage stream before allowing cache fills again. + MutationGuard mutation_; + std::unique_ptr stream_; + }; + + class CachedOutputFile : public OutputFile { + public: + CachedOutputFile(std::unique_ptr output, + std::shared_ptr cache) + : output_(std::move(output)), cache_(std::move(cache)) {} + std::string_view location() const override { return output_->location(); } + Result> Create() override { + return Open(false); + } + Result> CreateOrOverwrite() override { + return Open(true); + } + + private: + Result> Open(bool overwrite) { + auto stream = std::make_unique(cache_); + ICEBERG_RETURN_UNEXPECTED(stream->Open(*output_, overwrite)); + return stream; + } + std::unique_ptr output_; + std::shared_ptr cache_; + }; + + std::shared_ptr cache_; +}; + +Result> ContentCacheOptions::FromProperties( + const std::unordered_map& properties) { + const auto& enabled = ContentCacheProperties::kEnabled; + if (!PropertyUtil::PropertyAsBoolean(properties, enabled.key(), enabled.value())) { + return std::nullopt; + } + const auto read_limit = [&properties](const auto& entry) -> Result { + ICEBERG_ASSIGN_OR_RAISE(auto limit, PropertyUtil::PropertyAsInt64( + properties, entry.key(), entry.value())); + ICEBERG_PRECHECK(limit > 0 && std::in_range(limit), + "Property '{}' must be positive and fit in size_t: {}", entry.key(), + limit); + return static_cast(limit); + }; + ContentCacheOptions options; + ICEBERG_ASSIGN_OR_RAISE(options.max_total_bytes, + read_limit(ContentCacheProperties::kMaxTotalBytes)); + ICEBERG_ASSIGN_OR_RAISE(options.max_content_length, + read_limit(ContentCacheProperties::kMaxContentLength)); + return options; +} + +ContentCache::ContentCache(std::shared_ptr io, ContentCacheOptions options) + : io_(std::move(io)), + options_(options), + registry_(GlobalContentCacheRegistry()), + registration_(std::make_shared( + io_.get(), ManifestFileIO::GetRegistration(io_.get()))), + storage_(registry_->Bind(*registration_)) {} + +ContentCache::~ContentCache() { registry_->Unbind(storage_, *registration_); } + +Result ContentCache::SetGlobalCapacity(int32_t max_caches) { + return GlobalContentCacheRegistry()->SetCapacity(max_caches); +} + +std::shared_ptr ContentCache::Wrap() { + return std::make_shared(shared_from_this()); +} + +uint64_t ContentCache::Generation(bool* writing) const { + std::shared_lock lock(storage_.mutex); + if (writing) { + *writing = storage_.active_mutations != 0; + } + return GenerationLocked(); +} + +uint64_t ContentCache::GenerationLocked() const { + return registration_->invalidations + storage_.finished_mutations; +} + +bool ContentCache::CanCache(uint64_t size) const { + return size > 0 && size <= options_.max_content_length && + size <= options_.max_total_bytes; +} + +MetadataContent ContentCache::Find(std::string_view location, uint64_t* generation) { + std::shared_lock storage_lock(storage_.mutex); + std::lock_guard lock(mutex_); + if (generation) { + *generation = GenerationLocked(); + } + return FindLocked(location, std::nullopt); +} + +MetadataContent ContentCache::FindForHandle(std::string_view location, + uint64_t generation, + std::optional size, bool* can_load) { + std::shared_lock storage_lock(storage_.mutex); + std::lock_guard lock(mutex_); + const bool current = generation == GenerationLocked(); + if (can_load) { + *can_load = current && storage_.active_mutations == 0 && (!size || CanCache(*size)); + } + if (!current) { + return nullptr; + } + return FindLocked(location, size); +} + +MetadataContent ContentCache::FindLocked(std::string_view location, + std::optional size) { + auto files = registration_->last_files.lock(); + if (!files) { + return nullptr; + } + auto fits = [size](const MetadataContent& value) { + return !size || std::cmp_equal(value->size(), *size); + }; + const auto* file = files->FindAndPromoteIf(location, fits); + if (!file || !fits(*file)) { + return nullptr; + } + return registry_->IsActive(*registration_, files, /*promote=*/true) ? *file : nullptr; +} + +MetadataContent ContentCache::Insert(std::string_view location, MetadataContent content, + uint64_t generation) { + // Empty/corrupt metadata must not accumulate unbounded zero-weight entries. + if (!CanCache(content->size())) { + return content; + } + std::shared_lock storage_lock(storage_.mutex); + std::lock_guard lock(mutex_); + if (generation != GenerationLocked() || storage_.active_mutations != 0) { + return content; + } + if (auto retained = registration_->last_files.lock()) { + auto fits = [&](const MetadataContent& value) { + return value->size() == content->size(); + }; + if (auto* winner = retained->FindAndPromoteIf(location, fits)) { + const bool same_size = fits(*winner); + if (registry_->IsActive(*registration_, retained, /*promote=*/same_size)) { + return same_size ? *winner : content; + } + } + } + auto files = registry_->GetOrCreate(registration_, options_.max_total_bytes); + registration_->last_files = files; + ICEBERG_THROW_NOT_OK(files->Replace(std::string(location), content, + static_cast(content->size()))); + return content; +} + +void ContentCache::Clear() { + std::lock_guard lock(storage_.mutex); + registry_->Invalidate(storage_, registration_.get()); +} + +Result> ContentCache::NewInputFile( + std::string location, std::optional length) { + ICEBERG_PRECHECK(!length || std::in_range(*length), + "File length {} exceeds int64_t max", *length); + // A hit needs neither storage resolution nor working remote credentials. + uint64_t generation; + if (auto content = Find(location, &generation)) { + return std::make_unique(std::move(location), std::move(content)); + } + return NewInputFileOnMiss(std::move(location), length, generation); +} + +Result> ContentCache::NewInputFileOnMiss( + std::string location, std::optional length, uint64_t generation) { + std::unique_ptr input; + if (length) { + ICEBERG_ASSIGN_OR_RAISE(input, io_->NewInputFile(location, *length)); + } else { + ICEBERG_ASSIGN_OR_RAISE(input, io_->NewInputFile(location)); + } + if (input->location() != location) { + if (auto content = FindForHandle(input->location(), generation)) { + return std::make_unique(std::string(input->location()), + std::move(content)); + } + } + ICEBERG_ASSIGN_OR_RAISE(auto size, input->Size()); + if (size < 0) { + return Invalid("File size {} for {} does not fit in size_t", size, input->location()); + } + std::optional verify_location; + if (length && std::cmp_equal(size, *length)) { + verify_location = std::move(location); + } + return std::make_unique(std::move(input), shared_from_this(), size, + generation, std::move(verify_location)); +} + +bool ContentCache::MatchesStorageSize(const std::string& location, int64_t size) const { + auto whole = storage_.io->NewInputFile(location); + return whole && (*whole)->Size().value_or(-1) == size; +} + +} // namespace iceberg::internal diff --git a/src/iceberg/content_cache_internal.h b/src/iceberg/content_cache_internal.h new file mode 100644 index 000000000..749fb3df2 --- /dev/null +++ b/src/iceberg/content_cache_internal.h @@ -0,0 +1,113 @@ +/* + * 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "iceberg/file_io.h" +#include "iceberg/util/config.h" + +namespace iceberg::internal { + +class ContentCacheProperties : public ConfigBase { + public: + inline static const Entry kEnabled{"io.manifest.cache-enabled", false}; + inline static const Entry kMaxTotalBytes{"io.manifest.cache.max-total-bytes", + 100 * 1024 * 1024}; + inline static const Entry kMaxContentLength{ + "io.manifest.cache.max-content-length", 8 * 1024 * 1024}; +}; + +// Retain only validated cache settings, independent of the storage credentials. +struct ICEBERG_EXPORT ContentCacheOptions { + size_t max_total_bytes = + static_cast(ContentCacheProperties::kMaxTotalBytes.value()); + size_t max_content_length = + static_cast(ContentCacheProperties::kMaxContentLength.value()); + friend bool operator==(const ContentCacheOptions&, + const ContentCacheOptions&) = default; + // Returns std::nullopt when manifest caching is disabled. + static Result> FromProperties( + const std::unordered_map& properties); +}; + +using MetadataContent = std::shared_ptr>; + +struct ContentCacheRegistration; +struct ContentCacheStorage; +class ContentCacheRegistry; + +// The per-table handle owns its cached files. The process-wide registry tracks +// active caches through weak references and can evict their contents at capacity. +class ICEBERG_EXPORT ContentCache : public std::enable_shared_from_this { + public: + // A cache and all its adapters use this FileIO for their entire lifetime. + // The caller must keep its storage namespace stable: every cached location must + // continue to identify the same immutable file. Bind a fresh cache when replacing + // the FileIO or changing where it resolves those locations. + ContentCache(std::shared_ptr io, ContentCacheOptions options); + ~ContentCache(); + // Return the previous process-wide capacity. The new capacity must be positive. + static Result SetGlobalCapacity(int32_t max_caches); + const ContentCacheOptions& options() const { return options_; } + std::shared_ptr Wrap(); + Result> NewInputFile( + std::string location, std::optional length = std::nullopt); + // A load that overlaps invalidation may serve its own reader but cannot repopulate + // the cache. Capture the generation under the same lock as the lookup. + MetadataContent Find(std::string_view location, uint64_t* generation = nullptr); + MetadataContent FindForHandle(std::string_view location, uint64_t generation, + std::optional size = std::nullopt, + bool* can_load = nullptr); + uint64_t Generation(bool* writing = nullptr) const; + bool MatchesStorageSize(const std::string& location, int64_t size) const; + // A competing load of the same size in this generation shares the winner's bytes. + MetadataContent Insert(std::string_view location, MetadataContent content, + uint64_t generation); + void Clear(); + + private: + class ManifestFileIO; + + uint64_t GenerationLocked() const; + bool CanCache(uint64_t size) const; + Result> NewInputFileOnMiss(std::string location, + std::optional length, + uint64_t generation); + MetadataContent FindLocked(std::string_view location, std::optional size); + const std::shared_ptr io_; + const ContentCacheOptions options_; + const std::shared_ptr registry_; + const std::shared_ptr registration_; + ContentCacheStorage& storage_; + // Cache operations take the shared storage lock before the table mutex. + // A clear takes the exclusive storage lock so outer adapters see local clears. + std::mutex mutex_; +}; + +} // namespace iceberg::internal diff --git a/src/iceberg/file_io.cc b/src/iceberg/file_io.cc index 543c13b03..429a714cc 100644 --- a/src/iceberg/file_io.cc +++ b/src/iceberg/file_io.cc @@ -22,26 +22,12 @@ #include #include +#include "iceberg/file_io_internal.h" +#include "iceberg/util/error_util_internal.h" #include "iceberg/util/macros.h" namespace iceberg { -namespace { - -Status FinishWithCloseStatus(Status operation_status, Status close_status) { - if (!operation_status.has_value()) { - auto error = operation_status.error(); - if (!close_status.has_value()) { - error.message += "; additionally failed to close stream: "; - error.message += close_status.error().message; - } - return ::iceberg::unexpected(std::move(error)); - } - return close_status; -} - -} // namespace - Result> FileIO::NewInputFile(std::string file_location) { return NotImplemented("NewInputFile not implemented for {}", file_location); } @@ -69,20 +55,27 @@ Result FileIO::ReadFile(const std::string& file_location, ICEBERG_ASSIGN_OR_RAISE(input_file, NewInputFile(file_location)); ICEBERG_ASSIGN_OR_RAISE(read_size, input_file->Size()); } - if (read_size < 0) { - return Invalid("Invalid negative file size {} for {}", read_size, file_location); + return internal::ReadFile(*input_file, file_location, read_size); +} + +Result internal::ReadFile(InputFile& input_file, + std::string_view file_location, + int64_t read_size) { + if (!std::in_range(read_size)) { + return Invalid("File size {} for {} does not fit in size_t", read_size, + file_location); } auto size = static_cast(read_size); std::string content(size, '\0'); - ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file->Open()); + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open()); Status read_status = {}; if (size > 0) { auto bytes = std::as_writable_bytes(std::span(content.data(), content.size())); read_status = stream->ReadFully(/*position=*/0, bytes); } ICEBERG_RETURN_UNEXPECTED( - FinishWithCloseStatus(std::move(read_status), stream->Close())); + internal::FinishWithCloseStatus(std::move(read_status), stream->Close())); return content; } @@ -97,7 +90,7 @@ Status FileIO::WriteFile(const std::string& file_location, std::string_view cont if (status.has_value()) { status = stream->Flush(); } - return FinishWithCloseStatus(std::move(status), stream->Close()); + return internal::FinishWithCloseStatus(std::move(status), stream->Close()); } Status FileIO::DeleteFiles(const std::vector& file_locations) { diff --git a/src/iceberg/file_io_internal.h b/src/iceberg/file_io_internal.h new file mode 100644 index 000000000..3fee4b3ec --- /dev/null +++ b/src/iceberg/file_io_internal.h @@ -0,0 +1,28 @@ +/* + * 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 + +#include "iceberg/file_io.h" + +namespace iceberg::internal { + +Result ReadFile(InputFile& file, std::string_view location, int64_t size); + +} // namespace iceberg::internal diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt index c5d9883a2..91bca0441 100644 --- a/src/iceberg/test/CMakeLists.txt +++ b/src/iceberg/test/CMakeLists.txt @@ -183,6 +183,7 @@ add_iceberg_test(util_test lazy_test.cc location_util_test.cc math_util_internal_test.cc + metadata_cache_test.cc mumbling_bitmap_test.cc executor_util_test.cc roaring_position_bitmap_test.cc diff --git a/src/iceberg/test/arrow_io_test.cc b/src/iceberg/test/arrow_io_test.cc index 7bc9ebba5..8312d63d4 100644 --- a/src/iceberg/test/arrow_io_test.cc +++ b/src/iceberg/test/arrow_io_test.cc @@ -19,7 +19,9 @@ #include #include +#include #include +#include #include #include #include @@ -31,6 +33,7 @@ #include "iceberg/arrow/arrow_io_internal.h" #include "iceberg/arrow/arrow_register.h" +#include "iceberg/content_cache_internal.h" #include "iceberg/file_io_registry.h" #include "iceberg/resolving_file_io.h" #include "iceberg/test/matchers.h" @@ -146,7 +149,7 @@ class WriteFailureOutputFile : public OutputFile { std::shared_ptr state_; }; -class WriteFailureFileIO : public FileIO { +class WriteFailureFileIO : public test::StdFileIO { public: explicit WriteFailureFileIO(std::shared_ptr state) : state_(std::move(state)) {} @@ -368,6 +371,148 @@ TEST_F(LocalFileIOTest, DeleteFile) { EXPECT_THAT(del_res, HasErrorMessage("Cannot delete file")); } +TEST(ArrowFileIOTest, AliasDeleteInvalidatesEveryCachedSpelling) { + std::shared_ptr storage = arrow::ArrowFileSystemFileIO::MakeMockFileIO(); + const std::string canonical = "s3://manifest.avro"; + const std::string alias = "s3a://manifest.avro"; + const std::string unrelated = "s3://other.avro"; + for (bool warm_alias : {false, true}) { + SCOPED_TRACE(warm_alias); + auto cache = std::make_shared( + storage, internal::ContentCacheOptions{}); + auto adapter = cache->Wrap(); + ASSERT_THAT(storage->WriteFile(canonical, "old"), IsOk()); + ASSERT_THAT(storage->WriteFile(unrelated, "keep"), IsOk()); + ASSERT_THAT(adapter->ReadFile(unrelated, std::nullopt), + HasValue(::testing::Eq("keep"))); + ASSERT_THAT(adapter->ReadFile(canonical, std::nullopt), + HasValue(::testing::Eq("old"))); + if (warm_alias) { + ASSERT_THAT(adapter->ReadFile(alias, std::nullopt), HasValue(::testing::Eq("old"))); + } + ASSERT_THAT(adapter->DeleteFiles({alias, unrelated}), IsOk()); + EXPECT_FALSE(cache->Find(unrelated)); + ASSERT_THAT(storage->WriteFile(canonical, "new"), IsOk()); + EXPECT_THAT(adapter->ReadFile(canonical, std::nullopt), + HasValue(::testing::Eq("new"))); + EXPECT_THAT(adapter->ReadFile(alias, std::nullopt), HasValue(::testing::Eq("new"))); + } +} + +TEST_F(LocalFileIOTest, HintedStreamEndsAtReportedSizeAcrossCacheLimits) { + ASSERT_THAT(file_io_->WriteFile(temp_filepath_, "12345678"), IsOk()); + for (size_t limit : {8, 2}) { + SCOPED_TRACE(limit); + auto cache = std::make_shared( + file_io_, internal::ContentCacheOptions{.max_content_length = limit}); + ICEBERG_UNWRAP_OR_FAIL(auto file, cache->Wrap()->NewInputFile(temp_filepath_, 4)); + ASSERT_THAT(file->Size(), HasValue(::testing::Eq(4))); + ICEBERG_UNWRAP_OR_FAIL(auto stream, file->Open()); + std::string bytes(8, '_'); + auto buffer = std::as_writable_bytes(std::span(bytes)); + EXPECT_THAT(stream->Read(buffer), HasValue(::testing::Eq(4))); + EXPECT_EQ(bytes, "1234____"); + EXPECT_THAT(stream->Read(buffer), HasValue(::testing::Eq(0))); + EXPECT_THAT(stream->Close(), IsOk()); + EXPECT_FALSE(cache->Find(temp_filepath_)); + } +} + +TEST_F(LocalFileIOTest, ColdHandleRejectsLongerReplacementAfterOverwrite) { + for (size_t limit : {2, 8}) { + for (bool hinted : {false, true}) { + SCOPED_TRACE(::testing::Message() << "limit=" << limit << ", hinted=" << hinted); + auto cache = std::make_shared( + file_io_, internal::ContentCacheOptions{.max_content_length = limit}); + auto adapter = cache->Wrap(); + ASSERT_THAT(adapter->WriteFile(temp_filepath_, "old"), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto file, hinted ? adapter->NewInputFile(temp_filepath_, 3) + : adapter->NewInputFile(temp_filepath_)); + ASSERT_THAT(adapter->WriteFile(temp_filepath_, "longer"), IsOk()); + ASSERT_THAT(adapter->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("longer"))); + EXPECT_THAT(file->Open(), IsError(ErrorKind::kInvalid)); + } + } +} + +TEST_F(LocalFileIOTest, AliasDeleteClearsCachedLocalPaths) { + auto cache = + std::make_shared(file_io_, internal::ContentCacheOptions{}); + auto adapter = cache->Wrap(); + const std::filesystem::path path(temp_filepath_); + const auto alias = (path.parent_path() / "." / path.filename()).string(); + ASSERT_THAT(file_io_->WriteFile(temp_filepath_, "old"), IsOk()); + ASSERT_THAT(adapter->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("old"))); + ASSERT_THAT(adapter->DeleteFile(alias), IsOk()); + ASSERT_THAT(file_io_->WriteFile(temp_filepath_, "new"), IsOk()); + EXPECT_THAT(adapter->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("new"))); +} + +TEST_F(LocalFileIOTest, OverwritingThroughAnAliasInvalidatesTheCachedFile) { + auto cache = + std::make_shared(file_io_, internal::ContentCacheOptions{}); + auto adapter = cache->Wrap(); + const auto path = std::filesystem::path(temp_filepath_); + const auto alias = (path.parent_path() / "." / path.filename()).string(); + ASSERT_THAT(adapter->WriteFile(temp_filepath_, "old"), IsOk()); + ASSERT_THAT(adapter->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("old"))); + ASSERT_THAT(adapter->WriteFile(alias, "new"), IsOk()); + EXPECT_THAT(adapter->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("new"))); +} + +TEST_F(LocalFileIOTest, RecreatingAFileAfterAnotherCacheDeletesItReadsNewBytes) { + auto writer = + std::make_shared(file_io_, internal::ContentCacheOptions{}) + ->Wrap(); + auto cleaner = + std::make_shared(file_io_, internal::ContentCacheOptions{}) + ->Wrap(); + const std::filesystem::path path(temp_filepath_); + const auto alias = (path.parent_path() / "." / path.filename()).string(); + ASSERT_THAT(writer->WriteFile(temp_filepath_, "old"), IsOk()); + ASSERT_THAT(writer->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("old"))); + ASSERT_THAT(cleaner->DeleteFile(alias), IsOk()); + ASSERT_THAT(writer->WriteFile(alias, "new"), IsOk()); + EXPECT_THAT(writer->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("new"))); + EXPECT_THAT(writer->ReadFile(alias, std::nullopt), HasValue(::testing::Eq("new"))); +} + +TEST_F(LocalFileIOTest, RecreatingAnExternallyDeletedAliasInvalidatesSibling) { + auto reader = + std::make_shared(file_io_, internal::ContentCacheOptions{}) + ->Wrap(); + auto writer = + std::make_shared(file_io_, internal::ContentCacheOptions{}) + ->Wrap(); + const std::filesystem::path path(temp_filepath_); + const auto alias = (path.parent_path() / "." / path.filename()).string(); + for (bool whole_file : {false, true}) { + SCOPED_TRACE(whole_file); + ASSERT_THAT(file_io_->WriteFile(temp_filepath_, "old"), IsOk()); + ASSERT_THAT(reader->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("old"))); + ASSERT_THAT(file_io_->DeleteFile(temp_filepath_), IsOk()); + if (whole_file) { + ASSERT_THAT(writer->WriteFile(alias, "new"), IsOk()); + } else { + ICEBERG_UNWRAP_OR_FAIL(auto file, writer->NewOutputFile(alias)); + ICEBERG_UNWRAP_OR_FAIL(auto out, file->Create()); + ASSERT_THAT(out->Write(std::as_bytes(std::span("new", 3))), IsOk()); + ASSERT_THAT(out->Close(), IsOk()); + } + EXPECT_THAT(reader->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("new"))); + ASSERT_THAT(writer->DeleteFile(alias), IsOk()); + } +} + TEST_F(LocalFileIOTest, DeleteFiles) { auto first_path = CreateNewTempFilePath(); auto second_path = CreateNewTempFilePath(); @@ -568,4 +713,33 @@ TEST(FileIOTest, WriteFileReturnsWriteErrorWithCloseContext) { EXPECT_THAT(result, HasErrorMessage("close failed")); } +TEST_F(LocalFileIOTest, CacheFillsResumeAfterFailedWriterIsDestroyed) { + ASSERT_THAT(file_io_->WriteFile(temp_filepath_, "manifest"), IsOk()); + for (bool fail_close : {false, true}) { + SCOPED_TRACE(fail_close ? "close failure" : "write failure"); + auto state = std::make_shared(); + auto storage = std::make_shared(state); + auto cache = std::make_shared( + storage, internal::ContentCacheOptions{}); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto output, adapter->NewOutputFile("write-failure")); + ICEBERG_UNWRAP_OR_FAIL(auto writer, output->Create()); + if (fail_close) { + ASSERT_THAT(writer->Close(), IsError(ErrorKind::kIOError)); + EXPECT_TRUE(state->closed); + } else { + ASSERT_THAT(writer->Write(std::as_bytes(std::span("data", 4))), + IsError(ErrorKind::kIOError)); + } + ASSERT_THAT(adapter->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("manifest"))); + ASSERT_FALSE(cache->Find(temp_filepath_)); + + writer.reset(); + ASSERT_THAT(adapter->ReadFile(temp_filepath_, std::nullopt), + HasValue(::testing::Eq("manifest"))); + EXPECT_TRUE(cache->Find(temp_filepath_)); + } +} + } // namespace iceberg diff --git a/src/iceberg/test/cache_test.cc b/src/iceberg/test/cache_test.cc index fbc29ab9c..ebc8e61e2 100644 --- a/src/iceberg/test/cache_test.cc +++ b/src/iceberg/test/cache_test.cc @@ -18,13 +18,19 @@ */ #include +#include #include +#include #include #include +#include +#include #include +#include "iceberg/exception.h" #include "iceberg/test/executor.h" +#include "iceberg/test/matchers.h" #include "iceberg/util/cache_internal.h" #include "iceberg/util/task_group.h" @@ -33,16 +39,193 @@ namespace iceberg::internal { TEST(LruCacheTest, Eviction) { LruCache cache(2); - EXPECT_TRUE(cache.Replace(1, "one").first); - EXPECT_TRUE(cache.Replace(2, "two").first); + EXPECT_TRUE(cache.Replace(1, "one").value().first); + EXPECT_TRUE(cache.Replace(2, "two").value().first); ASSERT_NE(cache.Find(1), nullptr); - EXPECT_TRUE(cache.Replace(3, "three").first); + EXPECT_TRUE(cache.Replace(3, "three").value().first); EXPECT_EQ(cache.Find(2), nullptr); ASSERT_NE(cache.Find(1), nullptr); EXPECT_EQ(*cache.Find(1), "one"); ASSERT_NE(cache.Find(3), nullptr); EXPECT_EQ(*cache.Find(3), "three"); + EXPECT_EQ(cache.size(), 2); + EXPECT_EQ(cache.total_weight(), 2); +} + +TEST(LruCacheTest, LargeLimitDoesNotReserveStorage) { + constexpr auto kLargeLimit = std::numeric_limits::max(); + LruCache cache(kLargeLimit); + ASSERT_NE(cache.Replace(1, "one").value().second, nullptr); + + ASSERT_THAT(cache.Resize(1), IsOk()); + ASSERT_THAT(cache.Resize(kLargeLimit), IsOk()); + EXPECT_EQ(cache.max_weight(), kLargeLimit); + EXPECT_EQ(cache.size(), 1); + cache.Clear(); + ASSERT_NE(cache.Replace(2, "two").value().second, nullptr); + EXPECT_EQ(cache.size(), 1); +} + +TEST(LruCacheTest, WeightedEviction) { + LruCache cache(10); + + EXPECT_TRUE(cache.Replace(1, "aaaa", 4).value().first); + EXPECT_TRUE(cache.Replace(2, "bbb", 3).value().first); + ASSERT_NE(cache.Find(1), nullptr); + EXPECT_EQ(cache.total_weight(), 7); + + // 7 + 6 exceeds 10, so the least recently used entry 2 is evicted. + auto [inserted, value] = cache.Replace(3, "cccccc", 6).value(); + static_assert(std::same_as); + static_assert(std::same_as); + EXPECT_TRUE(inserted); + ASSERT_NE(value, nullptr); + EXPECT_EQ(*value, "cccccc"); + EXPECT_EQ(cache.Find(2), nullptr); + ASSERT_NE(cache.Find(1), nullptr); + EXPECT_EQ(*cache.Find(1), "aaaa"); + EXPECT_EQ(cache.size(), 2); + EXPECT_EQ(cache.total_weight(), 10); +} + +TEST(LruCacheTest, WeightedEvictionRemovesMultipleEntries) { + LruCache cache(10); + ASSERT_THAT(cache.Replace(1, "aaa", 3), IsOk()); + ASSERT_THAT(cache.Replace(2, "bbb", 3), IsOk()); + ASSERT_THAT(cache.Replace(3, "ccc", 3), IsOk()); + + // Making room for 7 requires evicting the two least recently used entries. + ASSERT_NE(cache.Replace(4, "ddddddd", 7).value().second, nullptr); + EXPECT_EQ(cache.Find(1), nullptr); + EXPECT_EQ(cache.Find(2), nullptr); + EXPECT_NE(cache.Find(3), nullptr); + EXPECT_NE(cache.Find(4), nullptr); + EXPECT_EQ(cache.size(), 2); + EXPECT_EQ(cache.total_weight(), 10); +} + +TEST(LruCacheTest, OversizedValueIsNotCached) { + LruCache cache(5); + ASSERT_THAT(cache.Replace(1, "aa", 2), IsOk()); + + auto [inserted, value] = cache.Replace(2, "bbbbbb", 6).value(); + EXPECT_FALSE(inserted); + EXPECT_EQ(value, nullptr); + EXPECT_EQ(cache.Find(2), nullptr); + // Rejecting the oversized value must not evict anything. + ASSERT_NE(cache.Find(1), nullptr); + EXPECT_EQ(cache.size(), 1); + EXPECT_EQ(cache.total_weight(), 2); + + // A value exactly at the maximum weight fits. + ASSERT_NE(cache.Replace(3, "ccccc", 5).value().second, nullptr); + EXPECT_EQ(cache.Find(1), nullptr); + EXPECT_EQ(cache.total_weight(), 5); +} + +TEST(LruCacheTest, ReplaceReweighsEntry) { + LruCache cache(10); + ASSERT_THAT(cache.Replace(1, "aaa", 3), IsOk()); + ASSERT_THAT(cache.Replace(2, "bbb", 3), IsOk()); + + // Growing entry 2 from 3 to 7 still fits next to entry 1. + EXPECT_FALSE(cache.Replace(2, "bbbbbbb", 7).value().first); + EXPECT_EQ(cache.size(), 2); + EXPECT_EQ(cache.total_weight(), 10); + + // Growing entry 1 to 8 makes it most recently used and evicts entry 2. + auto [inserted, value] = cache.Replace(1, "aaaaaaaa", 8).value(); + EXPECT_FALSE(inserted); + ASSERT_NE(value, nullptr); + EXPECT_EQ(*value, "aaaaaaaa"); + EXPECT_EQ(cache.Find(2), nullptr); + EXPECT_EQ(cache.size(), 1); + EXPECT_EQ(cache.total_weight(), 8); + + // Shrinking releases weight. + ASSERT_THAT(cache.Replace(1, "a", 1), IsOk()); + EXPECT_EQ(cache.total_weight(), 1); + + // Replacing with an oversized value removes the existing entry. + std::tie(inserted, value) = cache.Replace(1, std::string(11, 'a'), 11).value(); + EXPECT_FALSE(inserted); + EXPECT_EQ(value, nullptr); + EXPECT_EQ(cache.Find(1), nullptr); + EXPECT_EQ(cache.size(), 0); + EXPECT_EQ(cache.total_weight(), 0); +} + +TEST(LruCacheTest, InvalidWeightsLeaveCacheUnchanged) { + using Cache = LruCache; + EXPECT_THROW(Cache(-1), IcebergError); + Cache cache(4); + ASSERT_THAT(cache.Replace(1, "old", 3), IsOk()); + EXPECT_THAT(cache.Resize(-1), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(cache.Replace(1, "new", -1), IsError(ErrorKind::kInvalidArgument)); + EXPECT_EQ(cache.max_weight(), 4); + EXPECT_EQ(cache.total_weight(), 3); + ASSERT_NE(cache.Find(1), nullptr); + EXPECT_EQ(*cache.Find(1), "old"); +} + +TEST(LruCacheTest, MovesTransferEntriesAndWeightTogether) { + LruCache source(5); + ASSERT_THAT(source.Replace(1, "first", 2), IsOk()); + ASSERT_THAT(source.Replace(2, "second", 3), IsOk()); + + auto moved = std::move(source); + // Both move operations leave the source cache empty and reusable. + // NOLINTNEXTLINE(clang-analyzer-cplusplus.Move) + EXPECT_EQ(source.size(), 0); + ASSERT_EQ(source.total_weight(), 0); + ASSERT_THAT(source.Resize(1), IsOk()); + EXPECT_TRUE(source.Replace(3, "reused").value().first); + + // Moving into a populated cache must also discard its previous entries. + source = std::move(moved); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.Move) + EXPECT_EQ(moved.size(), 0); + ASSERT_EQ(moved.total_weight(), 0); + ASSERT_THAT(moved.Resize(1), IsOk()); + EXPECT_TRUE(moved.Replace(4, "reused").value().first); + + EXPECT_EQ(source.Find(3), nullptr); + EXPECT_EQ(source.size(), 2); + EXPECT_EQ(source.total_weight(), 5); + EXPECT_EQ(source.max_weight(), 5); + ASSERT_THAT(source.Resize(3), IsOk()); + EXPECT_EQ(source.Find(1), nullptr); + ASSERT_NE(source.Find(2), nullptr); + EXPECT_EQ(*source.Find(2), "second"); +} + +TEST(LruCacheTest, ClearResetsWeight) { + LruCache cache(10); + ASSERT_THAT(cache.Replace(1, "aaaa", 4), IsOk()); + ASSERT_THAT(cache.Replace(2, "bbbb", 4), IsOk()); + + cache.Clear(); + EXPECT_EQ(cache.size(), 0); + EXPECT_EQ(cache.total_weight(), 0); + + ASSERT_NE(cache.Replace(3, std::string(10, 'c'), 10).value().second, nullptr); + EXPECT_EQ(cache.total_weight(), 10); +} + +TEST(LruCacheTest, ShrinkingLimitEvictsByWeightInLruOrder) { + LruCache cache(10); + ASSERT_THAT(cache.Replace(1, "aaa", 3), IsOk()); + ASSERT_THAT(cache.Replace(2, "bbbb", 4), IsOk()); + ASSERT_THAT(cache.Replace(3, "ccc", 3), IsOk()); + ASSERT_NE(cache.Find(1), nullptr); + + ASSERT_THAT(cache.Resize(3), IsOk()); + EXPECT_EQ(cache.max_weight(), 3); + EXPECT_EQ(cache.total_weight(), 3); + EXPECT_EQ(cache.Find(2), nullptr); + EXPECT_EQ(cache.Find(3), nullptr); + EXPECT_NE(cache.Find(1), nullptr); } TEST(MemoizeLruTest, Caches) { @@ -64,6 +247,14 @@ TEST(MemoizeLruTest, Caches) { EXPECT_EQ(calls, 4); } +TEST(MemoizeLruTest, RejectsLookupWithZeroCapacity) { + auto identity = [](int32_t key) { return key; }; + auto memoized = MemoizeLru(identity, 0); + auto memoized_thread_unsafe = MemoizeLruThreadUnsafe(identity, 0); + EXPECT_THROW(memoized(1), IcebergError); + EXPECT_THROW(memoized_thread_unsafe(1), IcebergError); +} + TEST(MemoizeLruTest, MovesKey) { auto memoized = MemoizeLru([](const std::unique_ptr& key) { return *key; }, 2); EXPECT_EQ(memoized(std::make_unique(1)), 1); diff --git a/src/iceberg/test/metadata_cache_test.cc b/src/iceberg/test/metadata_cache_test.cc new file mode 100644 index 000000000..f0a80db4b --- /dev/null +++ b/src/iceberg/test/metadata_cache_test.cc @@ -0,0 +1,970 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "iceberg/content_cache_internal.h" +#include "iceberg/exception.h" +#include "iceberg/file_io.h" +#include "iceberg/test/matchers.h" +#include "iceberg/test/mock_io.h" +#include "iceberg/util/macros.h" + +namespace iceberg { +namespace { +using internal::ContentCacheOptions; +using internal::ContentCacheProperties; + +std::shared_ptr MakeCache( + std::shared_ptr storage = std::make_shared(), + ContentCacheOptions options = {}) { + return std::make_shared(std::move(storage), options); +} + +void ExpectWriteFile(MockFileIO& storage, const std::string& path, + std::string_view content) { + EXPECT_CALL(storage, WriteFile(path, content)) + .WillOnce([&storage](const auto& location, auto bytes) { + storage.AddFile(location, bytes); + return Status{}; + }); +} + +class ScopedGlobalCacheLimit { + public: + explicit ScopedGlobalCacheLimit(int32_t limit) { + ICEBERG_ASSIGN_OR_THROW(previous_, internal::ContentCache::SetGlobalCapacity(limit)); + } + ~ScopedGlobalCacheLimit() { + EXPECT_THAT(internal::ContentCache::SetGlobalCapacity(previous_), IsOk()); + } + + private: + int32_t previous_; +}; + +struct FailingOpenState { + int open_count = 0; + int size_count = 0; + int64_t size = 8; + Error first_error; + Result> fallback_file = IOError("unexpected fallback open"); +}; + +class FailingOpenInputFile : public InputFile { + public: + explicit FailingOpenInputFile(std::shared_ptr state) + : state_(std::move(state)) {} + + std::string_view location() const override { return "manifest.avro"; } + Result Size() const override { + ++state_->size_count; + return state_->size; + } + + Result> Open() override { + ++state_->open_count; + if (state_->open_count == 1) { + return unexpected(state_->first_error); + } + ICEBERG_RETURN_UNEXPECTED(state_->fallback_file); + return (*state_->fallback_file)->Open(); + } + + private: + std::shared_ptr state_; +}; + +class FailingOpenFileIO : public FileIO { + public: + explicit FailingOpenFileIO(std::shared_ptr state) + : state_(std::move(state)) {} + + Result> NewInputFile( + std::string /*file_location*/) override { + return std::make_unique(state_); + } + + private: + std::shared_ptr state_; +}; + +TEST(MetadataCacheTest, RejectsNullStorage) { + EXPECT_THROW(MakeCache(nullptr), IcebergError); +} + +TEST(MetadataCacheTest, WholeFileOnlyBackendSupportsCachedReadsAndWrites) { + class WholeFileIO : public FileIO { + public: + MOCK_METHOD((Result), ReadFile, + (const std::string&, std::optional), (override)); + MOCK_METHOD(Status, WriteFile, (const std::string&, std::string_view), (override)); + }; + auto storage = std::make_shared<::testing::StrictMock>(); + auto cache = MakeCache(storage); + auto reader = cache->Wrap(); + auto writer = MakeCache(storage)->Wrap(); + EXPECT_CALL(*storage, ReadFile("manifest", ::testing::Eq(std::nullopt))) + .WillOnce(::testing::Return(std::string("old"))); + ASSERT_THAT(reader->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("old"))); + ASSERT_THAT(reader->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("old"))); + EXPECT_CALL(*storage, ReadFile("manifest", std::optional{1})) + .WillOnce(::testing::Return(std::string("o"))); + EXPECT_THAT(reader->ReadFile("manifest", 1), HasValue(::testing::Eq("o"))); + + for (bool fail_write : {true, false}) { + SCOPED_TRACE(fail_write); + EXPECT_CALL(*storage, WriteFile("manifest", "new")) + .WillOnce([&](const auto&, auto) -> Status { + EXPECT_FALSE(cache->Find("manifest")); + EXPECT_THAT(reader->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("n"))); + EXPECT_FALSE(cache->Find("manifest")); + return fail_write ? IOError("write failed") : Status{}; + }); + EXPECT_CALL(*storage, ReadFile("manifest", ::testing::Eq(std::nullopt))) + .WillOnce(::testing::Return(std::string("n"))) + .WillOnce(::testing::Return(std::string("new"))); + auto status = writer->WriteFile("manifest", "new"); + if (fail_write) { + ASSERT_THAT(status, HasErrorMessage("write failed")); + } else { + ASSERT_THAT(status, IsOk()); + } + ASSERT_THAT(reader->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("new"))); + ASSERT_TRUE(cache->Find("manifest")); + } +} + +TEST(MetadataCacheTest, IdenticalLocationsOnDifferentBackendsHaveIndependentContents) { + auto first = std::make_shared(); + auto second = std::make_shared(); + first->AddFile("manifest.avro", "first"); + second->AddFile("manifest.avro", "second"); + + auto cache = MakeCache(first); + ASSERT_THAT(cache->Wrap()->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("first"))); + first->RemoveFile("manifest.avro"); + + auto replacement = MakeCache(second); + EXPECT_THAT(replacement->Wrap()->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("second"))); + EXPECT_THAT(cache->Wrap()->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("first"))); +} + +TEST(MetadataCacheTest, NegativeStorageSizeIsInvalidWithOrWithoutCaching) { + auto state = std::make_shared(); + state->size = -1; + std::shared_ptr storage = std::make_shared(state); + auto cache = MakeCache(storage); + for (const auto& io : {storage, cache->Wrap()}) { + auto result = io->ReadFile("manifest.avro", std::nullopt); + EXPECT_THAT(result, IsError(ErrorKind::kInvalid)); + EXPECT_THAT(result, HasErrorMessage("File size -1 for manifest.avro")); + } + EXPECT_EQ(state->open_count, 0); +} + +TEST(MetadataCacheTest, CachedInputFileDoesNotRetryNonIOErrors) { + auto state = std::make_shared(FailingOpenState{ + .first_error = {.kind = ErrorKind::kNotFound, .message = "missing"}, + }); + auto cache = MakeCache(std::make_shared(state)); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto input_file, adapter->NewInputFile("manifest.avro")); + + EXPECT_THAT(input_file->Open(), IsError(ErrorKind::kNotFound)); + EXPECT_EQ(state->open_count, 1); +} + +TEST(MetadataCacheTest, CachedInputFilePreservesReadAheadAndFallbackErrors) { + auto state = std::make_shared(FailingOpenState{ + .first_error = {.kind = ErrorKind::kIOError, .message = "read-ahead failed"}, + .fallback_file = IOError("open failed"), + }); + auto cache = MakeCache(std::make_shared(state)); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto input_file, adapter->NewInputFile("manifest.avro")); + + auto result = input_file->Open(); + EXPECT_THAT(result, IsError(ErrorKind::kIOError)); + EXPECT_THAT(result, HasErrorMessage("read-ahead failed")); + EXPECT_THAT(result, HasErrorMessage("fallback open failed: open failed")); + EXPECT_EQ(state->open_count, 2); +} + +TEST(MetadataCacheTest, SuccessfulFallbackRespectsHandleSizeAndSkipsCache) { + MockFileIO storage; + storage.AddFile("manifest.avro", "manifest"); + auto state = std::make_shared(FailingOpenState{ + .size = 4, + .first_error = {.kind = ErrorKind::kIOError, .message = "read-ahead failed"}, + .fallback_file = storage.NewInputFile("manifest.avro"), + }); + auto cache = MakeCache(std::make_shared(state)); + ICEBERG_UNWRAP_OR_FAIL(auto file, cache->Wrap()->NewInputFile("manifest.avro")); + ICEBERG_UNWRAP_OR_FAIL(auto stream, file->Open()); + EXPECT_EQ(state->open_count, 2); + + std::string bytes(8, '_'); + auto buffer = std::as_writable_bytes(std::span(bytes)); + EXPECT_THAT(stream->Read(buffer), HasValue(::testing::Eq(4))); + EXPECT_EQ(bytes, "mani____"); + EXPECT_THAT(stream->Read(buffer), HasValue(::testing::Eq(0))); + EXPECT_THAT(stream->Seek(5), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(stream->ReadFully(0, buffer), IsError(ErrorKind::kInvalidArgument)); + ASSERT_THAT(stream->Close(), IsOk()); + EXPECT_THAT(stream->Read(buffer), IsError(ErrorKind::kInvalidArgument)); + EXPECT_FALSE(cache->Find("manifest.avro")); +} + +TEST(MetadataCacheTest, ReadAndSeekOnWarmCachedStream) { + auto storage = std::make_shared(); + storage->AddFile("manifest", "abcdef"); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + ASSERT_THAT(adapter->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("abcdef"))); + ASSERT_TRUE(cache->Find("manifest")); + storage->RemoveFile("manifest"); + ICEBERG_UNWRAP_OR_FAIL(auto file, adapter->NewInputFile("manifest")); + ICEBERG_UNWRAP_OR_FAIL(auto stream, file->Open()); + + std::string bytes(2, '_'); + auto buffer = std::as_writable_bytes(std::span(bytes)); + ASSERT_THAT(stream->Read(buffer), HasValue(::testing::Eq(2))); + EXPECT_EQ(bytes, "ab"); + ASSERT_THAT(stream->Read(buffer), HasValue(::testing::Eq(2))); + EXPECT_EQ(bytes, "cd"); + EXPECT_THAT(stream->Position(), HasValue(::testing::Eq(4))); + ASSERT_THAT(stream->Seek(1), IsOk()); + ASSERT_THAT(stream->Read(buffer), HasValue(::testing::Eq(2))); + EXPECT_EQ(bytes, "bc"); + ASSERT_THAT(stream->Seek(5), IsOk()); + bytes[1] = '_'; + ASSERT_THAT(stream->Read(buffer), HasValue(::testing::Eq(1))); + EXPECT_EQ(bytes, "f_"); + + ASSERT_THAT(stream->ReadFully(4, buffer), IsOk()); + EXPECT_EQ(bytes, "ef"); + EXPECT_THAT(stream->ReadFully(-1, buffer), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(stream->ReadFully(5, buffer), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(stream->ReadFully(6, {}), IsOk()); + ASSERT_THAT(stream->Seek(6), IsOk()); + EXPECT_THAT(stream->Seek(-1), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(stream->Seek(7), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(stream->Position(), HasValue(::testing::Eq(6))); + EXPECT_THAT(stream->Read(buffer), HasValue(::testing::Eq(0))); + + ASSERT_THAT(stream->Close(), IsOk()); + EXPECT_THAT(stream->Read(buffer), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(stream->ReadFully(0, buffer), IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(stream->Seek(0), IsError(ErrorKind::kInvalidArgument)); +} + +TEST(MetadataCacheTest, ParsesJavaCompatibleProperties) { + ContentCacheProperties properties; + properties.Set(ContentCacheProperties::kEnabled, true) + .Set(ContentCacheProperties::kMaxTotalBytes, int64_t{200}) + .Set(ContentCacheProperties::kMaxContentLength, int64_t{50}); + + ICEBERG_UNWRAP_OR_FAIL(auto options, + ContentCacheOptions::FromProperties(properties.configs())); + ASSERT_TRUE(options.has_value()); + EXPECT_EQ(options->max_total_bytes, 200); + EXPECT_EQ(options->max_content_length, 50); +} + +TEST(MetadataCacheTest, ParsesEnabledPropertyIgnoringCase) { + for (const auto* value : {"true", "TRUE", "True", "tRuE"}) { + SCOPED_TRACE(value); + ICEBERG_UNWRAP_OR_FAIL(auto options, + ContentCacheOptions::FromProperties( + {{ContentCacheProperties::kEnabled.key(), value}})); + EXPECT_TRUE(options.has_value()); + } +} + +TEST(MetadataCacheTest, TreatsOtherEnabledPropertyValuesAsFalseLikeJava) { + for (const auto* value : + {"false", "FALSE", "False", "fAlSe", "", "yes", "1", "ture", " true "}) { + SCOPED_TRACE(value); + ICEBERG_UNWRAP_OR_FAIL(auto options, + ContentCacheOptions::FromProperties( + {{ContentCacheProperties::kEnabled.key(), value}})); + EXPECT_FALSE(options.has_value()); + } +} + +TEST(MetadataCacheTest, UsesJavaCompatibleDefaults) { + ICEBERG_UNWRAP_OR_FAIL(auto defaults, ContentCacheOptions::FromProperties({})); + EXPECT_FALSE(defaults.has_value()); + + ICEBERG_UNWRAP_OR_FAIL(auto options, + ContentCacheOptions::FromProperties( + {{ContentCacheProperties::kEnabled.key(), "true"}})); + ASSERT_TRUE(options.has_value()); + EXPECT_EQ(options->max_total_bytes, 100 * 1024 * 1024); + EXPECT_EQ(options->max_content_length, 8 * 1024 * 1024); +} + +TEST(MetadataCacheTest, InvalidNumericPropertyErrorIncludesPropertyName) { + auto options = ContentCacheOptions::FromProperties( + {{ContentCacheProperties::kEnabled.key(), "true"}, + {ContentCacheProperties::kMaxTotalBytes.key(), "invalid"}}); + + EXPECT_THAT(options, IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(options, HasErrorMessage(ContentCacheProperties::kMaxTotalBytes.key())); +} + +TEST(MetadataCacheTest, IgnoresInvalidTuningPropertiesWhenDisabled) { + ICEBERG_UNWRAP_OR_FAIL( + auto options, ContentCacheOptions::FromProperties( + {{ContentCacheProperties::kEnabled.key(), "false"}, + {ContentCacheProperties::kMaxTotalBytes.key(), "invalid"}})); + EXPECT_FALSE(options.has_value()); +} + +TEST(MetadataCacheTest, PartialBatchDeleteClearsCacheAndPreservesStorageError) { + auto storage = std::make_shared(); + storage->AddFile("alias", "contents"); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + ASSERT_THAT(adapter->ReadFile("alias", std::nullopt), + HasValue(::testing::Eq("contents"))); + + ASSERT_THAT(adapter->DeleteFiles({}), IsOk()); + ASSERT_TRUE(cache->Find("alias")); + ::testing::InSequence sequence; + EXPECT_CALL(*storage, DeleteFile("canonical")).WillOnce(::testing::Return(Status{})); + EXPECT_CALL(*storage, DeleteFile("missing")).WillOnce([] { + return NotFound("missing"); + }); + EXPECT_THAT(adapter->DeleteFiles({"canonical", "missing"}), + IsError(ErrorKind::kNotFound)); + EXPECT_FALSE(cache->Find("alias")); + ASSERT_THAT(adapter->ReadFile("alias", std::nullopt), + HasValue(::testing::Eq("contents"))); + EXPECT_TRUE(cache->Find("alias")); +} + +TEST(MetadataCacheTest, RecreatingAFileDuringDeleteReadsNewBytesWithoutCaching) { + for (bool batch : {false, true}) { + SCOPED_TRACE(batch); + auto storage = std::make_shared(); + storage->AddFile("manifest", "old"); + auto cleaner = MakeCache(storage)->Wrap(); + auto writer = MakeCache(storage)->Wrap(); + auto cache = MakeCache(storage); + auto reader = cache->Wrap(); + ASSERT_THAT(reader->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("old"))); + ASSERT_TRUE(cache->Find("manifest")); + + ExpectWriteFile(*storage, "manifest", "new"); + std::unique_ptr handle_during_delete; + EXPECT_CALL(*storage, DeleteFile("manifest")).WillOnce([&]() -> Status { + storage->RemoveFile("manifest"); + EXPECT_THAT(reader->ReadFile("manifest", std::nullopt), + IsError(ErrorKind::kNotFound)); + ICEBERG_RETURN_UNEXPECTED(writer->WriteFile("manifest", "new")); + EXPECT_THAT(reader->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("new"))); + EXPECT_FALSE(cache->Find("manifest")); + ICEBERG_ASSIGN_OR_RAISE(handle_during_delete, reader->NewInputFile("manifest")); + return {}; + }); + ASSERT_THAT( + batch ? cleaner->DeleteFiles({"manifest"}) : cleaner->DeleteFile("manifest"), + IsOk()); + + ASSERT_NE(handle_during_delete, nullptr); + ASSERT_THAT(handle_during_delete->Open(), IsOk()); + EXPECT_FALSE(cache->Find("manifest")); + ASSERT_THAT(reader->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("new"))); + EXPECT_TRUE(cache->Find("manifest")); + } +} + +TEST(MetadataCacheTest, InFlightReadAheadCannotCacheBytesAfterSiblingOverwrite) { + class Storage : public MockFileIO { + public: + MOCK_METHOD((Result>), NewInputFile, (std::string), + (override)); + }; + class DelayedInput : public InputFile { + public: + std::string_view location() const override { return "manifest"; } + Result Size() const override { return 3; } + MOCK_METHOD((Result>), Open, (), (override)); + }; + for (bool pins_original_file : {true, false}) { + SCOPED_TRACE(pins_original_file); + auto storage = std::make_shared(); + storage->AddFile("manifest", "old"); + auto cache = MakeCache(storage); + auto reader = cache->Wrap(); + auto writer = MakeCache(storage)->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto old, storage->MockFileIO::NewInputFile("manifest")); + ExpectWriteFile(*storage, "manifest", "longer"); + auto delayed = std::make_unique(); + EXPECT_CALL(*delayed, Open()) + .WillOnce([&]() -> Result> { + ICEBERG_RETURN_UNEXPECTED(writer->WriteFile("manifest", "longer")); + if (pins_original_file) { + return old->Open(); + } + ICEBERG_ASSIGN_OR_RAISE(auto current, + storage->MockFileIO::NewInputFile("manifest")); + return current->Open(); + }); + EXPECT_CALL(*storage, NewInputFile("manifest")) + .WillOnce(::testing::Return(::testing::ByMove(std::move(delayed)))) + .WillOnce([&](std::string path) { + return storage->MockFileIO::NewInputFile(std::move(path)); + }); + + auto result = reader->ReadFile("manifest", std::nullopt); + if (pins_original_file) { + ASSERT_THAT(result, HasValue(::testing::Eq("old"))); + } else { + ASSERT_THAT(result, IsError(ErrorKind::kInvalid)); + } + EXPECT_FALSE(cache->Find("manifest")); + EXPECT_THAT(reader->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("longer"))); + } +} + +TEST(MetadataCacheTest, FailedOverwriteInvalidatesSiblingBeforeStorageChanges) { + class Storage : public MockFileIO { + public: + MOCK_METHOD((Result>), NewOutputFile, (std::string), + (override)); + }; + class FailingOutput : public OutputFile { + public: + std::string_view location() const override { return "manifest"; } + Result> Create() override { + return AlreadyExists("manifest exists"); + } + MOCK_METHOD((Result>), CreateOrOverwrite, (), + (override)); + }; + auto storage = std::make_shared(); + storage->AddFile("manifest", "old"); + auto cache = MakeCache(storage); + auto reader = cache->Wrap(); + auto writer = MakeCache(storage)->Wrap(); + ASSERT_THAT(reader->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("old"))); + auto output = std::make_unique(); + EXPECT_CALL(*output, CreateOrOverwrite()) + .WillOnce([&]() -> Result> { + EXPECT_FALSE(cache->Find("manifest")); + storage->AddFile("manifest", "partial"); + return NotImplemented("overwrite failed after changing storage"); + }); + EXPECT_CALL(*storage, NewOutputFile("manifest")) + .WillOnce(::testing::Return(::testing::ByMove(std::move(output)))); + + ICEBERG_UNWRAP_OR_FAIL(auto file, writer->NewOutputFile("manifest")); + EXPECT_THAT(file->CreateOrOverwrite(), + HasErrorMessage("overwrite failed after changing storage")); + EXPECT_THAT(reader->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("partial"))); + EXPECT_TRUE(cache->Find("manifest")); +} + +TEST(MetadataCacheTest, OldInputHandleOpensAfterReplacementIsCached) { + for (const auto* replacement : {"new", "longer"}) { + SCOPED_TRACE(replacement); + auto storage = std::make_shared(); + storage->AddFile("manifest.avro", "old"); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto old_file, adapter->NewInputFile("manifest.avro")); + EXPECT_CALL(*storage, DeleteFile("manifest.avro")).WillOnce([&] { + storage->RemoveFile("manifest.avro"); + return Status{}; + }); + ASSERT_THAT(adapter->DeleteFile("manifest.avro"), IsOk()); + storage->AddFile("manifest.avro", replacement); + ASSERT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq(replacement))); + + EXPECT_THAT(old_file->Size(), HasValue(::testing::Eq(3))); + ICEBERG_UNWRAP_OR_FAIL(auto old_stream, old_file->Open()); + std::string bytes(8, ' '); + EXPECT_THAT(old_stream->Read(std::as_writable_bytes(std::span(bytes))), + HasValue(::testing::Eq(3))); + EXPECT_EQ(bytes.substr(0, 3), "old"); + EXPECT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq(replacement))); + } +} + +TEST(MetadataCacheTest, OpenRespectsHandleSizeWhenALongerEntryIsAlreadyCached) { + auto storage = std::make_shared(); + storage->AddFile("manifest.avro", "manifest"); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto short_file, adapter->NewInputFile("manifest.avro", 4)); + ASSERT_THAT(short_file->Size(), HasValue(::testing::Eq(4))); + ASSERT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("manifest"))); + + ICEBERG_UNWRAP_OR_FAIL(auto stream, short_file->Open()); + std::array bytes; + EXPECT_THAT(stream->Read(bytes), HasValue(::testing::Eq(4))); + EXPECT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("manifest"))); +} + +class IgnoredHintFileIO : public MockFileIO { + public: + Result> NewInputFile(std::string location, + size_t length) override { + ++hinted_calls; + EXPECT_EQ(length, 4); + return MockFileIO::NewInputFile(std::move(location)); + } + + int hinted_calls = 0; +}; + +TEST(MetadataCacheTest, HintedInputUsesSizeReportedByStorage) { + auto storage = std::make_shared(); + storage->AddFile("manifest.avro", "manifest"); + for (size_t limit : {4, 8}) { + SCOPED_TRACE(limit); + auto cache = MakeCache(storage, ContentCacheOptions{.max_content_length = limit}); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto file, adapter->NewInputFile("manifest.avro", 4)); + EXPECT_THAT(file->Size(), HasValue(::testing::Eq(8))); + ICEBERG_UNWRAP_OR_FAIL(auto stream, file->Open()); + EXPECT_THAT(stream->Close(), IsOk()); + EXPECT_EQ(static_cast(cache->Find("manifest.avro")), limit == 8); + EXPECT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("manifest"))); + } + EXPECT_EQ(storage->hinted_calls, 2); +} + +class CountingFileIO : public MockFileIO { + public: + using MockFileIO::NewInputFile; + Result> NewInputFile(std::string location) override { + ++unhinted_calls; + return MockFileIO::NewInputFile(std::move(location)); + } + int unhinted_calls = 0; +}; + +TEST(MetadataCacheTest, ShortHintOnFirstOpenDoesNotPublishAPrefix) { + auto storage = std::make_shared(); + storage->AddFile("manifest.avro", "manifest"); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto file, adapter->NewInputFile("manifest.avro", 4)); + EXPECT_EQ(storage->unhinted_calls, 0); + ICEBERG_UNWRAP_OR_FAIL(auto stream, file->Open()); + ASSERT_THAT(file->Open(), IsOk()); + EXPECT_EQ(storage->unhinted_calls, 1); + std::array buffer; + EXPECT_THAT(stream->Read(buffer), HasValue(::testing::Eq(4))); + EXPECT_FALSE(cache->Find("manifest.avro")); + EXPECT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("manifest"))); +} + +TEST(MetadataCacheTest, BypassedHandlesReuseTheirStorageSize) { + for (int64_t size : {0, 9}) { + auto state = std::make_shared(); + state->size = size; + auto cache = MakeCache(std::make_shared(state), + ContentCacheOptions{.max_content_length = 8}); + ICEBERG_UNWRAP_OR_FAIL(auto input, cache->NewInputFile("manifest.avro")); + EXPECT_THAT(input->Size(), HasValue(::testing::Eq(size))); + EXPECT_THAT(input->Size(), HasValue(::testing::Eq(size))); + EXPECT_EQ(state->size_count, 1); + EXPECT_EQ(state->open_count, 0); + } +} + +TEST(MetadataCacheTest, CredentialedFileIOCanCacheInAStableNamespace) { + class CredentialedFileIO : public MockFileIO, public SupportsStorageCredentials { + public: + SupportsStorageCredentials* AsSupportsStorageCredentials() override { return this; } + Status SetStorageCredentials( + const std::vector& credentials) override { + credentials_ = credentials; + return {}; + } + std::vector credentials() const override { return credentials_; } + + private: + std::vector credentials_; + }; + auto storage = std::make_shared(); + storage->AddFile("manifest.avro", "manifest"); + auto adapter = MakeCache(storage)->Wrap(); + ASSERT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("manifest"))); + ASSERT_THAT(storage->SetStorageCredentials({{"manifest.avro", {{"token", "rotated"}}}}), + IsOk()); + storage->RemoveFile("manifest.avro"); + EXPECT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("manifest"))); +} + +TEST(MetadataCacheTest, NestedCacheFollowsInnerOverwrites) { + auto storage = std::make_shared(); + storage->AddFile("manifest", "old"); + // Only the outer adapter retains this file. + auto inner = MakeCache(storage, ContentCacheOptions{.max_content_length = 1})->Wrap(); + auto outer = MakeCache(inner)->Wrap(); + ASSERT_THAT(outer->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("old"))); + ExpectWriteFile(*storage, "manifest", "new"); + ASSERT_THAT(inner->WriteFile("manifest", "new"), IsOk()); + EXPECT_THAT(outer->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("new"))); +} + +TEST(MetadataCacheTest, NestedCacheInvalidatesRecreatedFileBeforeStreamingWrite) { + auto storage = std::make_shared(); + storage->AddFile("manifest", "old"); + auto inner = MakeCache(storage, ContentCacheOptions{.max_content_length = 1})->Wrap(); + auto cache = MakeCache(inner); + auto outer = cache->Wrap(); + ASSERT_THAT(outer->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("old"))); + ASSERT_TRUE(cache->Find("manifest")); + storage->RemoveFile("manifest"); + + ICEBERG_UNWRAP_OR_FAIL(auto file, inner->NewOutputFile("manifest")); + ICEBERG_UNWRAP_OR_FAIL(auto writer, file->CreateOrOverwrite()); + EXPECT_FALSE(cache->Find("manifest")); + auto bytes = std::as_bytes(std::span("ab", 2)); + ASSERT_THAT(writer->Write(bytes), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto partial, outer->NewInputFile("manifest")); + ASSERT_THAT(outer->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("ab"))); + EXPECT_FALSE(cache->Find("manifest")); + ASSERT_THAT(writer->Write(bytes), IsOk()); + ASSERT_THAT(writer->Close(), IsOk()); + + ASSERT_THAT(partial->Open(), IsError(ErrorKind::kInvalid)); + EXPECT_FALSE(cache->Find("manifest")); + EXPECT_THAT(outer->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("abab"))); +} + +TEST(MetadataCacheTest, ExplicitClearOnlyAffectsTheTableAndItsOuterAdapters) { + auto storage = std::make_shared(); + storage->AddFile("manifest", "content"); + auto table = MakeCache(storage); + auto outer = MakeCache(table->Wrap()); + auto sibling = MakeCache(storage); + for (const auto& cache : {outer, sibling}) { + ASSERT_THAT(cache->Wrap()->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("content"))); + } + std::weak_ptr> outer_bytes = outer->Find("manifest"); + ASSERT_FALSE(outer_bytes.expired()); + table->Clear(); + EXPECT_TRUE(outer_bytes.expired()); + EXPECT_FALSE(table->Find("manifest")); + EXPECT_FALSE(outer->Find("manifest")); + EXPECT_TRUE(sibling->Find("manifest")); +} + +TEST(MetadataCacheTest, ConcurrentInsertionsShareTheWinnerForTheSameSizeAndGeneration) { + auto cache = MakeCache(); + auto insert = [&](size_t size, uint64_t generation) { + return cache->Insert("manifest", std::make_shared>(size), + generation); + }; + std::barrier start(2); + internal::MetadataContent first; + std::jthread loader([&] { + start.arrive_and_wait(); + first = insert(8, 0); + }); + start.arrive_and_wait(); + auto second = insert(8, 0); + loader.join(); + ASSERT_EQ(first, second); + EXPECT_NE(insert(4, 0), first); + EXPECT_EQ(cache->Find("manifest"), first); + cache->Clear(); + auto replacement = insert(8, 1); + EXPECT_NE(insert(8, 0), replacement); + EXPECT_EQ(cache->Find("manifest"), replacement); +} + +TEST(MetadataCacheTest, SizeMismatchDoesNotPromoteAFileWithinItsTable) { + auto cache = MakeCache(std::make_shared(), + ContentCacheOptions{.max_total_bytes = 4}); + auto bytes = std::make_shared>(2); + cache->Insert("a", bytes, 0); + cache->Insert("b", bytes, 0); + EXPECT_FALSE(cache->FindForHandle("a", 0, 1)); + cache->Insert("a", std::make_shared>(1), 0); + cache->Insert("c", bytes, 0); + EXPECT_FALSE(cache->Find("a")); + EXPECT_EQ(cache->Find("b"), bytes); +} + +TEST(MetadataCacheTest, MissInAnActiveTableDoesNotRefreshItsGlobalSlot) { + ScopedGlobalCacheLimit limit(2); + auto first = MakeCache(); + auto second = MakeCache(); + auto third = MakeCache(); + auto bytes = std::make_shared>(1); + first->Insert("a", bytes, 0); + second->Insert("b", bytes, 0); + EXPECT_FALSE(first->Find("missing")); + third->Insert("c", bytes, 0); + EXPECT_FALSE(first->Find("a")); + EXPECT_TRUE(second->Find("b")); +} + +TEST(MetadataCacheTest, ReadersOverlappingFreshWritesCannotPublishPartialBytes) { + auto storage = std::make_shared(); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto output, adapter->NewOutputFile("fresh")); + ICEBERG_UNWRAP_OR_FAIL(auto writer, output->CreateOrOverwrite()); + auto bytes = std::as_bytes(std::span("ab", 2)); + ASSERT_THAT(writer->Write(bytes), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto partial, adapter->NewInputFile("fresh")); + EXPECT_THAT(adapter->ReadFile("fresh", std::nullopt), HasValue(::testing::Eq("ab"))); + ASSERT_FALSE(cache->Find("fresh")); + ASSERT_THAT(writer->Write(bytes), IsOk()); + EXPECT_THAT(partial->Open(), IsError(ErrorKind::kInvalid)); + ASSERT_THAT(writer->Close(), IsOk()); + ASSERT_THAT(partial->Open(), IsError(ErrorKind::kInvalid)); + EXPECT_FALSE(cache->Find("fresh")); + ASSERT_THAT(adapter->ReadFile("fresh", std::nullopt), HasValue(::testing::Eq("abab"))); + ASSERT_TRUE(cache->Find("fresh")); + const int calls_after_fill = storage->unhinted_calls; + EXPECT_THAT(adapter->ReadFile("fresh", std::nullopt), HasValue(::testing::Eq("abab"))); + EXPECT_EQ(storage->unhinted_calls, calls_after_fill); +} + +TEST(MetadataCacheTest, FailedCreateAllowsSubsequentCacheFills) { + auto storage = std::make_shared(); + storage->AddFile("manifest", "original"); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto output, adapter->NewOutputFile("manifest")); + ASSERT_THAT(output->Create(), IsError(ErrorKind::kAlreadyExists)); + ASSERT_THAT(adapter->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("original"))); + EXPECT_TRUE(cache->Find("manifest")); +} + +TEST(MetadataCacheTest, DestroyingAnUnclosedWriterAllowsNewReadersToFillCache) { + auto storage = std::make_shared(); + storage->AddFile("manifest", "contents"); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto output, adapter->NewOutputFile("fresh")); + ICEBERG_UNWRAP_OR_FAIL(auto writer, output->Create()); + ASSERT_THAT(writer->Write(std::as_bytes(std::span("ab", 2))), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto overlapping, adapter->NewInputFile("manifest")); + ASSERT_THAT(adapter->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("contents"))); + ASSERT_FALSE(cache->Find("manifest")); + + writer.reset(); + ASSERT_THAT(overlapping->Open(), IsOk()); + EXPECT_FALSE(cache->Find("manifest")); + ASSERT_THAT(adapter->ReadFile("manifest", std::nullopt), + HasValue(::testing::Eq("contents"))); + EXPECT_TRUE(cache->Find("manifest")); +} + +TEST(MetadataCacheTest, PrefixReadDoesNotPopulateWholeFileCache) { + auto storage = std::make_shared(); + storage->AddFile("manifest.avro", "manifest"); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + + EXPECT_CALL(*storage, ReadFile("manifest.avro", std::optional{4})) + .WillOnce(::testing::Return(std::string("mani"))); + EXPECT_THAT(adapter->ReadFile("manifest.avro", 4), HasValue(::testing::Eq("mani"))); + EXPECT_FALSE(cache->Find("manifest.avro")); + EXPECT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("manifest"))); +} + +TEST(MetadataCacheTest, OversizedReadDoesNotDisplaceAWarmCache) { + ScopedGlobalCacheLimit limit(1); + auto warm = MakeCache(); + warm->Insert("warm.avro", std::make_shared>(1), 0); + + auto storage = std::make_shared(); + storage->AddFile("large.avro", "large"); + auto cold = MakeCache(storage, ContentCacheOptions{.max_content_length = 4}); + EXPECT_THAT(cold->Wrap()->ReadFile("large.avro", std::nullopt), + HasValue(::testing::Eq("large"))); + EXPECT_FALSE(cold->Find("large.avro")); + EXPECT_TRUE(warm->Find("warm.avro")); +} + +TEST(MetadataCacheTest, GlobalEvictionReleasesBytesAndReadersKeepTheirContent) { + ScopedGlobalCacheLimit limit(1); + auto first = MakeCache(); + auto content = std::make_shared>(8); + std::weak_ptr> weak_content = content; + first->Insert("manifest.avro", std::move(content), 0); + auto adapter = first->Wrap(); + ICEBERG_UNWRAP_OR_FAIL(auto file, adapter->NewInputFile("manifest.avro")); + ICEBERG_UNWRAP_OR_FAIL(auto reader, file->Open()); + file.reset(); + auto second = MakeCache(); + second->Insert("other.avro", std::make_shared>(8), 0); + EXPECT_FALSE(first->Find("manifest.avro")); + // Only the active reader still owns these bytes after global eviction. + EXPECT_FALSE(weak_content.expired()); + std::array out; + ASSERT_THAT(reader->ReadFully(0, out), IsOk()); + EXPECT_EQ(out, (std::array{})); + reader.reset(); + EXPECT_TRUE(weak_content.expired()); +} + +TEST(MetadataCacheTest, DestroyingLastCacheHandleReleasesRetainedBytes) { + auto cache = MakeCache(); + auto content = std::make_shared>(8); + std::weak_ptr> weak_content = content; + cache->Insert("manifest.avro", std::move(content), 0); + ASSERT_FALSE(weak_content.expired()); + cache.reset(); + EXPECT_TRUE(weak_content.expired()); +} + +TEST(MetadataCacheTest, DestroyedCacheFreesItsSlotWithoutEvictingALiveCache) { + ScopedGlobalCacheLimit limit(2); + auto first = MakeCache(); + first->Insert("first", std::make_shared>(1), 0); + std::weak_ptr weak_cache; + { + auto second = MakeCache(); + weak_cache = second; + second->Insert("second", std::make_shared>(1), 0); + } + ASSERT_TRUE(weak_cache.expired()); + auto third = MakeCache(); + third->Insert("third", std::make_shared>(1), 0); + EXPECT_TRUE(first->Find("first")); + EXPECT_TRUE(third->Find("third")); +} + +TEST(MetadataCacheTest, LoweringGlobalCapacityEvictsLeastRecentlyUsedTables) { + ScopedGlobalCacheLimit limit(3); + auto first = MakeCache(); + auto second = MakeCache(); + auto third = MakeCache(); + const auto bytes = std::make_shared>(1); + first->Insert("first", bytes, 0); + second->Insert("second", bytes, 0); + third->Insert("third", bytes, 0); + EXPECT_THAT(internal::ContentCache::SetGlobalCapacity(0), + IsError(ErrorKind::kInvalidArgument)); + auto negative = internal::ContentCache::SetGlobalCapacity(-3); + EXPECT_THAT(negative, IsError(ErrorKind::kInvalidArgument)); + EXPECT_THAT(negative, + HasErrorMessage("Global manifest cache limit must be positive, got -3")); + ASSERT_TRUE(second->Find("second")); + ASSERT_TRUE(third->Find("third")); + ASSERT_TRUE(first->Find("first")); + ASSERT_THAT(internal::ContentCache::SetGlobalCapacity(1), HasValue(::testing::Eq(3))); + EXPECT_TRUE(first->Find("first")); + EXPECT_FALSE(second->Find("second")); + EXPECT_FALSE(third->Find("third")); +} + +TEST(MetadataCacheTest, ClearingCacheFreesItsGlobalSlot) { + ScopedGlobalCacheLimit limit(2); + auto first = MakeCache(); + auto second = MakeCache(); + auto third = MakeCache(); + const auto bytes = std::make_shared>(1); + first->Insert("first", bytes, 0); + second->Insert("second", bytes, 0); + second->Clear(); + third->Insert("third", bytes, 0); + EXPECT_TRUE(first->Find("first")); + EXPECT_FALSE(second->Find("second")); + EXPECT_TRUE(third->Find("third")); +} + +TEST(MetadataCacheTest, DeletingThroughSiblingReleasesBytesAndGlobalSlotImmediately) { + ScopedGlobalCacheLimit limit(2); + auto storage = std::make_shared(); + auto reader_cache = MakeCache(storage); + auto deleter = MakeCache(storage)->Wrap(); + auto healthy = MakeCache(); + auto newcomer = MakeCache(); + auto bytes = std::make_shared>(1); + healthy->Insert("healthy", bytes, 0); + storage->AddFile("manifest", "old"); + ASSERT_THAT(reader_cache->Wrap()->ReadFile("manifest", std::nullopt), IsOk()); + std::weak_ptr> retained = reader_cache->Find("manifest"); + ASSERT_FALSE(retained.expired()); + + EXPECT_CALL(*storage, DeleteFile("manifest")).WillOnce([&] { + EXPECT_TRUE(retained.expired()); + newcomer->Insert("new", bytes, 0); + EXPECT_EQ(healthy->Find("healthy"), bytes); + storage->RemoveFile("manifest"); + return Status{}; + }); + EXPECT_THAT(deleter->DeleteFile("manifest"), IsOk()); +} + +TEST(MetadataCacheTest, InvalidatedLoadCannotPopulateRecreatedCacheState) { + ScopedGlobalCacheLimit limit(1); + auto cache = MakeCache(); + uint64_t generation; + ASSERT_FALSE(cache->Find("manifest.avro", &generation)); + auto other = MakeCache(); + other->Insert("other.avro", std::make_shared>(8), 0); + cache->Clear(); + cache->Insert("manifest.avro", std::make_shared>(8), + generation); + EXPECT_FALSE(cache->Find("manifest.avro")); +} + +} // namespace +} // namespace iceberg diff --git a/src/iceberg/test/mock_io.h b/src/iceberg/test/mock_io.h index 63abb6ea6..45641563c 100644 --- a/src/iceberg/test/mock_io.h +++ b/src/iceberg/test/mock_io.h @@ -84,6 +84,8 @@ class MockFileIO : public FileIO { std::as_bytes(std::span(data.data(), data.size()))); } + void RemoveFile(const std::string& file_location) { files_->erase(file_location); } + std::vector& FileData(const std::string& file_location) { return *GetOrCreateFile(file_location); } diff --git a/src/iceberg/util/cache_internal.h b/src/iceberg/util/cache_internal.h index d82a93b80..3070e24e7 100644 --- a/src/iceberg/util/cache_internal.h +++ b/src/iceberg/util/cache_internal.h @@ -33,72 +33,120 @@ #include #include +#include "iceberg/exception.h" #include "iceberg/util/macros.h" namespace iceberg::internal { -// A LRU (Least recently used) replacement cache -template +// A least recently used cache. Replace accepts an entry weight (one by default). +// Storage grows as entries are inserted, up to the maximum combined weight. +template , + typename KeyEqual = std::equal_to> class LruCache { public: - explicit LruCache(int32_t capacity) : capacity_(capacity) { - // The map size can temporarily exceed the cache capacity, see Replace() - map_.reserve(capacity_ + 1); + explicit LruCache(int64_t max_weight) : max_weight_(max_weight) { + ICEBERG_CHECK_OR_DIE(max_weight >= 0, "Cache maximum weight must be non-negative"); } LruCache(const LruCache&) = delete; LruCache& operator=(const LruCache&) = delete; - LruCache(LruCache&&) noexcept = default; - LruCache& operator=(LruCache&&) noexcept = default; + LruCache(LruCache&& other) noexcept : LruCache(other.max_weight_) { + *this = std::move(other); + } + + LruCache& operator=(LruCache&& other) noexcept { + if (this != &other) { + Clear(); + items_.swap(other.items_); + map_.swap(other.map_); + max_weight_ = other.max_weight_; + total_weight_ = std::exchange(other.total_weight_, 0); + } + return *this; + } void Clear() { items_.clear(); map_.clear(); - // The C++ spec doesn't tell whether map_.clear() will shrink the map capacity - map_.reserve(capacity_ + 1); + total_weight_ = 0; } + // Number of retained entries. int32_t size() const { ICEBERG_DCHECK(items_.size() == map_.size(), "Cache item and map sizes differ"); return static_cast(items_.size()); } + // Combined weight of retained entries. + int64_t total_weight() const { return total_weight_; } + + // Maximum combined weight allowed in this cache. + int64_t max_weight() const { return max_weight_; } + + // Apply a new limit immediately, evicting least recently used entries as needed. + Status Resize(int64_t max_weight) { + ICEBERG_PRECHECK(max_weight >= 0, "Cache maximum weight must be non-negative"); + max_weight_ = max_weight; + while (total_weight_ > max_weight_) { + EvictLeastRecentlyUsed(); + } + return {}; + } + template - Value* Find(K&& key) { + const Value* Find(K&& key) { + return FindAndPromoteIf(std::forward(key), [](const Value&) { return true; }); + } + + // Return the stored value even when the caller cannot use it. Only a value + // accepted by the caller counts as a use for eviction order. + template + const Value* FindAndPromoteIf(K&& key, Predicate promote) { const auto it = map_.find(key); if (it == map_.end()) { return nullptr; } - // Found => move item at front of the list auto list_it = it->second; - items_.splice(items_.begin(), items_, list_it); + if (promote(list_it->value)) { + items_.splice(items_.begin(), items_, list_it); + } return &list_it->value; } + // Insert or update the value for `key`, mark it as most recently used, and evict least + // recently used entries until the cache is within its maximum weight again. + // + // Returns whether a new entry was added, and a pointer to the cached value. A value + // heavier than the maximum weight is not cached: any existing entry for `key` is + // removed, other entries are kept, and {false, nullptr} is returned. A negative + // weight returns InvalidArgument before modifying the cache. + // Use Replace to change a cached value. A successful replacement invalidates the + // previous value pointer. template - std::pair Replace(K&& key, V&& value) { - // Try to insert temporary iterator - auto [it, inserted] = map_.emplace(std::forward(key), ListIt{}); - if (inserted) { - // Inserted => push item at front of the list, and update iterator - items_.emplace_front(&it->first, std::forward(value)); - it->second = items_.begin(); - // Did we exceed the cache capacity? If so, remove least recently used item - if (static_cast(items_.size()) > capacity_) { - const bool erased = map_.erase(*items_.back().key); - ICEBERG_DCHECK(erased, "Failed to erase least recently used cache item"); - static_cast(erased); - items_.pop_back(); - } - return {true, &it->second->value}; + Result> Replace(K&& key, V&& value, int64_t weight = 1) { + ICEBERG_PRECHECK(weight >= 0, "Cache entry weight must be non-negative"); + List candidate; + auto& item = candidate.emplace_front(nullptr, std::forward(value), weight); + auto [it, inserted] = map_.try_emplace(std::forward(key)); + item.key = &it->first; + if (!inserted) { + total_weight_ -= it->second->weight; + items_.erase(it->second); + } + if (item.weight > max_weight_) { + map_.erase(it); + return std::pair{false, nullptr}; } - // Already exists => move item at front of the list, and update value - auto list_it = it->second; - items_.splice(items_.begin(), items_, list_it); - list_it->value = std::forward(value); - return {false, &list_it->value}; + items_.splice(items_.begin(), candidate); + it->second = items_.begin(); + // Subtract from the limit before adding the new weight to avoid overflow. + while (total_weight_ > max_weight_ - item.weight) { + EvictLeastRecentlyUsed(); + } + total_weight_ += item.weight; + return std::pair{inserted, &item.value}; } private: @@ -106,14 +154,26 @@ class LruCache { // Pointer to the key inside the unordered_map const Key* key; Value value; + int64_t weight; }; using List = std::list; using ListIt = typename List::iterator; - const int32_t capacity_; + void EvictLeastRecentlyUsed() { + ICEBERG_DCHECK(!items_.empty(), "Cannot evict from an empty cache"); + const Item& item = items_.back(); + total_weight_ -= item.weight; + const bool erased = map_.erase(*item.key); + ICEBERG_DCHECK(erased, "Failed to erase least recently used cache item"); + static_cast(erased); + items_.pop_back(); + } + + int64_t max_weight_; + int64_t total_weight_ = 0; // In most to least recently used order std::list items_; - std::unordered_map map_; + std::unordered_map map_; }; template @@ -135,7 +195,11 @@ struct ThreadSafeMemoizer { lock.unlock(); Value value = func_(key); lock.lock(); - return *cache_.Replace(std::forward(key), std::move(value)).second; + ICEBERG_ASSIGN_OR_THROW(auto entry, + cache_.Replace(std::forward(key), std::move(value))); + ICEBERG_CHECK_OR_DIE(entry.second != nullptr, + "Memoization cache capacity must be positive"); + return *entry.second; } private: @@ -158,7 +222,11 @@ struct ThreadUnsafeMemoizer { return *value_ptr; } Value value = func_(key); - return *cache_.Replace(std::forward(key), std::move(value)).second; + ICEBERG_ASSIGN_OR_THROW(auto entry, + cache_.Replace(std::forward(key), std::move(value))); + ICEBERG_CHECK_OR_DIE(entry.second != nullptr, + "Memoization cache capacity must be positive"); + return *entry.second; } private: @@ -184,7 +252,7 @@ auto Memoize(Func&& func, int32_t cache_capacity) { return Memoizer(std::forward(func), cache_capacity); } -// Apply a LRU memoization cache to a callable. +// Apply a LRU memoization cache to a callable. Calls require positive capacity. template auto MemoizeLru(Func&& func, int32_t cache_capacity) { return Memoize(std::forward(func), cache_capacity); diff --git a/src/iceberg/util/error_util_internal.h b/src/iceberg/util/error_util_internal.h index 8ecfd3ce1..529514265 100644 --- a/src/iceberg/util/error_util_internal.h +++ b/src/iceberg/util/error_util_internal.h @@ -21,11 +21,25 @@ #include #include +#include #include "iceberg/logging/log_macros.h" +#include "iceberg/result.h" namespace iceberg::internal { +inline Status FinishWithCloseStatus(Status operation_status, Status close_status) { + if (operation_status.has_value()) { + return close_status; + } + auto error = std::move(operation_status).error(); + if (!close_status.has_value()) { + error.message += "; close also failed: "; + error.message += close_status.error().message; + } + return unexpected(std::move(error)); +} + template void LogAndIgnoreFailure(std::string_view name, Action&& action) noexcept { try { diff --git a/src/iceberg/util/property_util.cc b/src/iceberg/util/property_util.cc index 7fbd23d44..b990cf8d3 100644 --- a/src/iceberg/util/property_util.cc +++ b/src/iceberg/util/property_util.cc @@ -23,6 +23,7 @@ #include #include "iceberg/table_properties.h" +#include "iceberg/util/macros.h" #include "iceberg/util/string_util.h" namespace iceberg { @@ -47,6 +48,19 @@ Status PropertyUtil::ValidateCommitProperties( return {}; } +Result PropertyUtil::PropertyAsInt64( + const std::unordered_map& properties, std::string_view key, + int64_t default_value) { + auto it = properties.find(std::string(key)); + if (it == properties.end()) { + return default_value; + } + auto result = StringUtils::ParseNumber(it->second); + ICEBERG_PRECHECK(result.has_value(), "Invalid numeric value '{}' for property '{}': {}", + it->second, key, result.error().message); + return result; +} + bool PropertyUtil::PropertyAsBoolean( const std::unordered_map& properties, std::string_view key, bool default_value) { diff --git a/src/iceberg/util/property_util.h b/src/iceberg/util/property_util.h index 72bbf9f04..83fd8de4c 100644 --- a/src/iceberg/util/property_util.h +++ b/src/iceberg/util/property_util.h @@ -22,6 +22,7 @@ /// \file iceberg/util/property_util.h /// \brief Provide property conversion helpers. +#include #include #include #include @@ -37,6 +38,11 @@ class ICEBERG_EXPORT PropertyUtil { static Status ValidateCommitProperties( const std::unordered_map& properties); + /// \brief Read a signed 64-bit property, returning the default when absent. + static Result PropertyAsInt64( + const std::unordered_map& properties, + std::string_view key, int64_t default_value); + /// \brief Read a boolean property from a property map. /// /// Mirrors Java's PropertyUtil.propertyAsBoolean: the value is parsed with