timothyw553 commented on code in PR #1174: URL: https://github.com/apache/iceberg-cpp/pull/1174#discussion_r4746763603
########## src/iceberg/content_cache.cc: ########## @@ -0,0 +1,648 @@ +/* + * 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 <algorithm> +#include <atomic> +#include <cstring> +#include <format> +#include <list> +#include <mutex> +#include <shared_mutex> +#include <stdexcept> +#include <utility> + +#include "iceberg/content_cache_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<std::string, MetadataContent, StringHash, StringEqual>; + +// 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<std::weak_ptr<ContentCacheRegistration>>; + Entries::iterator position; + std::shared_ptr<CachedFiles> files; + // Accessed under the per-table mutex. A miss needs no registry lock. + std::weak_ptr<CachedFiles> last_files; +}; + +// Adapters over one storage FileIO share mutation state. Each table still owns +// its own cached bytes. The registry mutex protects the number of bound caches. +struct ContentCacheStorage { + explicit ContentCacheStorage(FileIO* file_io) : io(file_io) {} + FileIO* const io; + size_t caches = 0; + std::shared_mutex mutex; + size_t active_writes = 0; + uint64_t finished_writes = 0; + uint64_t invalidations = 0; + std::atomic<bool> ever_cached = false; +}; + +class ContentCacheRegistry { + public: + explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {} + + ContentCacheStorage& Bind(FileIO* io) { + if (!io) { + throw std::invalid_argument("Content cache requires a storage FileIO"); + } + std::lock_guard lock(mutex_); + auto& storage = storage_.try_emplace(io, io).first->second; + ++storage.caches; + return storage; + } + + void Unbind(ContentCacheStorage& storage) { + std::lock_guard lock(mutex_); + if (--storage.caches == 0) { + storage_.erase(storage.io); + } + } + + bool IsActive(const ContentCacheRegistration& entry, + const std::shared_ptr<CachedFiles>& 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<CachedFiles> GetOrCreate( + const std::shared_ptr<ContentCacheRegistration>& entry, size_t max_total_bytes) { + std::shared_ptr<CachedFiles> evicted; + std::lock_guard lock(mutex_); + if (entry->files) { + entries_.splice(entries_.begin(), entries_, entry->position); + } else { + auto files = std::make_shared<CachedFiles>(static_cast<int64_t>(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; + } + + void Erase(ContentCacheRegistration& entry) { + std::shared_ptr<CachedFiles> evicted; + std::lock_guard lock(mutex_); + if (entry.files) { + entries_.erase(entry.position); + evicted = std::move(entry.files); + } + } + + int32_t SetCapacity(int32_t capacity) { + if (capacity <= 0) { + throw std::invalid_argument( + std::format("Global manifest cache limit must be positive, got {}", capacity)); + } + std::vector<std::shared_ptr<CachedFiles>> evicted; + std::lock_guard lock(mutex_); + if (std::cmp_greater(entries_.size(), capacity)) { + evicted.reserve(entries_.size() - static_cast<size_t>(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<CachedFiles> 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<const FileIO*, ContentCacheStorage> storage_; +}; + +namespace { + +// Match Iceberg Java's default for iceberg.io.manifest.cache.fileio-max. +constexpr int32_t kDefaultMaxTableCaches = 8; + +std::shared_ptr<ContentCacheRegistry> GlobalContentCacheRegistry() { + // Handles keep the registry alive even when destroyed during static teardown. + static auto registry = std::make_shared<ContentCacheRegistry>(kDefaultMaxTableCaches); + return registry; +} + +Result<std::vector<std::byte>> ReadInputFile(InputFile& input_file, int64_t read_size, + std::string_view file_location) { + if (!std::in_range<size_t>(read_size)) { + return Invalid("File size {} for {} does not fit in size_t", read_size, + file_location); + } + + std::vector<std::byte> content(static_cast<size_t>(read_size)); + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open()); + auto read_status = stream->ReadFully(/*position=*/0, content); + ICEBERG_RETURN_UNEXPECTED( + FinishWithCloseStatus(std::move(read_status), stream->Close())); + return content; +} + +class SizedInputStream : public SeekableInputStream { + public: + explicit SizedInputStream(MetadataContent content) + : size_(content->size()), content_(std::move(content)) {} + SizedInputStream(std::unique_ptr<SeekableInputStream> input, size_t size) + : size_(size), input_(std::move(input)) {} + + Result<int64_t> Position() const override { + return input_ ? input_->Position() : Result<int64_t>(position_); + } + + Status Seek(int64_t position) override { Review Comment: looks like the tests never call `Seek`, and the `Read` calls in `metadata_cache_test.cc` only hit wrapped storage streams rather than the in-memory `content_` branch. since avro decoding uses both, could we add tests on an actual cached stream for sequential `Read`, `Seek` (backward, eof, invalid positions), `ReadFully` bounds, and reads after `Close()`? ########## src/iceberg/content_cache.cc: ########## @@ -0,0 +1,648 @@ +/* + * 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 <algorithm> +#include <atomic> +#include <cstring> +#include <format> +#include <list> +#include <mutex> +#include <shared_mutex> +#include <stdexcept> +#include <utility> + +#include "iceberg/content_cache_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<std::string, MetadataContent, StringHash, StringEqual>; + +// 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<std::weak_ptr<ContentCacheRegistration>>; + Entries::iterator position; + std::shared_ptr<CachedFiles> files; + // Accessed under the per-table mutex. A miss needs no registry lock. + std::weak_ptr<CachedFiles> last_files; +}; + +// Adapters over one storage FileIO share mutation state. Each table still owns +// its own cached bytes. The registry mutex protects the number of bound caches. +struct ContentCacheStorage { + explicit ContentCacheStorage(FileIO* file_io) : io(file_io) {} + FileIO* const io; + size_t caches = 0; + std::shared_mutex mutex; + size_t active_writes = 0; + uint64_t finished_writes = 0; + uint64_t invalidations = 0; + std::atomic<bool> ever_cached = false; +}; + +class ContentCacheRegistry { + public: + explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {} + + ContentCacheStorage& Bind(FileIO* io) { + if (!io) { + throw std::invalid_argument("Content cache requires a storage FileIO"); + } + std::lock_guard lock(mutex_); + auto& storage = storage_.try_emplace(io, io).first->second; + ++storage.caches; + return storage; + } + + void Unbind(ContentCacheStorage& storage) { + std::lock_guard lock(mutex_); + if (--storage.caches == 0) { + storage_.erase(storage.io); + } + } + + bool IsActive(const ContentCacheRegistration& entry, + const std::shared_ptr<CachedFiles>& 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<CachedFiles> GetOrCreate( + const std::shared_ptr<ContentCacheRegistration>& entry, size_t max_total_bytes) { + std::shared_ptr<CachedFiles> evicted; + std::lock_guard lock(mutex_); + if (entry->files) { + entries_.splice(entries_.begin(), entries_, entry->position); + } else { + auto files = std::make_shared<CachedFiles>(static_cast<int64_t>(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; + } + + void Erase(ContentCacheRegistration& entry) { + std::shared_ptr<CachedFiles> evicted; + std::lock_guard lock(mutex_); + if (entry.files) { + entries_.erase(entry.position); + evicted = std::move(entry.files); + } + } + + int32_t SetCapacity(int32_t capacity) { + if (capacity <= 0) { + throw std::invalid_argument( + std::format("Global manifest cache limit must be positive, got {}", capacity)); + } + std::vector<std::shared_ptr<CachedFiles>> evicted; + std::lock_guard lock(mutex_); + if (std::cmp_greater(entries_.size(), capacity)) { + evicted.reserve(entries_.size() - static_cast<size_t>(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<CachedFiles> 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<const FileIO*, ContentCacheStorage> storage_; +}; + +namespace { + +// Match Iceberg Java's default for iceberg.io.manifest.cache.fileio-max. +constexpr int32_t kDefaultMaxTableCaches = 8; + +std::shared_ptr<ContentCacheRegistry> GlobalContentCacheRegistry() { + // Handles keep the registry alive even when destroyed during static teardown. + static auto registry = std::make_shared<ContentCacheRegistry>(kDefaultMaxTableCaches); + return registry; +} + +Result<std::vector<std::byte>> ReadInputFile(InputFile& input_file, int64_t read_size, + std::string_view file_location) { + if (!std::in_range<size_t>(read_size)) { + return Invalid("File size {} for {} does not fit in size_t", read_size, + file_location); + } + + std::vector<std::byte> content(static_cast<size_t>(read_size)); + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open()); + auto read_status = stream->ReadFully(/*position=*/0, content); + ICEBERG_RETURN_UNEXPECTED( + FinishWithCloseStatus(std::move(read_status), stream->Close())); + return content; +} + +class SizedInputStream : public SeekableInputStream { + public: + explicit SizedInputStream(MetadataContent content) + : size_(content->size()), content_(std::move(content)) {} + SizedInputStream(std::unique_ptr<SeekableInputStream> input, size_t size) + : size_(size), input_(std::move(input)) {} + + Result<int64_t> Position() const override { + return input_ ? input_->Position() : Result<int64_t>(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(std::cmp_less_equal(position, size_), + "Position {} exceeds file size {}", position, size_); + if (input_) { + return input_->Seek(position); + } + position_ = position; + return {}; + } + + Result<int64_t> Read(std::span<std::byte> out) override { + ICEBERG_PRECHECK(!closed_, "Input stream is closed"); + if (input_) { + ICEBERG_ASSIGN_OR_RAISE(auto current, input_->Position()); + ICEBERG_PRECHECK(current >= 0 && std::cmp_less_equal(current, size_), + "Invalid stream position {}", current); + return input_->Read( + out.first(std::min(out.size(), size_ - static_cast<size_t>(current)))); + } + auto position = static_cast<size_t>(position_); + auto bytes_to_read = std::min(out.size(), size_ - position); + if (bytes_to_read > 0) { + std::memcpy(out.data(), content_->data() + position, bytes_to_read); + position_ += static_cast<int64_t>(bytes_to_read); + } + return static_cast<int64_t>(bytes_to_read); + } + + Status ReadFully(int64_t position, std::span<std::byte> out) override { + ICEBERG_PRECHECK(!closed_, "Input stream is closed"); + ICEBERG_PRECHECK(position >= 0, "Position must not be negative: {}", position); + ICEBERG_PRECHECK(std::cmp_less_equal(position, size_), + "Position {} exceeds file size {}", position, size_); + auto offset = static_cast<size_t>(position); + ICEBERG_PRECHECK(out.size() <= size_ - offset, + "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() + offset, out.size()); + } + return {}; + } + + Status Close() override { + closed_ = true; + return input_ ? input_->Close() : Status{}; + } + + private: + size_t size_; + std::unique_ptr<SeekableInputStream> input_; + MetadataContent content_; + int64_t position_ = 0; + bool closed_ = false; +}; + +class CachedInputFile : public InputFile { + public: + CachedInputFile(std::unique_ptr<InputFile> input, std::shared_ptr<ContentCache> cache, + int64_t size, uint64_t generation, + std::optional<std::string> 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<int64_t>(content->size())), + content_(std::move(content)) {} + std::string_view location() const override { return location_; } + Result<int64_t> Size() const override { return size_; } + Result<std::unique_ptr<SeekableInputStream>> Open() override { + if (content_) { + return std::make_unique<SizedInputStream>(content_); + } + if (!cache_) { + return input_->Open(); + } + bool can_load; + if (auto cached = cache_->FindForHandle(location_, generation_, size_, &can_load)) { + return std::make_unique<SizedInputStream>(std::move(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) { + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_->Open()); + return std::make_unique<SizedInputStream>(std::move(stream), + static_cast<size_t>(size_)); + } + auto loaded = ReadInputFile(*input_, size_, location_); + if (!loaded) { + auto error = std::move(loaded).error(); + if (error.kind != ErrorKind::kIOError) { + return unexpected<Error>(std::move(error)); + } + auto fallback = input_->Open(); + if (!fallback) { + error.message += "; fallback open failed: " + fallback.error().message; + return unexpected<Error>(std::move(error)); + } + return fallback; Review Comment: normal bypass returns a `SizedInputStream`, whereas this fallback path returns the raw stream directly. should we wrap `fallback` in `SizedInputStream` here for consistency? also the fake in `metadata_cache_test.cc` always fails the fallback open, so could we test a successful fallback (bytes, bounds, close, and not populating the cache)? ```diff - return fallback; + return std::make_unique<SizedInputStream>( + std::move(fallback).value(), static_cast<size_t>(size_)); ``` ########## src/iceberg/content_cache_internal.h: ########## @@ -0,0 +1,112 @@ +/* + * 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 <cstddef> +#include <cstdint> +#include <memory> +#include <mutex> +#include <optional> +#include <string> +#include <string_view> +#include <unordered_map> +#include <vector> + +#include "iceberg/file_io.h" +#include "iceberg/util/config.h" + +namespace iceberg::internal { + +class ContentCacheProperties : public ConfigBase<ContentCacheProperties> { + public: + inline static const Entry<bool> kEnabled{"io.manifest.cache-enabled", false}; + inline static const Entry<int64_t> kMaxTotalBytes{"io.manifest.cache.max-total-bytes", + 100 * 1024 * 1024}; + inline static const Entry<int64_t> kMaxContentLength{ + "io.manifest.cache.max-content-length", 8 * 1024 * 1024}; +}; + +// Retain only validated cache settings, independent of the storage credentials. +struct ICEBERG_EXPORT ContentCacheOptions { + bool enabled = ContentCacheProperties::kEnabled.value(); Review Comment: `enabled` defaults to false here, yet `ContentCache::Wrap()` still wraps and caches unconditionally. if `ContentCache` owns this flag, should `Wrap()` return `io_` when `!options_.enabled` (and update tests to enable it)? or if the caller owns it, should we drop `enabled` from `ContentCacheOptions` and document that? ########## src/iceberg/test/metadata_cache_test.cc: ########## @@ -0,0 +1,642 @@ +/* + * 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 <array> +#include <barrier> +#include <cstdint> +#include <memory> +#include <optional> +#include <span> +#include <stdexcept> +#include <string> +#include <string_view> +#include <thread> +#include <utility> +#include <vector> + +#include <gtest/gtest.h> + +#include "iceberg/content_cache_internal.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<internal::ContentCache> MakeCache( + std::shared_ptr<FileIO> storage = std::make_shared<MockFileIO>(), + ContentCacheOptions options = {}) { + return std::make_shared<internal::ContentCache>(std::move(storage), options); +} + +class ScopedGlobalCacheLimit { + public: + explicit ScopedGlobalCacheLimit(int32_t limit) + : previous_(internal::ContentCache::SetGlobalCapacity(limit)) {} + ~ScopedGlobalCacheLimit() { internal::ContentCache::SetGlobalCapacity(previous_); } + + private: + int32_t previous_; +}; + +struct FailingOpenState { + int open_count = 0; + int size_count = 0; + int64_t size = 8; + Error first_error; + Error fallback_error; +}; + +class FailingOpenInputFile : public InputFile { + public: + explicit FailingOpenInputFile(std::shared_ptr<FailingOpenState> state) + : state_(std::move(state)) {} + + std::string_view location() const override { return "manifest.avro"; } + Result<int64_t> Size() const override { + ++state_->size_count; + return state_->size; + } + + Result<std::unique_ptr<SeekableInputStream>> Open() override { + ++state_->open_count; + if (state_->open_count == 1) { + return unexpected<Error>(state_->first_error); + } + return unexpected<Error>(state_->fallback_error); + } + + private: + std::shared_ptr<FailingOpenState> state_; +}; + +class FailingOpenFileIO : public FileIO { + public: + explicit FailingOpenFileIO(std::shared_ptr<FailingOpenState> state) + : state_(std::move(state)) {} + + Result<std::unique_ptr<InputFile>> NewInputFile( + std::string /*file_location*/) override { + return std::make_unique<FailingOpenInputFile>(state_); + } + + private: + std::shared_ptr<FailingOpenState> state_; +}; + +TEST(MetadataCacheTest, IdenticalLocationsOnDifferentBackendsHaveIndependentContents) { + auto first = std::make_shared<MockFileIO>(); + auto second = std::make_shared<MockFileIO>(); + 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<FailingOpenState>(); + state->size = -1; + std::shared_ptr<FileIO> storage = std::make_shared<FailingOpenFileIO>(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>(FailingOpenState{ + .first_error = {.kind = ErrorKind::kNotFound, .message = "missing"}, + .fallback_error = {.kind = ErrorKind::kIOError, .message = "unexpected retry"}, + }); + auto cache = MakeCache(std::make_shared<FailingOpenFileIO>(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>(FailingOpenState{ + .first_error = {.kind = ErrorKind::kIOError, .message = "read-ahead failed"}, + .fallback_error = {.kind = ErrorKind::kIOError, .message = "open failed"}, + }); + auto cache = MakeCache(std::make_shared<FailingOpenFileIO>(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, ParsesJavaCompatibleProperties) { + ContentCacheProperties properties; + properties.Set(ContentCacheProperties::kEnabled, true) + .Set(ContentCacheProperties::kMaxTotalBytes, int64_t{200}) + .Set(ContentCacheProperties::kMaxContentLength, int64_t{50}); + + auto options = ContentCacheOptions::FromProperties(properties.configs()); + + ASSERT_THAT(options, IsOk()); + EXPECT_TRUE(options->enabled); + 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.enabled); + } +} + +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.enabled); + } +} + +TEST(MetadataCacheTest, UsesJavaCompatibleDefaults) { + auto options = ContentCacheOptions::FromProperties( + {{ContentCacheProperties::kEnabled.key(), "true"}}); + + ASSERT_THAT(options, IsOk()); + EXPECT_TRUE(options->enabled); + 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.enabled); +} + +TEST(MetadataCacheTest, PartialBatchDeleteClearsCacheAndPreservesStorageError) { + auto storage = std::make_shared<MockFileIO>(); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + cache->Insert("alias", std::make_shared<const std::vector<std::byte>>(1), 0); + + 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)); + uint64_t generation; + EXPECT_FALSE(cache->Find("alias", &generation)); + EXPECT_EQ(generation, 1); +} + +TEST(MetadataCacheTest, OldInputHandleOpensAfterReplacementIsCached) { + for (const auto* replacement : {"new", "longer"}) { + SCOPED_TRACE(replacement); + auto storage = std::make_shared<MockFileIO>(); + 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<MockFileIO>(); + 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<std::byte, 8> 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<std::unique_ptr<InputFile>> 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<IgnoredHintFileIO>(); + 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<bool>(cache->Find("manifest.avro")), limit == 8); + EXPECT_THAT(adapter->ReadFile("manifest.avro", std::nullopt), + HasValue(::testing::Eq("manifest"))); + } + EXPECT_EQ(storage->hinted_calls, 2); +} + +TEST(MetadataCacheTest, ShortHintOnFirstOpenDoesNotPublishAPrefix) { + class CountingFileIO : public MockFileIO { + public: + using MockFileIO::NewInputFile; + Result<std::unique_ptr<InputFile>> NewInputFile(std::string location) override { + ++unhinted_calls; + return MockFileIO::NewInputFile(std::move(location)); + } + int unhinted_calls = 0; + }; + auto storage = std::make_shared<CountingFileIO>(); + 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<std::byte, 8> 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<FailingOpenState>(); + state->size = size; + auto cache = MakeCache(std::make_shared<FailingOpenFileIO>(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<StorageCredential>& credentials) override { + credentials_ = credentials; + return {}; + } + std::vector<StorageCredential> credentials() const override { return credentials_; } + + private: + std::vector<StorageCredential> credentials_; + }; + auto storage = std::make_shared<CredentialedFileIO>(); + 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<MockFileIO>(); + 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"))); + ASSERT_THAT(inner->WriteFile("manifest", "new"), IsOk()); + EXPECT_THAT(outer->ReadFile("manifest", std::nullopt), HasValue(::testing::Eq("new"))); +} + +TEST(MetadataCacheTest, NestedCacheKeepsWarmFilesAcrossFreshWrites) { + auto storage = std::make_shared<MockFileIO>(); + storage->AddFile("warm", "manifest"); + auto inner = MakeCache(storage, ContentCacheOptions{.max_content_length = 1})->Wrap(); + auto cache = MakeCache(inner); + auto outer = cache->Wrap(); + ASSERT_THAT(outer->ReadFile("warm", std::nullopt), HasValue(::testing::Eq("manifest"))); + auto warm = cache->Find("warm"); + ASSERT_TRUE(warm); + + ICEBERG_UNWRAP_OR_FAIL(auto file, inner->NewOutputFile("fresh")); + ICEBERG_UNWRAP_OR_FAIL(auto writer, file->CreateOrOverwrite()); + EXPECT_EQ(cache->Find("warm"), warm); + auto bytes = std::as_bytes(std::span("ab", 2)); + ASSERT_THAT(writer->Write(bytes), IsOk()); + ICEBERG_UNWRAP_OR_FAIL(auto partial, outer->NewInputFile("fresh")); + ASSERT_THAT(outer->ReadFile("fresh", std::nullopt), HasValue(::testing::Eq("ab"))); + EXPECT_FALSE(cache->Find("fresh")); + ASSERT_THAT(writer->Write(bytes), IsOk()); + ASSERT_THAT(writer->Close(), IsOk()); + + ASSERT_THAT(partial->Open(), IsOk()); + EXPECT_FALSE(cache->Find("fresh")); + EXPECT_EQ(cache->Find("warm"), warm); + EXPECT_THAT(outer->ReadFile("fresh", std::nullopt), HasValue(::testing::Eq("abab"))); +} + +TEST(MetadataCacheTest, ExplicitClearOnlyAffectsTheTableAndItsOuterAdapters) { + auto storage = std::make_shared<MockFileIO>(); + 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"))); + } + table->Clear(); + 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<const std::vector<std::byte>>(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<MockFileIO>(), + ContentCacheOptions{.max_total_bytes = 4}); + auto bytes = std::make_shared<const std::vector<std::byte>>(2); + cache->Insert("a", bytes, 0); + cache->Insert("b", bytes, 0); + EXPECT_FALSE(cache->FindForHandle("a", 0, 1)); + cache->Insert("a", std::make_shared<const std::vector<std::byte>>(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<const std::vector<std::byte>>(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<MockFileIO>(); + auto cache = MakeCache(storage); + auto adapter = cache->Wrap(); + auto warm = std::make_shared<const std::vector<std::byte>>(8); + cache->Insert("warm", warm, 0); + 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()); + ASSERT_THAT(writer->Close(), IsOk()); + ASSERT_THAT(partial->Open(), IsOk()); + EXPECT_FALSE(cache->Find("fresh")); + EXPECT_EQ(cache->Find("warm"), warm); Review Comment: this checks that `ReadFile` returns `"abab"`, but not that `"fresh"` actually gets cached afterward—if `active_writes` got stuck, this would still pass from storage. could we also assert `cache->Find("fresh")` (and that another read skips storage)? also, could we test failed create, failed write, failed close, and destroying a writer without closing through the wrapper? ########## src/iceberg/content_cache.cc: ########## @@ -0,0 +1,648 @@ +/* + * 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 <algorithm> +#include <atomic> +#include <cstring> +#include <format> +#include <list> +#include <mutex> +#include <shared_mutex> +#include <stdexcept> +#include <utility> + +#include "iceberg/content_cache_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<std::string, MetadataContent, StringHash, StringEqual>; + +// 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<std::weak_ptr<ContentCacheRegistration>>; + Entries::iterator position; + std::shared_ptr<CachedFiles> files; + // Accessed under the per-table mutex. A miss needs no registry lock. + std::weak_ptr<CachedFiles> last_files; +}; + +// Adapters over one storage FileIO share mutation state. Each table still owns +// its own cached bytes. The registry mutex protects the number of bound caches. +struct ContentCacheStorage { + explicit ContentCacheStorage(FileIO* file_io) : io(file_io) {} + FileIO* const io; + size_t caches = 0; + std::shared_mutex mutex; + size_t active_writes = 0; + uint64_t finished_writes = 0; + uint64_t invalidations = 0; + std::atomic<bool> ever_cached = false; +}; + +class ContentCacheRegistry { + public: + explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {} + + ContentCacheStorage& Bind(FileIO* io) { + if (!io) { + throw std::invalid_argument("Content cache requires a storage FileIO"); + } + std::lock_guard lock(mutex_); + auto& storage = storage_.try_emplace(io, io).first->second; + ++storage.caches; + return storage; + } + + void Unbind(ContentCacheStorage& storage) { + std::lock_guard lock(mutex_); + if (--storage.caches == 0) { + storage_.erase(storage.io); + } + } + + bool IsActive(const ContentCacheRegistration& entry, + const std::shared_ptr<CachedFiles>& 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<CachedFiles> GetOrCreate( + const std::shared_ptr<ContentCacheRegistration>& entry, size_t max_total_bytes) { + std::shared_ptr<CachedFiles> evicted; + std::lock_guard lock(mutex_); + if (entry->files) { + entries_.splice(entries_.begin(), entries_, entry->position); + } else { + auto files = std::make_shared<CachedFiles>(static_cast<int64_t>(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; + } + + void Erase(ContentCacheRegistration& entry) { + std::shared_ptr<CachedFiles> evicted; + std::lock_guard lock(mutex_); + if (entry.files) { + entries_.erase(entry.position); + evicted = std::move(entry.files); + } + } + + int32_t SetCapacity(int32_t capacity) { + if (capacity <= 0) { + throw std::invalid_argument( + std::format("Global manifest cache limit must be positive, got {}", capacity)); + } + std::vector<std::shared_ptr<CachedFiles>> evicted; + std::lock_guard lock(mutex_); + if (std::cmp_greater(entries_.size(), capacity)) { + evicted.reserve(entries_.size() - static_cast<size_t>(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<CachedFiles> 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<const FileIO*, ContentCacheStorage> storage_; +}; + +namespace { + +// Match Iceberg Java's default for iceberg.io.manifest.cache.fileio-max. +constexpr int32_t kDefaultMaxTableCaches = 8; + +std::shared_ptr<ContentCacheRegistry> GlobalContentCacheRegistry() { + // Handles keep the registry alive even when destroyed during static teardown. + static auto registry = std::make_shared<ContentCacheRegistry>(kDefaultMaxTableCaches); + return registry; +} + +Result<std::vector<std::byte>> ReadInputFile(InputFile& input_file, int64_t read_size, + std::string_view file_location) { + if (!std::in_range<size_t>(read_size)) { + return Invalid("File size {} for {} does not fit in size_t", read_size, + file_location); + } + + std::vector<std::byte> content(static_cast<size_t>(read_size)); + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open()); + auto read_status = stream->ReadFully(/*position=*/0, content); + ICEBERG_RETURN_UNEXPECTED( + FinishWithCloseStatus(std::move(read_status), stream->Close())); + return content; +} + +class SizedInputStream : public SeekableInputStream { + public: + explicit SizedInputStream(MetadataContent content) + : size_(content->size()), content_(std::move(content)) {} + SizedInputStream(std::unique_ptr<SeekableInputStream> input, size_t size) + : size_(size), input_(std::move(input)) {} + + Result<int64_t> Position() const override { + return input_ ? input_->Position() : Result<int64_t>(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(std::cmp_less_equal(position, size_), + "Position {} exceeds file size {}", position, size_); + if (input_) { + return input_->Seek(position); + } + position_ = position; + return {}; + } + + Result<int64_t> Read(std::span<std::byte> out) override { + ICEBERG_PRECHECK(!closed_, "Input stream is closed"); + if (input_) { + ICEBERG_ASSIGN_OR_RAISE(auto current, input_->Position()); + ICEBERG_PRECHECK(current >= 0 && std::cmp_less_equal(current, size_), + "Invalid stream position {}", current); + return input_->Read( + out.first(std::min(out.size(), size_ - static_cast<size_t>(current)))); + } + auto position = static_cast<size_t>(position_); + auto bytes_to_read = std::min(out.size(), size_ - position); + if (bytes_to_read > 0) { + std::memcpy(out.data(), content_->data() + position, bytes_to_read); + position_ += static_cast<int64_t>(bytes_to_read); + } + return static_cast<int64_t>(bytes_to_read); + } + + Status ReadFully(int64_t position, std::span<std::byte> out) override { + ICEBERG_PRECHECK(!closed_, "Input stream is closed"); + ICEBERG_PRECHECK(position >= 0, "Position must not be negative: {}", position); + ICEBERG_PRECHECK(std::cmp_less_equal(position, size_), + "Position {} exceeds file size {}", position, size_); + auto offset = static_cast<size_t>(position); + ICEBERG_PRECHECK(out.size() <= size_ - offset, + "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() + offset, out.size()); + } + return {}; + } + + Status Close() override { + closed_ = true; + return input_ ? input_->Close() : Status{}; + } + + private: + size_t size_; + std::unique_ptr<SeekableInputStream> input_; + MetadataContent content_; + int64_t position_ = 0; + bool closed_ = false; +}; + +class CachedInputFile : public InputFile { + public: + CachedInputFile(std::unique_ptr<InputFile> input, std::shared_ptr<ContentCache> cache, + int64_t size, uint64_t generation, + std::optional<std::string> 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<int64_t>(content->size())), + content_(std::move(content)) {} + std::string_view location() const override { return location_; } + Result<int64_t> Size() const override { return size_; } + Result<std::unique_ptr<SeekableInputStream>> Open() override { + if (content_) { + return std::make_unique<SizedInputStream>(content_); + } + if (!cache_) { + return input_->Open(); + } + bool can_load; + if (auto cached = cache_->FindForHandle(location_, generation_, size_, &can_load)) { + return std::make_unique<SizedInputStream>(std::move(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) { + ICEBERG_ASSIGN_OR_RAISE(auto stream, input_->Open()); + return std::make_unique<SizedInputStream>(std::move(stream), + static_cast<size_t>(size_)); + } + auto loaded = ReadInputFile(*input_, size_, location_); + if (!loaded) { + auto error = std::move(loaded).error(); + if (error.kind != ErrorKind::kIOError) { + return unexpected<Error>(std::move(error)); + } + auto fallback = input_->Open(); + if (!fallback) { + error.message += "; fallback open failed: " + fallback.error().message; + return unexpected<Error>(std::move(error)); + } + return fallback; + } + auto content = + std::make_shared<const std::vector<std::byte>>(std::move(loaded).value()); + content = cache_->Insert(location_, std::move(content), generation_); + return std::make_unique<SizedInputStream>(std::move(content)); + } + + private: + std::unique_ptr<InputFile> input_; + std::shared_ptr<ContentCache> cache_; + std::string location_; + int64_t size_; + uint64_t generation_ = 0; + std::optional<std::string> verify_location_; + std::once_flag verify_once_; + bool complete_ = false; + MetadataContent content_; +}; + +} // namespace + +// Clear once after each cleanup, including partially successful batch deletes. +class ContentCache::ManifestFileIO final : public FileIO { + public: + explicit ManifestFileIO(std::shared_ptr<ContentCache> cache) + : cache_(std::move(cache)) {} + static const ContentCache* GetCache(FileIO* io) { + const auto* adapter = dynamic_cast<const ManifestFileIO*>(io); + return adapter ? adapter->cache_.get() : nullptr; + } + Result<std::unique_ptr<InputFile>> NewInputFile(std::string location) override { + return cache_->NewInputFile(std::move(location)); + } + Result<std::unique_ptr<InputFile>> NewInputFile(std::string location, + size_t length) override { + return cache_->NewInputFile(std::move(location), length); + } + Result<std::string> ReadFile(const std::string& location, + std::optional<size_t> length) override { + // A requested byte count can cover only a prefix of an immutable file. + if (length) { + return cache_->io_->ReadFile(location, length); + } + return FileIO::ReadFile(location, std::nullopt); + } + Result<std::unique_ptr<OutputFile>> 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<CachedOutputFile>(std::move(output), cache_); + } + Status DeleteFile(const std::string& location) override { + ClearAfterDelete cleanup{*cache_}; + return cache_->storage_.io->DeleteFile(location); + } + Status DeleteFiles(const std::vector<std::string>& locations) override { + if (locations.empty()) { + return cache_->storage_.io->DeleteFiles(locations); + } + ClearAfterDelete cleanup{*cache_}; + return cache_->storage_.io->DeleteFiles(locations); + } + const std::unordered_map<std::string, std::string>& properties() const override { + return cache_->io_->properties(); + } + + private: + // A reader overlapping any write can see partial bytes through another spelling + // of the path. Existing immutable entries remain usable during create-only writes. + class WritingStream : public PositionOutputStream { + public: + explicit WritingStream(std::shared_ptr<ContentCache> cache) + : cache_(std::move(cache)) { + std::lock_guard lock(cache_->storage_.mutex); + ++cache_->storage_.active_writes; + may_have_cached_files_ = + cache_->storage_.ever_cached.load(std::memory_order_relaxed); + } + + ~WritingStream() override { + stream_.reset(); + Finish(); + } + + Status Open(OutputFile& output, bool overwrite) { + if (overwrite && !may_have_cached_files_) { + ICEBERG_ASSIGN_OR_RAISE(stream_, output.CreateOrOverwrite()); + return {}; + } + auto created = output.Create(); + if (!created && overwrite) { + // The path may already exist under a cached alias. Clear before storage can + // truncate it, including when opening the overwrite stream itself fails. + cache_->InvalidateStorage(); + created = output.CreateOrOverwrite(); + } + ICEBERG_ASSIGN_OR_RAISE(stream_, std::move(created)); + return {}; + } + + Result<int64_t> Position() const override { return stream_->Position(); } + Result<int64_t> StoredLength() const override { return stream_->StoredLength(); } + Status Write(std::span<const std::byte> data) override { + return stream_->Write(data); + } + Status Flush() override { return stream_->Flush(); } + Status Close() override { + auto status = stream_->Close(); + if (status) { + Finish(); + } + return status; + } + + private: + void Finish() { + if (auto cache = std::move(cache_)) { + std::lock_guard lock(cache->storage_.mutex); + --cache->storage_.active_writes; + ++cache->storage_.finished_writes; + } + } + std::shared_ptr<ContentCache> cache_; + std::unique_ptr<PositionOutputStream> stream_; + bool may_have_cached_files_; + }; + + class CachedOutputFile : public OutputFile { + public: + CachedOutputFile(std::unique_ptr<OutputFile> output, + std::shared_ptr<ContentCache> cache) + : output_(std::move(output)), cache_(std::move(cache)) {} + std::string_view location() const override { return output_->location(); } + Result<std::unique_ptr<PositionOutputStream>> Create() override { + return Open(false); + } + Result<std::unique_ptr<PositionOutputStream>> CreateOrOverwrite() override { + return Open(true); + } + + private: + Result<std::unique_ptr<PositionOutputStream>> Open(bool overwrite) { + auto stream = std::make_unique<WritingStream>(cache_); + ICEBERG_RETURN_UNEXPECTED(stream->Open(*output_, overwrite)); + return stream; + } + std::unique_ptr<OutputFile> output_; + std::shared_ptr<ContentCache> cache_; + }; + + struct ClearAfterDelete { + ContentCache& cache; + ~ClearAfterDelete() { cache.InvalidateStorage(); } Review Comment: `ClearAfterDelete` only invalidates in the destructor after `DeleteFile` returns. what if storage deletes the file and another adapter recreates it at the same path before `DeleteFile` finishes? readers could still get the old cached bytes in that window. could we track it as an active write and invalidate up front too, plus add a test for that overlap? ```diff struct ClearAfterDelete { + explicit ClearAfterDelete(ContentCache& owner) : cache(owner) { + std::lock_guard lock(cache.storage_.mutex); + ++cache.storage_.active_writes; + ++cache.storage_.invalidations; + cache.SyncGenerationLocked(); + } + ContentCache& cache; - ~ClearAfterDelete() { cache.InvalidateStorage(); } + ~ClearAfterDelete() { + std::lock_guard lock(cache.storage_.mutex); + --cache.storage_.active_writes; + ++cache.storage_.invalidations; + cache.SyncGenerationLocked(); + } }; ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
