wgtmac commented on code in PR #1174:
URL: https://github.com/apache/iceberg-cpp/pull/1174#discussion_r4709296412


##########
src/iceberg/content_cache.cc:
##########
@@ -0,0 +1,439 @@
+/*
+ * 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 <cstring>
+#include <limits>
+#include <list>
+#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 {
+
+struct CachedFile {
+  MetadataContent content;
+  std::optional<std::string> storage_path;
+};
+
+struct MetadataContentWeigher {
+  int64_t operator()(const std::string&, const CachedFile& file) const {
+    return static_cast<int64_t>(file.content->size());
+  }
+};
+
+using CachedFiles =
+    LruCache<std::string, CachedFile, MetadataContentWeigher, StringHash, 
StringEqual>;
+
+// Owned by the table's cache handle. Only the registry accesses these fields 
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;
+};
+
+class ContentCacheRegistry {
+ public:
+  explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {}
+
+  // Pin the files for the calling operation. Their entries are protected by 
the
+  // per-table mutex, so accessing bytes never requires holding the registry 
lock.
+  std::shared_ptr<CachedFiles> Find(const ContentCacheRegistration& entry,
+                                    bool touch = true) {
+    std::lock_guard lock(mutex_);
+    if (touch && entry.files) {
+      entries_.splice(entries_.begin(), entries_, entry.position);
+    }
+    return entry.files;
+  }
+
+  std::shared_ptr<CachedFiles> GetOrCreate(
+      const std::shared_ptr<ContentCacheRegistration>& entry, size_t 
max_total_bytes) {
+    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);
+      TrimToCapacity();
+    }
+    return entry->files;
+  }
+
+  void Erase(ContentCacheRegistration& entry) {
+    std::lock_guard lock(mutex_);
+    if (entry.files) {
+      entries_.erase(entry.position);
+      entry.files.reset();
+    }
+  }
+
+  int32_t SetCapacity(int32_t capacity) {
+    ICEBERG_DCHECK(capacity > 0, "Global manifest cache limit must be 
positive");
+    std::lock_guard lock(mutex_);
+    const auto previous = std::exchange(capacity_, capacity);
+    TrimToCapacity();
+    return previous;
+  }
+
+ private:
+  void TrimToCapacity() {
+    while (std::cmp_greater(entries_.size(), capacity_)) {
+      if (auto entry = entries_.back().lock()) {
+        entry->files.reset();
+      }
+      entries_.pop_back();
+    }
+  }
+
+  std::mutex mutex_;
+  int32_t capacity_;
+  ContentCacheRegistration::Entries entries_;
+};
+
+namespace {
+
+std::optional<std::string_view> StoragePath(const InputFile& input) {
+  if (const auto* file = dynamic_cast<const 
InputFileWithStoragePath*>(&input)) {
+    return file->storage_path();
+  }
+  return std::nullopt;
+}
+
+std::shared_ptr<ContentCacheRegistry> GlobalContentCacheRegistry() {
+  // Handles keep the registry alive even when destroyed during static 
teardown.
+  static auto registry = std::make_shared<ContentCacheRegistry>(8);
+  return registry;
+}
+
+Result<std::vector<std::byte>> ReadInputFile(InputFile& input_file, int64_t 
read_size,
+                                             std::string_view file_location) {
+  if (read_size < 0) {
+    return Invalid("Invalid negative file size {} for {}", read_size, 
file_location);
+  }
+  if (std::cmp_greater(read_size, std::numeric_limits<size_t>::max())) {
+    return Invalid("File size {} exceeds size_t max for {}", read_size, 
file_location);
+  }
+
+  auto size = static_cast<size_t>(read_size);
+  std::vector<std::byte> content(size);
+  ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open());
+  Status read_status = {};
+  if (size > 0) {
+    read_status = stream->ReadFully(/*position=*/0, content);
+  }
+  ICEBERG_RETURN_UNEXPECTED(
+      FinishWithCloseStatus(std::move(read_status), stream->Close()));
+  return content;
+}
+
+class CachedSeekableInputStream : public SeekableInputStream {
+ public:
+  explicit CachedSeekableInputStream(MetadataContent content)
+      : content_(std::move(content)) {}
+
+  Result<int64_t> Position() const override { return 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, content_->size()),
+                     "Position {} exceeds file size {}", position, 
content_->size());
+    position_ = position;
+    return {};
+  }
+
+  Result<int64_t> Read(std::span<std::byte> out) override {
+    ICEBERG_PRECHECK(!closed_, "Input stream is closed");
+    auto position = static_cast<size_t>(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<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, content_->size()),
+                     "Position {} exceeds file size {}", position, 
content_->size());
+    auto offset = static_cast<size_t>(position);
+    ICEBERG_PRECHECK(out.size() <= content_->size() - offset,
+                     "Read out of bounds: offset {} + length {} exceeds file 
size {}",
+                     position, out.size(), content_->size());
+    if (!out.empty()) {
+      std::memcpy(out.data(), content_->data() + offset, out.size());
+    }
+    return {};
+  }
+
+  Status Close() override {
+    closed_ = true;
+    return {};
+  }
+
+ private:
+  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)
+      : input_(std::move(input)),
+        cache_(std::move(cache)),
+        location_(input_->location()),
+        size_(size),
+        generation_(generation) {}
+  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<CachedSeekableInputStream>(content_);
+    }
+    if (auto cached = cache_->Find(location_)) {

Review Comment:
   This handle fixes Size() at construction, while Open() can use a later cache 
entry. After invalidation and a warm read of a differently sized replacement, 
this lookup can return the new bytes with the old size. Please require a 
matching generation and length on the second lookup and cover opening the old 
handle after the replacement is warm.



##########
src/iceberg/util/cache_internal.h:
##########
@@ -76,44 +109,103 @@ class LruCache {
     return &list_it->value;
   }
 
+  // Return whether a cached entry was removed.
+  template <typename K>
+  bool Erase(const K& key) {
+    const auto it = map_.find(key);
+    if (it == map_.end()) {
+      return false;
+    }
+    total_weight_ -= it->second->weight;
+    items_.erase(it->second);
+    map_.erase(it);
+    return true;
+  }
+
+  // Remove matching entries without changing the eviction order of the 
survivors.
+  template <typename Predicate>
+  void EraseIf(Predicate matches) {
+    for (auto it = map_.begin(); it != map_.end();) {
+      const auto item = it->second;
+      if (matches(std::as_const(item->value))) {
+        total_weight_ -= item->weight;
+        items_.erase(item);
+        it = map_.erase(it);
+      } else {
+        ++it;
+      }
+    }
+  }
+
+  // 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.
+  // Use Replace to change a cached value. A successful replacement 
invalidates the
+  // previous value pointer. If weighing throws, the cache retains its 
previous state.
   template <typename K, typename V>
-  std::pair<bool, Value*> Replace(K&& key, V&& value) {
-    // Try to insert temporary iterator
-    auto [it, inserted] = map_.emplace(std::forward<K>(key), ListIt{});
-    if (inserted) {
-      // Inserted => push item at front of the list, and update iterator
-      items_.emplace_front(&it->first, std::forward<V>(value));
-      it->second = items_.begin();
-      // Did we exceed the cache capacity?  If so, remove least recently used 
item
-      if (static_cast<int32_t>(items_.size()) > capacity_) {
-        const bool erased = map_.erase(*items_.back().key);
-        ICEBERG_DCHECK(erased, "Failed to erase least recently used cache 
item");
-        static_cast<void>(erased);
-        items_.pop_back();
+  std::pair<bool, const Value*> Replace(K&& key, V&& value) {
+    List candidate;
+    auto& item = candidate.emplace_front(nullptr, std::forward<V>(value));
+    auto [it, inserted] = map_.try_emplace(std::forward<K>(key));
+    item.key = &it->first;
+    try {

Review Comment:
   Both callers already know the weight: one per memoized entry or the file 
size in bytes. Could `Replace()` take the weight directly, defaulting to `1`, 
so we can remove the throwing callback and rollback path?



##########
src/iceberg/util/cache_internal.h:
##########
@@ -54,17 +72,32 @@ class LruCache {
   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<int32_t>(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.
+  void Resize(int64_t max_weight) {
+    ICEBERG_DCHECK(max_weight >= 0, "Cache maximum weight must be 
non-negative");

Review Comment:
   A negative limit can drive eviction past the last entry in release builds 
because this `DCHECK` is compiled out. Can we validate the limit at the 
configuration boundary, or return `InvalidArgument` from `Resize()` if it 
accepts unchecked input?



##########
src/iceberg/content_cache.cc:
##########
@@ -0,0 +1,439 @@
+/*
+ * 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 <cstring>
+#include <limits>
+#include <list>
+#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 {
+
+struct CachedFile {
+  MetadataContent content;
+  std::optional<std::string> storage_path;
+};
+
+struct MetadataContentWeigher {
+  int64_t operator()(const std::string&, const CachedFile& file) const {
+    return static_cast<int64_t>(file.content->size());
+  }
+};
+
+using CachedFiles =
+    LruCache<std::string, CachedFile, MetadataContentWeigher, StringHash, 
StringEqual>;
+
+// Owned by the table's cache handle. Only the registry accesses these fields 
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;
+};
+
+class ContentCacheRegistry {
+ public:
+  explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {}
+
+  // Pin the files for the calling operation. Their entries are protected by 
the
+  // per-table mutex, so accessing bytes never requires holding the registry 
lock.
+  std::shared_ptr<CachedFiles> Find(const ContentCacheRegistration& entry,
+                                    bool touch = true) {
+    std::lock_guard lock(mutex_);
+    if (touch && entry.files) {
+      entries_.splice(entries_.begin(), entries_, entry.position);
+    }
+    return entry.files;
+  }
+
+  std::shared_ptr<CachedFiles> GetOrCreate(
+      const std::shared_ptr<ContentCacheRegistration>& entry, size_t 
max_total_bytes) {
+    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);
+      TrimToCapacity();
+    }
+    return entry->files;
+  }
+
+  void Erase(ContentCacheRegistration& entry) {
+    std::lock_guard lock(mutex_);
+    if (entry.files) {
+      entries_.erase(entry.position);
+      entry.files.reset();
+    }
+  }
+
+  int32_t SetCapacity(int32_t capacity) {
+    ICEBERG_DCHECK(capacity > 0, "Global manifest cache limit must be 
positive");
+    std::lock_guard lock(mutex_);
+    const auto previous = std::exchange(capacity_, capacity);
+    TrimToCapacity();
+    return previous;
+  }
+
+ private:
+  void TrimToCapacity() {
+    while (std::cmp_greater(entries_.size(), capacity_)) {
+      if (auto entry = entries_.back().lock()) {
+        entry->files.reset();
+      }
+      entries_.pop_back();
+    }
+  }
+
+  std::mutex mutex_;
+  int32_t capacity_;
+  ContentCacheRegistration::Entries entries_;
+};
+
+namespace {
+
+std::optional<std::string_view> StoragePath(const InputFile& input) {
+  if (const auto* file = dynamic_cast<const 
InputFileWithStoragePath*>(&input)) {
+    return file->storage_path();
+  }
+  return std::nullopt;
+}
+
+std::shared_ptr<ContentCacheRegistry> GlobalContentCacheRegistry() {
+  // Handles keep the registry alive even when destroyed during static 
teardown.
+  static auto registry = std::make_shared<ContentCacheRegistry>(8);
+  return registry;
+}
+
+Result<std::vector<std::byte>> ReadInputFile(InputFile& input_file, int64_t 
read_size,
+                                             std::string_view file_location) {
+  if (read_size < 0) {
+    return Invalid("Invalid negative file size {} for {}", read_size, 
file_location);
+  }
+  if (std::cmp_greater(read_size, std::numeric_limits<size_t>::max())) {
+    return Invalid("File size {} exceeds size_t max for {}", read_size, 
file_location);
+  }
+
+  auto size = static_cast<size_t>(read_size);
+  std::vector<std::byte> content(size);
+  ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open());
+  Status read_status = {};
+  if (size > 0) {
+    read_status = stream->ReadFully(/*position=*/0, content);
+  }
+  ICEBERG_RETURN_UNEXPECTED(
+      FinishWithCloseStatus(std::move(read_status), stream->Close()));
+  return content;
+}
+
+class CachedSeekableInputStream : public SeekableInputStream {
+ public:
+  explicit CachedSeekableInputStream(MetadataContent content)
+      : content_(std::move(content)) {}
+
+  Result<int64_t> Position() const override { return 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, content_->size()),
+                     "Position {} exceeds file size {}", position, 
content_->size());
+    position_ = position;
+    return {};
+  }
+
+  Result<int64_t> Read(std::span<std::byte> out) override {
+    ICEBERG_PRECHECK(!closed_, "Input stream is closed");
+    auto position = static_cast<size_t>(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<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, content_->size()),
+                     "Position {} exceeds file size {}", position, 
content_->size());
+    auto offset = static_cast<size_t>(position);
+    ICEBERG_PRECHECK(out.size() <= content_->size() - offset,
+                     "Read out of bounds: offset {} + length {} exceeds file 
size {}",
+                     position, out.size(), content_->size());
+    if (!out.empty()) {
+      std::memcpy(out.data(), content_->data() + offset, out.size());
+    }
+    return {};
+  }
+
+  Status Close() override {
+    closed_ = true;
+    return {};
+  }
+
+ private:
+  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)
+      : input_(std::move(input)),
+        cache_(std::move(cache)),
+        location_(input_->location()),
+        size_(size),
+        generation_(generation) {}
+  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<CachedSeekableInputStream>(content_);
+    }
+    if (auto cached = cache_->Find(location_)) {
+      return std::make_unique<CachedSeekableInputStream>(std::move(cached));
+    }
+    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());
+    cache_->Insert(location_, content, generation_, StoragePath(*input_));
+    return std::make_unique<CachedSeekableInputStream>(std::move(content));
+  }
+
+ private:
+  std::unique_ptr<InputFile> input_;
+  std::shared_ptr<ContentCache> cache_;
+  std::string location_;
+  int64_t size_;
+  uint64_t generation_ = 0;
+  MetadataContent content_;
+};
+
+// Manifest maintenance creates outputs on storage. Cleanup deletes through 
storage
+// and invalidates the cache after each delete attempt.
+class ManifestFileIO : public FileIO {
+ public:
+  ManifestFileIO(std::shared_ptr<FileIO> io, std::shared_ptr<ContentCache> 
cache)
+      : io_(std::move(io)), cache_(std::move(cache)) {}
+  Result<std::unique_ptr<InputFile>> NewInputFile(std::string location) 
override {
+    return cache_->NewInputFile(io_, std::move(location));
+  }
+  Result<std::unique_ptr<InputFile>> NewInputFile(std::string location,
+                                                  size_t length) override {
+    return cache_->NewInputFile(io_, 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 io_->ReadFile(location, length);
+    }
+    return FileIO::ReadFile(location, std::nullopt);
+  }
+  Result<std::unique_ptr<OutputFile>> NewOutputFile(std::string location) 
override {
+    return io_->NewOutputFile(std::move(location));
+  }
+  Status DeleteFile(const std::string& /*location*/) override {
+    return NotSupported("Delete files through the storage FileIO");
+  }
+  Status DeleteFiles(const std::vector<std::string>& /*locations*/) override {
+    return NotSupported("Delete files through the storage FileIO");
+  }
+  const std::unordered_map<std::string, std::string>& properties() const 
override {
+    return io_->properties();
+  }
+
+ private:
+  std::shared_ptr<FileIO> io_;
+  std::shared_ptr<ContentCache> cache_;
+};
+
+}  // namespace
+
+Result<ContentCacheOptions> ContentCacheOptions::FromProperties(
+    const std::unordered_map<std::string, std::string>& properties) {
+  ContentCacheOptions options;
+  const auto& enabled = ContentCacheProperties::kEnabled;
+  options.enabled =
+      PropertyUtil::PropertyAsBoolean(properties, enabled.key(), 
enabled.value());
+  if (!options.enabled) {
+    return options;
+  }
+  const auto read_limit = [&properties](const auto& entry) -> Result<size_t> {
+    ICEBERG_ASSIGN_OR_RAISE(auto limit, PropertyUtil::PropertyAsInt64(
+                                            properties, entry.key(), 
entry.value()));
+    ICEBERG_PRECHECK(limit > 0 && std::in_range<size_t>(limit),
+                     "Property '{}' must be positive and fit in size_t: {}", 
entry.key(),
+                     limit);
+    return static_cast<size_t>(limit);
+  };
+  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(ContentCacheOptions options)
+    : options_(options),
+      registry_(GlobalContentCacheRegistry()),
+      registration_(std::make_shared<ContentCacheRegistration>()) {}
+
+ContentCache::~ContentCache() { registry_->Erase(*registration_); }
+
+int32_t ContentCache::SetGlobalCapacity(int32_t max_caches) {
+  return GlobalContentCacheRegistry()->SetCapacity(max_caches);
+}
+
+std::shared_ptr<FileIO> ContentCache::Wrap(std::shared_ptr<FileIO> io) {
+  return std::make_shared<ManifestFileIO>(std::move(io), shared_from_this());
+}
+
+MetadataContent ContentCache::Find(std::string_view location, uint64_t* 
generation) {
+  std::lock_guard lock(mutex_);
+  if (generation) *generation = generation_;
+  auto files = registry_->Find(*registration_);
+  const auto* file = files ? files->Find(location) : nullptr;
+  return file ? file->content : nullptr;
+}
+
+void ContentCache::Insert(std::string_view location, MetadataContent content,
+                          uint64_t generation,
+                          std::optional<std::string_view> storage_path) {
+  // Empty/corrupt metadata must not accumulate unbounded zero-weight entries.
+  if (content->empty() || content->size() > options_.max_content_length ||
+      content->size() > options_.max_total_bytes) {
+    return;
+  }
+  std::lock_guard lock(mutex_);
+  if (generation == generation_) {
+    registry_->GetOrCreate(registration_, options_.max_total_bytes)
+        ->Replace(std::string(location),
+                  CachedFile{.content = std::move(content),
+                             .storage_path = 
std::optional<std::string>(storage_path)});
+  }
+}
+
+void ContentCache::Invalidate(FileIO& storage, std::string_view location) {
+  {
+    std::lock_guard lock(mutex_);
+    auto files = registry_->Find(*registration_, /*touch=*/false);
+    if (!files) {
+      ++generation_;
+      return;
+    }
+  }
+
+  // A URI may have several cached spellings, even when the deleted spelling
+  // itself was cached. Ask storage for the path it actually uses.
+  std::optional<std::string> path;
+  try {
+    if (auto input = storage.NewInputFile(std::string(location)); input && 
*input) {
+      path = StoragePath(**input);
+    }
+  } catch (...) {
+    // Failure to resolve an alias must not turn a completed delete into a 
failure.
+    Clear();
+    return;
+  }
+  if (!path) {
+    // The public InputFile location may simply echo the requested spelling.
+    Clear();
+    return;
+  }
+
+  std::lock_guard lock(mutex_);
+  ++generation_;
+  if (auto files = registry_->Find(*registration_, /*touch=*/false)) {
+    files->EraseIf([&](const CachedFile& file) {
+      return !file.storage_path || *file.storage_path == *path;
+    });
+    if (files->size() == 0) registry_->Erase(*registration_);
+  }
+}
+
+void ContentCache::Clear() {
+  std::lock_guard lock(mutex_);
+  registry_->Erase(*registration_);
+  ++generation_;
+}
+
+Result<std::unique_ptr<InputFile>> ContentCache::NewInputFile(
+    const std::shared_ptr<FileIO>& io, std::string location,
+    std::optional<size_t> length) {
+  if (length && std::cmp_greater(*length, 
std::numeric_limits<int64_t>::max())) {
+    return InvalidArgument("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<CachedInputFile>(std::move(location), 
std::move(content));
+  }
+  std::unique_ptr<InputFile> input;
+  if (length) {
+    ICEBERG_ASSIGN_OR_RAISE(input, io->NewInputFile(location, *length));
+  } else {
+    ICEBERG_ASSIGN_OR_RAISE(input, io->NewInputFile(location));
+  }
+  if (auto content = Find(input->location())) {
+    return std::make_unique<CachedInputFile>(std::string(input->location()),
+                                             std::move(content));
+  }
+  int64_t size;
+  if (length) {
+    size = static_cast<int64_t>(*length);

Review Comment:
   FileIO can ignore this length hint. A short hint then stores a prefix as the 
whole file, so a later unhinted read returns truncated content. Please pass the 
hint to the backend and use the returned InputFile's Size() for admission and 
read-ahead.



##########
src/iceberg/content_cache.cc:
##########
@@ -0,0 +1,439 @@
+/*
+ * 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 <cstring>
+#include <limits>
+#include <list>
+#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 {
+
+struct CachedFile {
+  MetadataContent content;
+  std::optional<std::string> storage_path;
+};
+
+struct MetadataContentWeigher {
+  int64_t operator()(const std::string&, const CachedFile& file) const {
+    return static_cast<int64_t>(file.content->size());
+  }
+};
+
+using CachedFiles =
+    LruCache<std::string, CachedFile, MetadataContentWeigher, StringHash, 
StringEqual>;
+
+// Owned by the table's cache handle. Only the registry accesses these fields 
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;
+};
+
+class ContentCacheRegistry {
+ public:
+  explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {}
+
+  // Pin the files for the calling operation. Their entries are protected by 
the
+  // per-table mutex, so accessing bytes never requires holding the registry 
lock.
+  std::shared_ptr<CachedFiles> Find(const ContentCacheRegistration& entry,
+                                    bool touch = true) {
+    std::lock_guard lock(mutex_);
+    if (touch && entry.files) {
+      entries_.splice(entries_.begin(), entries_, entry.position);
+    }
+    return entry.files;
+  }
+
+  std::shared_ptr<CachedFiles> GetOrCreate(
+      const std::shared_ptr<ContentCacheRegistration>& entry, size_t 
max_total_bytes) {
+    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);
+      TrimToCapacity();
+    }
+    return entry->files;
+  }
+
+  void Erase(ContentCacheRegistration& entry) {
+    std::lock_guard lock(mutex_);
+    if (entry.files) {
+      entries_.erase(entry.position);
+      entry.files.reset();
+    }
+  }
+
+  int32_t SetCapacity(int32_t capacity) {
+    ICEBERG_DCHECK(capacity > 0, "Global manifest cache limit must be 
positive");
+    std::lock_guard lock(mutex_);
+    const auto previous = std::exchange(capacity_, capacity);
+    TrimToCapacity();
+    return previous;
+  }
+
+ private:
+  void TrimToCapacity() {
+    while (std::cmp_greater(entries_.size(), capacity_)) {
+      if (auto entry = entries_.back().lock()) {
+        entry->files.reset();
+      }
+      entries_.pop_back();
+    }
+  }
+
+  std::mutex mutex_;
+  int32_t capacity_;
+  ContentCacheRegistration::Entries entries_;
+};
+
+namespace {
+
+std::optional<std::string_view> StoragePath(const InputFile& input) {
+  if (const auto* file = dynamic_cast<const 
InputFileWithStoragePath*>(&input)) {
+    return file->storage_path();
+  }
+  return std::nullopt;
+}
+
+std::shared_ptr<ContentCacheRegistry> GlobalContentCacheRegistry() {
+  // Handles keep the registry alive even when destroyed during static 
teardown.
+  static auto registry = std::make_shared<ContentCacheRegistry>(8);
+  return registry;
+}
+
+Result<std::vector<std::byte>> ReadInputFile(InputFile& input_file, int64_t 
read_size,
+                                             std::string_view file_location) {
+  if (read_size < 0) {
+    return Invalid("Invalid negative file size {} for {}", read_size, 
file_location);
+  }
+  if (std::cmp_greater(read_size, std::numeric_limits<size_t>::max())) {
+    return Invalid("File size {} exceeds size_t max for {}", read_size, 
file_location);
+  }
+
+  auto size = static_cast<size_t>(read_size);
+  std::vector<std::byte> content(size);
+  ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open());
+  Status read_status = {};
+  if (size > 0) {
+    read_status = stream->ReadFully(/*position=*/0, content);
+  }
+  ICEBERG_RETURN_UNEXPECTED(
+      FinishWithCloseStatus(std::move(read_status), stream->Close()));
+  return content;
+}
+
+class CachedSeekableInputStream : public SeekableInputStream {
+ public:
+  explicit CachedSeekableInputStream(MetadataContent content)
+      : content_(std::move(content)) {}
+
+  Result<int64_t> Position() const override { return 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, content_->size()),
+                     "Position {} exceeds file size {}", position, 
content_->size());
+    position_ = position;
+    return {};
+  }
+
+  Result<int64_t> Read(std::span<std::byte> out) override {
+    ICEBERG_PRECHECK(!closed_, "Input stream is closed");
+    auto position = static_cast<size_t>(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<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, content_->size()),
+                     "Position {} exceeds file size {}", position, 
content_->size());
+    auto offset = static_cast<size_t>(position);
+    ICEBERG_PRECHECK(out.size() <= content_->size() - offset,
+                     "Read out of bounds: offset {} + length {} exceeds file 
size {}",
+                     position, out.size(), content_->size());
+    if (!out.empty()) {
+      std::memcpy(out.data(), content_->data() + offset, out.size());
+    }
+    return {};
+  }
+
+  Status Close() override {
+    closed_ = true;
+    return {};
+  }
+
+ private:
+  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)
+      : input_(std::move(input)),
+        cache_(std::move(cache)),
+        location_(input_->location()),
+        size_(size),
+        generation_(generation) {}
+  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<CachedSeekableInputStream>(content_);
+    }
+    if (auto cached = cache_->Find(location_)) {
+      return std::make_unique<CachedSeekableInputStream>(std::move(cached));
+    }
+    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());
+    cache_->Insert(location_, content, generation_, StoragePath(*input_));
+    return std::make_unique<CachedSeekableInputStream>(std::move(content));
+  }
+
+ private:
+  std::unique_ptr<InputFile> input_;
+  std::shared_ptr<ContentCache> cache_;
+  std::string location_;
+  int64_t size_;
+  uint64_t generation_ = 0;
+  MetadataContent content_;
+};
+
+// Manifest maintenance creates outputs on storage. Cleanup deletes through 
storage
+// and invalidates the cache after each delete attempt.
+class ManifestFileIO : public FileIO {
+ public:
+  ManifestFileIO(std::shared_ptr<FileIO> io, std::shared_ptr<ContentCache> 
cache)
+      : io_(std::move(io)), cache_(std::move(cache)) {}
+  Result<std::unique_ptr<InputFile>> NewInputFile(std::string location) 
override {
+    return cache_->NewInputFile(io_, std::move(location));
+  }
+  Result<std::unique_ptr<InputFile>> NewInputFile(std::string location,
+                                                  size_t length) override {
+    return cache_->NewInputFile(io_, 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 io_->ReadFile(location, length);
+    }
+    return FileIO::ReadFile(location, std::nullopt);
+  }
+  Result<std::unique_ptr<OutputFile>> NewOutputFile(std::string location) 
override {
+    return io_->NewOutputFile(std::move(location));
+  }
+  Status DeleteFile(const std::string& /*location*/) override {

Review Comment:
   Could we give manifest cleanup a single operation that deletes through 
storage and invalidates the cache? Today every cleanup caller has to remember 
both steps.



##########
src/iceberg/content_cache.cc:
##########
@@ -0,0 +1,439 @@
+/*
+ * 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 <cstring>
+#include <limits>
+#include <list>
+#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 {
+
+struct CachedFile {
+  MetadataContent content;
+  std::optional<std::string> storage_path;
+};
+
+struct MetadataContentWeigher {
+  int64_t operator()(const std::string&, const CachedFile& file) const {
+    return static_cast<int64_t>(file.content->size());
+  }
+};
+
+using CachedFiles =
+    LruCache<std::string, CachedFile, MetadataContentWeigher, StringHash, 
StringEqual>;
+
+// Owned by the table's cache handle. Only the registry accesses these fields 
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;
+};
+
+class ContentCacheRegistry {
+ public:
+  explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {}
+
+  // Pin the files for the calling operation. Their entries are protected by 
the
+  // per-table mutex, so accessing bytes never requires holding the registry 
lock.
+  std::shared_ptr<CachedFiles> Find(const ContentCacheRegistration& entry,
+                                    bool touch = true) {
+    std::lock_guard lock(mutex_);
+    if (touch && entry.files) {
+      entries_.splice(entries_.begin(), entries_, entry.position);
+    }
+    return entry.files;
+  }
+
+  std::shared_ptr<CachedFiles> GetOrCreate(
+      const std::shared_ptr<ContentCacheRegistration>& entry, size_t 
max_total_bytes) {
+    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);
+      TrimToCapacity();
+    }
+    return entry->files;
+  }
+
+  void Erase(ContentCacheRegistration& entry) {
+    std::lock_guard lock(mutex_);
+    if (entry.files) {
+      entries_.erase(entry.position);
+      entry.files.reset();
+    }
+  }
+
+  int32_t SetCapacity(int32_t capacity) {
+    ICEBERG_DCHECK(capacity > 0, "Global manifest cache limit must be 
positive");
+    std::lock_guard lock(mutex_);
+    const auto previous = std::exchange(capacity_, capacity);
+    TrimToCapacity();
+    return previous;
+  }
+
+ private:
+  void TrimToCapacity() {
+    while (std::cmp_greater(entries_.size(), capacity_)) {
+      if (auto entry = entries_.back().lock()) {
+        entry->files.reset();

Review Comment:
   This reset can destroy an entire table's LRU under the registry mutex, 
blocking lookups for other tables. Could we detach the evicted state under the 
lock and release it after unlocking?



##########
src/iceberg/arrow/arrow_io.cc:
##########
@@ -421,6 +422,16 @@ class ArrowInputFile : public InputFile {
         file_size_(file_size) {}
 
   std::string_view location() const override { return location_; }
+  std::optional<std::string_view> storage_path() const override {
+    const auto type = fs_->type_name();
+    // Local paths can have symlinks, and a custom filesystem defines its own 
aliases.
+    if (type != "s3" && type != "mock") return std::nullopt;

Review Comment:
   This looks too hacky to me...



##########
src/iceberg/arrow/arrow_io.cc:
##########
@@ -421,6 +422,16 @@ class ArrowInputFile : public InputFile {
         file_size_(file_size) {}
 
   std::string_view location() const override { return location_; }
+  std::optional<std::string_view> storage_path() const override {
+    const auto type = fs_->type_name();
+    // Local paths can have symlinks, and a custom filesystem defines its own 
aliases.
+    if (type != "s3" && type != "mock") return std::nullopt;

Review Comment:
   Could we clear the table’s manifest cache once per cleanup batch? That would 
handle all path aliases without adding an InputFile subtype.



##########
src/iceberg/content_cache.cc:
##########
@@ -0,0 +1,439 @@
+/*
+ * 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 <cstring>
+#include <limits>
+#include <list>
+#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 {
+
+struct CachedFile {
+  MetadataContent content;
+  std::optional<std::string> storage_path;
+};
+
+struct MetadataContentWeigher {
+  int64_t operator()(const std::string&, const CachedFile& file) const {
+    return static_cast<int64_t>(file.content->size());
+  }
+};
+
+using CachedFiles =
+    LruCache<std::string, CachedFile, MetadataContentWeigher, StringHash, 
StringEqual>;
+
+// Owned by the table's cache handle. Only the registry accesses these fields 
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;
+};
+
+class ContentCacheRegistry {
+ public:
+  explicit ContentCacheRegistry(int32_t capacity) : capacity_(capacity) {}
+
+  // Pin the files for the calling operation. Their entries are protected by 
the
+  // per-table mutex, so accessing bytes never requires holding the registry 
lock.
+  std::shared_ptr<CachedFiles> Find(const ContentCacheRegistration& entry,
+                                    bool touch = true) {
+    std::lock_guard lock(mutex_);
+    if (touch && entry.files) {
+      entries_.splice(entries_.begin(), entries_, entry.position);
+    }
+    return entry.files;
+  }
+
+  std::shared_ptr<CachedFiles> GetOrCreate(
+      const std::shared_ptr<ContentCacheRegistration>& entry, size_t 
max_total_bytes) {
+    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);
+      TrimToCapacity();
+    }
+    return entry->files;
+  }
+
+  void Erase(ContentCacheRegistration& entry) {
+    std::lock_guard lock(mutex_);
+    if (entry.files) {
+      entries_.erase(entry.position);
+      entry.files.reset();
+    }
+  }
+
+  int32_t SetCapacity(int32_t capacity) {
+    ICEBERG_DCHECK(capacity > 0, "Global manifest cache limit must be 
positive");
+    std::lock_guard lock(mutex_);
+    const auto previous = std::exchange(capacity_, capacity);
+    TrimToCapacity();
+    return previous;
+  }
+
+ private:
+  void TrimToCapacity() {
+    while (std::cmp_greater(entries_.size(), capacity_)) {
+      if (auto entry = entries_.back().lock()) {
+        entry->files.reset();
+      }
+      entries_.pop_back();
+    }
+  }
+
+  std::mutex mutex_;
+  int32_t capacity_;
+  ContentCacheRegistration::Entries entries_;
+};
+
+namespace {
+
+std::optional<std::string_view> StoragePath(const InputFile& input) {
+  if (const auto* file = dynamic_cast<const 
InputFileWithStoragePath*>(&input)) {
+    return file->storage_path();
+  }
+  return std::nullopt;
+}
+
+std::shared_ptr<ContentCacheRegistry> GlobalContentCacheRegistry() {
+  // Handles keep the registry alive even when destroyed during static 
teardown.
+  static auto registry = std::make_shared<ContentCacheRegistry>(8);
+  return registry;
+}
+
+Result<std::vector<std::byte>> ReadInputFile(InputFile& input_file, int64_t 
read_size,
+                                             std::string_view file_location) {
+  if (read_size < 0) {
+    return Invalid("Invalid negative file size {} for {}", read_size, 
file_location);
+  }
+  if (std::cmp_greater(read_size, std::numeric_limits<size_t>::max())) {
+    return Invalid("File size {} exceeds size_t max for {}", read_size, 
file_location);
+  }
+
+  auto size = static_cast<size_t>(read_size);
+  std::vector<std::byte> content(size);
+  ICEBERG_ASSIGN_OR_RAISE(auto stream, input_file.Open());
+  Status read_status = {};
+  if (size > 0) {
+    read_status = stream->ReadFully(/*position=*/0, content);
+  }
+  ICEBERG_RETURN_UNEXPECTED(
+      FinishWithCloseStatus(std::move(read_status), stream->Close()));
+  return content;
+}
+
+class CachedSeekableInputStream : public SeekableInputStream {
+ public:
+  explicit CachedSeekableInputStream(MetadataContent content)
+      : content_(std::move(content)) {}
+
+  Result<int64_t> Position() const override { return 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, content_->size()),
+                     "Position {} exceeds file size {}", position, 
content_->size());
+    position_ = position;
+    return {};
+  }
+
+  Result<int64_t> Read(std::span<std::byte> out) override {
+    ICEBERG_PRECHECK(!closed_, "Input stream is closed");
+    auto position = static_cast<size_t>(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<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, content_->size()),
+                     "Position {} exceeds file size {}", position, 
content_->size());
+    auto offset = static_cast<size_t>(position);
+    ICEBERG_PRECHECK(out.size() <= content_->size() - offset,
+                     "Read out of bounds: offset {} + length {} exceeds file 
size {}",
+                     position, out.size(), content_->size());
+    if (!out.empty()) {
+      std::memcpy(out.data(), content_->data() + offset, out.size());
+    }
+    return {};
+  }
+
+  Status Close() override {
+    closed_ = true;
+    return {};
+  }
+
+ private:
+  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)
+      : input_(std::move(input)),
+        cache_(std::move(cache)),
+        location_(input_->location()),
+        size_(size),
+        generation_(generation) {}
+  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<CachedSeekableInputStream>(content_);
+    }
+    if (auto cached = cache_->Find(location_)) {
+      return std::make_unique<CachedSeekableInputStream>(std::move(cached));
+    }
+    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());
+    cache_->Insert(location_, content, generation_, StoragePath(*input_));
+    return std::make_unique<CachedSeekableInputStream>(std::move(content));
+  }
+
+ private:
+  std::unique_ptr<InputFile> input_;
+  std::shared_ptr<ContentCache> cache_;
+  std::string location_;
+  int64_t size_;
+  uint64_t generation_ = 0;
+  MetadataContent content_;
+};
+
+// Manifest maintenance creates outputs on storage. Cleanup deletes through 
storage
+// and invalidates the cache after each delete attempt.
+class ManifestFileIO : public FileIO {
+ public:
+  ManifestFileIO(std::shared_ptr<FileIO> io, std::shared_ptr<ContentCache> 
cache)
+      : io_(std::move(io)), cache_(std::move(cache)) {}
+  Result<std::unique_ptr<InputFile>> NewInputFile(std::string location) 
override {
+    return cache_->NewInputFile(io_, std::move(location));
+  }
+  Result<std::unique_ptr<InputFile>> NewInputFile(std::string location,
+                                                  size_t length) override {
+    return cache_->NewInputFile(io_, 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 io_->ReadFile(location, length);
+    }
+    return FileIO::ReadFile(location, std::nullopt);
+  }
+  Result<std::unique_ptr<OutputFile>> NewOutputFile(std::string location) 
override {
+    return io_->NewOutputFile(std::move(location));
+  }
+  Status DeleteFile(const std::string& /*location*/) override {
+    return NotSupported("Delete files through the storage FileIO");
+  }
+  Status DeleteFiles(const std::vector<std::string>& /*locations*/) override {
+    return NotSupported("Delete files through the storage FileIO");
+  }
+  const std::unordered_map<std::string, std::string>& properties() const 
override {
+    return io_->properties();
+  }
+
+ private:
+  std::shared_ptr<FileIO> io_;
+  std::shared_ptr<ContentCache> cache_;
+};
+
+}  // namespace
+
+Result<ContentCacheOptions> ContentCacheOptions::FromProperties(
+    const std::unordered_map<std::string, std::string>& properties) {
+  ContentCacheOptions options;
+  const auto& enabled = ContentCacheProperties::kEnabled;
+  options.enabled =
+      PropertyUtil::PropertyAsBoolean(properties, enabled.key(), 
enabled.value());
+  if (!options.enabled) {
+    return options;
+  }
+  const auto read_limit = [&properties](const auto& entry) -> Result<size_t> {
+    ICEBERG_ASSIGN_OR_RAISE(auto limit, PropertyUtil::PropertyAsInt64(
+                                            properties, entry.key(), 
entry.value()));
+    ICEBERG_PRECHECK(limit > 0 && std::in_range<size_t>(limit),
+                     "Property '{}' must be positive and fit in size_t: {}", 
entry.key(),
+                     limit);
+    return static_cast<size_t>(limit);
+  };
+  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(ContentCacheOptions options)
+    : options_(options),
+      registry_(GlobalContentCacheRegistry()),
+      registration_(std::make_shared<ContentCacheRegistration>()) {}
+
+ContentCache::~ContentCache() { registry_->Erase(*registration_); }
+
+int32_t ContentCache::SetGlobalCapacity(int32_t max_caches) {
+  return GlobalContentCacheRegistry()->SetCapacity(max_caches);
+}
+
+std::shared_ptr<FileIO> ContentCache::Wrap(std::shared_ptr<FileIO> io) {

Review Comment:
   A cache can be bound to several FileIOs, and a hit is keyed only by location 
before storage resolution. Could we make the same-storage-namespace requirement 
explicit at this binding point? Otherwise a rebind to a different backend can 
serve bytes from the previous one.



-- 
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]

Reply via email to