This is an automated email from the ASF dual-hosted git repository.

wgtmac pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-cpp.git


The following commit(s) were added to refs/heads/main by this push:
     new e0f15236 feat(inspect): capture scan inputs and open snapshot tasks 
(#1120)
e0f15236 is described below

commit e0f15236ffe530dc1c7ba530b6e146cf534647cf
Author: Manu Zhang <[email protected]>
AuthorDate: Fri Nov 20 15:18:36 2026 +0800

    feat(inspect): capture scan inputs and open snapshot tasks (#1120)
    
    ## Purpose
    
    Regular data-table scans already support snapshot selection through 
`UseSnapshot()`, `UseRef()`, and `AsOfTime()`. `MetadataScanBuilder` also 
already exposes these selectors, but its implemented metadata tables 
(`snapshots`, `history`, and `refs`) use in-memory static tasks and reject 
time-travel selection.
    
    This PR adds a generic snapshot-task execution path for the upcoming 
FilesTable (#876), ManifestsTable (#1121), and PartitionsTable (#1122) 
implementations. Those tables need to read metadata rows for a selected 
snapshot. The table implementations follow in their own PRs.
    
    A source-table refresh after `NewScan()` must not change a builder's 
captured inputs. Built scans, tasks, and row streams retain their inputs for 
their own lifetimes. This PR supplies that ownership contract and builds 
directly on main.
    
    ## Changes and rationale
    
    - **Capture consistent inputs.** The builder captures metadata and FileIO, 
then derives the schema through `SchemaForScan(captured_metadata)`. FileIO is 
held separately from `MetadataScanContext` and passed to the table's 
`MakeScan()` hook, so snapshot tasks retain the captured IO even after a source 
refresh.
    - **Share snapshot-task execution.** Define `SnapshotMetadataTask` 
alongside `StaticMetadataTask` in `metadata_scan_task.h/.cc`. Its factory 
validates the context, FileIO, and row-reader callback. 
`MetadataScanTaskReader` opens it through that callback, allowing 
table-specific readers without a dispatch branch for every table.
    - **Validate before reading.** Centralize required metadata/schema checks 
in `MetadataScanContext::Validate()`, check whole-column projections, and 
resolve snapshot IDs, references, or timestamps against captured metadata. 
Reference lookup reuses `SnapshotUtil::LatestSnapshot()` after strict reference 
validation. Empty main selections return `nullptr`; dangling snapshot IDs 
remain errors. Main-branch detection is shared through 
`SnapshotUtil::IsMainBranch()`.
    - **Retain execution inputs.** Tasks can be reopened with independent 
streams and configurable batch sizes. The builder, task, and active stream each 
retain the FileIO they need; static in-memory scans do not require FileIO.
    
    ## Public API and ABI changes
    
    The public virtual getter changes its return type:
    
    ```diff
    - virtual const std::shared_ptr<Schema>& schema() const = 0;
    + virtual std::shared_ptr<Schema> schema() const = 0;
    ```
    
    The member function remains `const`. Returning the pointer by value lets 
implementations copy it under their schema-cache lock, giving callers ownership 
that remains valid when the cache is replaced. This copies the `shared_ptr`, 
not the `Schema`.
    
    Derived metadata tables must also update their protected `MakeScan()` 
override to accept the builder-captured `std::shared_ptr<FileIO>` as its second 
argument. The PR adds the protected `SchemaForScan()` hook, 
`SnapshotMetadataTask`, and `TaskKind::kSnapshot`. Existing binary consumers 
must be rebuilt.
    
    ## Execution scope
    
    The initial snapshot scan plans one task using an in-process row-reader 
callback. Splitting work into multiple tasks and providing serializable task 
descriptions are follow-up work for parallel and distributed execution.
    
    ## Validation
    
    - All 62 metadata tests passed, including missing-input checks, repeated 
task opening, static scanning without FileIO, and the new FileIO-capture 
regression across source refresh and builder/scan/task destruction.
    - C++20 public-header compatibility passed.
    - Required pre-commit and changed-code clang-tidy 22.1.8 passed.
    
    Local validation covers the standalone static Debug scan implementation and 
tests, rebuilt against this revision with unchanged cached static dependencies. 
Dependent table PRs must pass captured FileIO separately when adapting their 
`MakeScan()` overrides.
---
 src/iceberg/CMakeLists.txt                         |   1 +
 src/iceberg/inspect/history_table.cc               |   9 +-
 src/iceberg/inspect/history_table.h                |   4 +-
 src/iceberg/inspect/metadata_scan.cc               |  35 ++-
 src/iceberg/inspect/metadata_scan.h                |   7 +-
 src/iceberg/inspect/metadata_scan_task.cc          |  21 ++
 src/iceberg/inspect/metadata_scan_task.h           |  34 +++
 src/iceberg/inspect/metadata_scan_task_reader.cc   |   5 +
 src/iceberg/inspect/metadata_table.cc              |   5 +
 src/iceberg/inspect/metadata_table.h               |  11 +-
 src/iceberg/inspect/metadata_table_util.cc         | 109 +++++++++
 src/iceberg/inspect/metadata_table_util_internal.h |  39 ++++
 src/iceberg/inspect/refs_table.cc                  |   9 +-
 src/iceberg/inspect/refs_table.h                   |   4 +-
 src/iceberg/inspect/snapshots_table.cc             |  11 +-
 src/iceberg/inspect/snapshots_table.h              |   4 +-
 src/iceberg/test/CMakeLists.txt                    |   1 +
 .../test/inspect/metadata_snapshot_scan_test.cc    | 252 +++++++++++++++++++++
 src/iceberg/test/inspect/snapshots_table_test.cc   |  12 +
 src/iceberg/util/snapshot_util.cc                  |  10 +-
 src/iceberg/util/snapshot_util.h                   |   5 +
 21 files changed, 544 insertions(+), 44 deletions(-)

diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt
index 4cde4fb2..0768f1aa 100644
--- a/src/iceberg/CMakeLists.txt
+++ b/src/iceberg/CMakeLists.txt
@@ -63,6 +63,7 @@ set(ICEBERG_SOURCES
     inspect/metadata_table.cc
     inspect/metadata_scan_task.cc
     inspect/metadata_scan_task_reader.cc
+    inspect/metadata_table_util.cc
     inspect/refs_table.cc
     inspect/snapshots_table.cc
     inheritable_metadata.cc
diff --git a/src/iceberg/inspect/history_table.cc 
b/src/iceberg/inspect/history_table.cc
index 1ee61a5f..f6dd3a87 100644
--- a/src/iceberg/inspect/history_table.cc
+++ b/src/iceberg/inspect/history_table.cc
@@ -94,7 +94,7 @@ HistoryTable::HistoryTable(std::shared_ptr<const Table> table)
 
 HistoryTable::~HistoryTable() = default;
 
-const std::shared_ptr<Schema>& HistoryTable::schema() const { return 
CanonicalSchema(); }
+std::shared_ptr<Schema> HistoryTable::schema() const { return 
CanonicalSchema(); }
 
 const std::shared_ptr<Schema>& HistoryTable::CanonicalSchema() {
   static const auto schema = std::make_shared<Schema>(std::vector<SchemaField>{
@@ -112,7 +112,7 @@ Result<std::unique_ptr<HistoryTable>> HistoryTable::Make(
 }
 
 Result<std::unique_ptr<MetadataScan>> HistoryTable::MakeScan(
-    internal::MetadataScanContext context) const {
+    internal::MetadataScanContext context, std::shared_ptr<FileIO> /*io*/) 
const {
   return HistoryScan::Make(std::move(context));
 }
 
@@ -170,10 +170,7 @@ Result<std::unique_ptr<HistoryScan>> HistoryScan::Make(
       context.as_of_time_in_millis.has_value()) {
     return NotSupported("Metadata table does not support time travel");
   }
-  ICEBERG_PRECHECK(context.table_metadata != nullptr, "Table metadata cannot 
be null");
-  ICEBERG_PRECHECK(context.schema != nullptr, "Metadata table schema cannot be 
null");
-  ICEBERG_PRECHECK(context.projected_schema != nullptr,
-                   "Projected schema cannot be null");
+  ICEBERG_RETURN_UNEXPECTED(context.Validate());
   ICEBERG_RETURN_UNEXPECTED(internal::SelectAppendFns<HistoryRow>(
       *HistoryTable::CanonicalSchema(), *context.projected_schema, 
kHistoryColumns));
   ICEBERG_ASSIGN_OR_RAISE(auto task,
diff --git a/src/iceberg/inspect/history_table.h 
b/src/iceberg/inspect/history_table.h
index d2dffb41..cadb90d3 100644
--- a/src/iceberg/inspect/history_table.h
+++ b/src/iceberg/inspect/history_table.h
@@ -46,11 +46,11 @@ class ICEBERG_EXPORT HistoryTable : public MetadataTable {
 
   MetadataTableKind kind() const noexcept override { return 
MetadataTableKind::kHistory; }
 
-  const std::shared_ptr<Schema>& schema() const override;
+  std::shared_ptr<Schema> schema() const override;
 
  protected:
   Result<std::unique_ptr<MetadataScan>> MakeScan(
-      internal::MetadataScanContext context) const override;
+      internal::MetadataScanContext context, std::shared_ptr<FileIO> io) const 
override;
 
  private:
   friend class MetadataScanTaskReader;
diff --git a/src/iceberg/inspect/metadata_scan.cc 
b/src/iceberg/inspect/metadata_scan.cc
index 2957a2ba..d6cc6236 100644
--- a/src/iceberg/inspect/metadata_scan.cc
+++ b/src/iceberg/inspect/metadata_scan.cc
@@ -107,20 +107,34 @@ class TaskArrowStreamSource {
 
 }  // namespace
 
-MetadataScanBuilder::MetadataScanBuilder(const MetadataTable& table)
-    : table_(&table),
-      context_{.kind = table.kind(),
-               .table_metadata = table.source_table()->metadata(),
-               .schema = table.schema(),
-               .projected_schema = table.schema()} {}
+Status internal::MetadataScanContext::Validate() const {
+  ICEBERG_PRECHECK(table_metadata != nullptr, "Table metadata cannot be null");
+  ICEBERG_PRECHECK(schema != nullptr, "Metadata table schema cannot be null");
+  ICEBERG_PRECHECK(projected_schema != nullptr, "Projected schema cannot be 
null");
+  return {};
+}
+
+MetadataScanBuilder::MetadataScanBuilder(const MetadataTable& table,
+                                         internal::MetadataScanContext context,
+                                         std::shared_ptr<FileIO> io)
+    : table_(&table), context_(std::move(context)), io_(std::move(io)) {}
 
 MetadataScanBuilder::~MetadataScanBuilder() = default;
 
 Result<std::unique_ptr<MetadataScanBuilder>> MetadataScanBuilder::Make(
     const MetadataTable& table) {
   ICEBERG_PRECHECK(table.source_table() != nullptr, "Source table cannot be 
null");
-  ICEBERG_PRECHECK(table.schema() != nullptr, "Metadata table schema cannot be 
null");
-  return std::unique_ptr<MetadataScanBuilder>(new MetadataScanBuilder(table));
+  auto metadata = table.source_table()->metadata();
+  ICEBERG_PRECHECK(metadata != nullptr, "Table metadata cannot be null");
+  auto io = table.source_table()->io();
+  ICEBERG_ASSIGN_OR_RAISE(auto schema, table.SchemaForScan(*metadata));
+  internal::MetadataScanContext context{.kind = table.kind(),
+                                        .table_metadata = std::move(metadata),
+                                        .schema = schema,
+                                        .projected_schema = std::move(schema)};
+  ICEBERG_RETURN_UNEXPECTED(context.Validate());
+  return std::unique_ptr<MetadataScanBuilder>(
+      new MetadataScanBuilder(table, std::move(context), std::move(io)));
 }
 
 MetadataScanBuilder& MetadataScanBuilder::Select(
@@ -170,9 +184,8 @@ MetadataScanBuilder& MetadataScanBuilder::AsOfTime(int64_t 
as_of_time_in_millis)
 
 Result<std::unique_ptr<MetadataScan>> MetadataScanBuilder::Build() {
   ICEBERG_RETURN_UNEXPECTED(CheckErrors());
-  ICEBERG_PRECHECK(context_.projected_schema != nullptr,
-                   "Projected schema cannot be null");
-  return table_->MakeScan(context_);
+  ICEBERG_RETURN_UNEXPECTED(context_.Validate());
+  return table_->MakeScan(context_, io_);
 }
 
 MetadataScan::MetadataScan(internal::MetadataScanContext context)
diff --git a/src/iceberg/inspect/metadata_scan.h 
b/src/iceberg/inspect/metadata_scan.h
index 5df4cc03..8a53b478 100644
--- a/src/iceberg/inspect/metadata_scan.h
+++ b/src/iceberg/inspect/metadata_scan.h
@@ -52,6 +52,9 @@ struct MetadataScanContext {
   std::optional<int64_t> snapshot_id;
   std::string ref_name;
   std::optional<int64_t> as_of_time_in_millis;
+
+  /// \brief Validate the metadata and schemas required by all scans.
+  ICEBERG_EXPORT Status Validate() const;
 };
 
 }  // namespace internal
@@ -97,10 +100,12 @@ class ICEBERG_EXPORT MetadataScanBuilder : public 
ErrorCollector {
   Result<std::unique_ptr<MetadataScan>> Build();
 
  private:
-  explicit MetadataScanBuilder(const MetadataTable& table);
+  MetadataScanBuilder(const MetadataTable& table, 
internal::MetadataScanContext context,
+                      std::shared_ptr<FileIO> io);
 
   const MetadataTable* table_;
   internal::MetadataScanContext context_;
+  const std::shared_ptr<FileIO> io_;
 };
 
 /// \brief A metadata scan that plans tasks or reads all of them as Arrow 
batches.
diff --git a/src/iceberg/inspect/metadata_scan_task.cc 
b/src/iceberg/inspect/metadata_scan_task.cc
index 07195e16..6d6b1c9d 100644
--- a/src/iceberg/inspect/metadata_scan_task.cc
+++ b/src/iceberg/inspect/metadata_scan_task.cc
@@ -49,4 +49,25 @@ StaticMetadataTask::StaticMetadataTask(MetadataTableKind 
table_kind,
       metadata_(std::move(metadata)),
       projected_schema_(std::move(projected_schema)) {}
 
+// SnapshotMetadataTask
+
+Result<std::shared_ptr<SnapshotMetadataTask>> SnapshotMetadataTask::Make(
+    internal::MetadataScanContext context, std::shared_ptr<FileIO> io,
+    ReadRowsFunction read_rows) {
+  ICEBERG_PRECHECK(read_rows != nullptr, "Snapshot row reader cannot be null");
+  ICEBERG_RETURN_UNEXPECTED(context.Validate());
+  ICEBERG_PRECHECK(io != nullptr, "FileIO cannot be null");
+  return std::shared_ptr<SnapshotMetadataTask>(
+      new SnapshotMetadataTask(std::move(context), std::move(io), read_rows));
+}
+
+SnapshotMetadataTask::SnapshotMetadataTask(internal::MetadataScanContext 
context,
+                                           std::shared_ptr<FileIO> io,
+                                           ReadRowsFunction read_rows)
+    : context_(std::move(context)), io_(std::move(io)), read_rows_(read_rows) 
{}
+
+Result<ArrowArrayStream> SnapshotMetadataTask::Open(int64_t batch_size) const {
+  return read_rows_(context_, io_, batch_size);
+}
+
 }  // namespace iceberg
diff --git a/src/iceberg/inspect/metadata_scan_task.h 
b/src/iceberg/inspect/metadata_scan_task.h
index 6e0dac54..eab2d269 100644
--- a/src/iceberg/inspect/metadata_scan_task.h
+++ b/src/iceberg/inspect/metadata_scan_task.h
@@ -19,9 +19,12 @@
 
 #pragma once
 
+#include <cstdint>
 #include <memory>
 
+#include "iceberg/arrow_c_data.h"
 #include "iceberg/iceberg_export.h"
+#include "iceberg/inspect/metadata_scan.h"
 #include "iceberg/result.h"
 #include "iceberg/type_fwd.h"
 
@@ -37,6 +40,8 @@ class ICEBERG_EXPORT MetadataScanTask {
   enum class TaskKind {
     /// StaticMetadataTask reads in-memory table metadata (snapshots, history, 
refs).
     kStatic,
+    /// SnapshotMetadataTask reads snapshot manifests and their file entries.
+    kSnapshot,
   };
 
   virtual ~MetadataScanTask() = default;
@@ -85,4 +90,33 @@ class ICEBERG_EXPORT StaticMetadataTask : public 
MetadataScanTask {
   const std::shared_ptr<Schema> projected_schema_;
 };
 
+/// \brief Task retaining a snapshot scan's captured settings and FileIO.
+///
+/// Rows are read through an in-process callback. Splitting work across 
multiple
+/// tasks and serializable task descriptions are future work for parallel 
execution.
+class ICEBERG_EXPORT SnapshotMetadataTask : public MetadataScanTask {
+ public:
+  using ReadRowsFunction = Result<ArrowArrayStream> (*)(
+      const internal::MetadataScanContext& /*context*/,
+      const std::shared_ptr<FileIO>& /*io*/, int64_t /*batch_size*/);
+
+  /// \brief Create a task owning the scan settings, FileIO, and row reader.
+  static Result<std::shared_ptr<SnapshotMetadataTask>> Make(
+      internal::MetadataScanContext context, std::shared_ptr<FileIO> io,
+      ReadRowsFunction read_rows);
+
+  Result<ArrowArrayStream> Open(int64_t batch_size) const;
+
+  TaskKind task_kind() const override { return TaskKind::kSnapshot; }
+  MetadataTableKind table_kind() const override { return context_.kind; }
+
+ private:
+  SnapshotMetadataTask(internal::MetadataScanContext context, 
std::shared_ptr<FileIO> io,
+                       ReadRowsFunction read_rows);
+
+  const internal::MetadataScanContext context_;
+  const std::shared_ptr<FileIO> io_;
+  const ReadRowsFunction read_rows_;
+};
+
 }  // namespace iceberg
diff --git a/src/iceberg/inspect/metadata_scan_task_reader.cc 
b/src/iceberg/inspect/metadata_scan_task_reader.cc
index 74acaa8f..a43b4f26 100644
--- a/src/iceberg/inspect/metadata_scan_task_reader.cc
+++ b/src/iceberg/inspect/metadata_scan_task_reader.cc
@@ -47,6 +47,11 @@ Result<std::unique_ptr<MetadataScanTaskReader>> 
MetadataScanTaskReader::Make(
 Result<ArrowArrayStream> MetadataScanTaskReader::Open(
     const MetadataScanTask& task) const {
   switch (task.task_kind()) {
+    case MetadataScanTask::TaskKind::kSnapshot: {
+      const auto& snapshot_task =
+          internal::checked_cast<const SnapshotMetadataTask&>(task);
+      return snapshot_task.Open(options_.batch_size);
+    }
     case MetadataScanTask::TaskKind::kStatic: {
       const auto& static_task = internal::checked_cast<const 
StaticMetadataTask&>(task);
       switch (static_task.table_kind()) {
diff --git a/src/iceberg/inspect/metadata_table.cc 
b/src/iceberg/inspect/metadata_table.cc
index 012ffaa9..57d8cdad 100644
--- a/src/iceberg/inspect/metadata_table.cc
+++ b/src/iceberg/inspect/metadata_table.cc
@@ -53,6 +53,11 @@ const std::shared_ptr<const Table>& 
MetadataTable::source_table() const {
   return source_table_;
 }
 
+Result<std::shared_ptr<Schema>> MetadataTable::SchemaForScan(
+    const TableMetadata& metadata) const {
+  return schema();
+}
+
 Result<std::unique_ptr<MetadataScanBuilder>> MetadataTable::NewScan() const {
   return MetadataScanBuilder::Make(*this);
 }
diff --git a/src/iceberg/inspect/metadata_table.h 
b/src/iceberg/inspect/metadata_table.h
index 83f44f5c..2e610527 100644
--- a/src/iceberg/inspect/metadata_table.h
+++ b/src/iceberg/inspect/metadata_table.h
@@ -78,8 +78,8 @@ class ICEBERG_EXPORT MetadataTable {
   /// \brief Return this metadata table's kind.
   virtual Kind kind() const noexcept = 0;
 
-  /// \brief Return the complete canonical schema of this metadata table.
-  virtual const std::shared_ptr<Schema>& schema() const = 0;
+  /// \brief Return shared ownership of this metadata table's canonical schema.
+  virtual std::shared_ptr<Schema> schema() const = 0;
 
   /// \brief Return the source table whose metadata is exposed.
   const std::shared_ptr<const Table>& source_table() const;
@@ -93,9 +93,14 @@ class ICEBERG_EXPORT MetadataTable {
  protected:
   explicit MetadataTable(std::shared_ptr<const Table> source_table);
 
+  /// \brief Derive a scan schema from the captured source metadata.
+  virtual Result<std::shared_ptr<Schema>> SchemaForScan(
+      const TableMetadata& metadata) const;
+
   /// \brief Plan a scan using the captured metadata, projection, and snapshot 
selection.
+  /// \param io FileIO captured when the scan builder was created
   virtual Result<std::unique_ptr<MetadataScan>> MakeScan(
-      internal::MetadataScanContext context) const = 0;
+      internal::MetadataScanContext context, std::shared_ptr<FileIO> io) const 
= 0;
 
  private:
   friend class MetadataScanBuilder;
diff --git a/src/iceberg/inspect/metadata_table_util.cc 
b/src/iceberg/inspect/metadata_table_util.cc
new file mode 100644
index 00000000..16a063f4
--- /dev/null
+++ b/src/iceberg/inspect/metadata_table_util.cc
@@ -0,0 +1,109 @@
+/*
+ * 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 <memory>
+#include <string>
+#include <utility>
+
+#include "iceberg/constants.h"
+#include "iceberg/inspect/metadata_table_util_internal.h"
+#include "iceberg/schema.h"
+#include "iceberg/table_metadata.h"
+#include "iceberg/type.h"
+#include "iceberg/util/macros.h"
+#include "iceberg/util/snapshot_util.h"
+
+namespace iceberg::internal {
+
+namespace {
+/// A scan that plans one task for a metadata table's selected snapshot.
+///
+/// The task retains the captured metadata, schemas, and FileIO so it can 
outlive the
+/// scan. Table-specific row reading is deferred to the supplied callback when
+/// MetadataScanTaskReader opens the task.
+class SnapshotMetadataScan : public MetadataScan {
+ public:
+  SnapshotMetadataScan(MetadataScanContext context,
+                       std::shared_ptr<SnapshotMetadataTask> task)
+      : MetadataScan(std::move(context)), task_(std::move(task)) {}
+
+  Result<MetadataScanTaskStreamPtr> PlanTasksStream() const override {
+    // Each planning call gets a fresh stream over the same retained task.
+    return MetadataScanTaskStream::FromVector({task_});
+  }
+
+ private:
+  const std::shared_ptr<MetadataScanTask> task_;
+};
+}  // namespace
+
+Result<std::unique_ptr<MetadataScan>> MakeSnapshotMetadataScan(
+    MetadataScanContext context, std::shared_ptr<FileIO> io,
+    SnapshotMetadataTask::ReadRowsFunction read_rows) {
+  ICEBERG_ASSIGN_OR_RAISE(auto task,
+                          SnapshotMetadataTask::Make(context, std::move(io), 
read_rows));
+  for (const auto& projected : context.projected_schema->fields()) {
+    ICEBERG_ASSIGN_OR_RAISE(auto field,
+                            
context.schema->GetFieldById(projected.field_id()));
+    ICEBERG_PRECHECK(field.has_value(), "Unknown metadata column: {}", 
projected.name());
+    if (*field->get().type() != *projected.type()) {
+      return NotSupported("Partial projection of metadata column is not 
supported: {}",
+                          projected.name());
+    }
+    ICEBERG_PRECHECK(!field->get().optional() || projected.optional(),
+                     "Nullable metadata column cannot be projected as 
required: {}",
+                     projected.name());
+  }
+  ICEBERG_RETURN_UNEXPECTED(
+      ResolveMetadataTableSnapshot(*context.table_metadata, context));
+  return std::make_unique<SnapshotMetadataScan>(std::move(context), 
std::move(task));
+}
+
+Result<std::shared_ptr<Snapshot>> ResolveMetadataTableSnapshot(
+    const TableMetadata& metadata, const MetadataScanContext& selection) {
+  const bool is_main_ref = SnapshotUtil::IsMainBranch(selection.ref_name);
+  if (!is_main_ref) {
+    ICEBERG_PRECHECK(
+        !selection.snapshot_id.has_value() && 
!selection.as_of_time_in_millis.has_value(),
+        "Cannot combine a snapshot reference with a snapshot ID or timestamp");
+  }
+  if (selection.snapshot_id.has_value()) {
+    return metadata.SnapshotById(*selection.snapshot_id);
+  }
+  if (selection.as_of_time_in_millis.has_value()) {
+    ICEBERG_ASSIGN_OR_RAISE(
+        auto snapshot_id,
+        SnapshotUtil::SnapshotIdAsOfTime(
+            metadata, TimePointMsFromUnixMs(*selection.as_of_time_in_millis)));
+    return metadata.SnapshotById(snapshot_id);
+  }
+  if (is_main_ref && metadata.current_snapshot_id == kInvalidSnapshotId) {
+    return std::shared_ptr<Snapshot>{nullptr};
+  }
+  if (!is_main_ref) {
+    auto ref = metadata.refs.find(selection.ref_name);
+    ICEBERG_PRECHECK(ref != metadata.refs.end(), "Cannot find snapshot 
reference '{}'",
+                     selection.ref_name);
+    ICEBERG_PRECHECK(ref->second != nullptr, "Snapshot reference '{}' is null",
+                     selection.ref_name);
+  }
+  return SnapshotUtil::LatestSnapshot(metadata, selection.ref_name);
+}
+
+}  // namespace iceberg::internal
diff --git a/src/iceberg/inspect/metadata_table_util_internal.h 
b/src/iceberg/inspect/metadata_table_util_internal.h
new file mode 100644
index 00000000..81b03c1c
--- /dev/null
+++ b/src/iceberg/inspect/metadata_table_util_internal.h
@@ -0,0 +1,39 @@
+/*
+ * 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 <memory>
+
+#include "iceberg/iceberg_export.h"
+#include "iceberg/inspect/metadata_scan.h"
+#include "iceberg/inspect/metadata_scan_task.h"
+#include "iceberg/result.h"
+
+namespace iceberg::internal {
+
+ICEBERG_EXPORT Result<std::unique_ptr<MetadataScan>> MakeSnapshotMetadataScan(
+    MetadataScanContext context, std::shared_ptr<FileIO> io,
+    SnapshotMetadataTask::ReadRowsFunction read_rows);
+
+/// \brief Resolve a time-travel selection to a snapshot.
+ICEBERG_EXPORT Result<std::shared_ptr<Snapshot>> ResolveMetadataTableSnapshot(
+    const TableMetadata& metadata, const MetadataScanContext& selection);
+
+}  // namespace iceberg::internal
diff --git a/src/iceberg/inspect/refs_table.cc 
b/src/iceberg/inspect/refs_table.cc
index 2ace6ed2..6a2ddbed 100644
--- a/src/iceberg/inspect/refs_table.cc
+++ b/src/iceberg/inspect/refs_table.cc
@@ -107,7 +107,7 @@ RefsTable::RefsTable(std::shared_ptr<const Table> table)
 
 RefsTable::~RefsTable() = default;
 
-const std::shared_ptr<Schema>& RefsTable::schema() const { return 
CanonicalSchema(); }
+std::shared_ptr<Schema> RefsTable::schema() const { return CanonicalSchema(); }
 
 const std::shared_ptr<Schema>& RefsTable::CanonicalSchema() {
   static const auto schema = std::make_shared<Schema>(std::vector<SchemaField>{
@@ -127,7 +127,7 @@ Result<std::unique_ptr<RefsTable>> 
RefsTable::Make(std::shared_ptr<const Table>
 }
 
 Result<std::unique_ptr<MetadataScan>> RefsTable::MakeScan(
-    internal::MetadataScanContext context) const {
+    internal::MetadataScanContext context, std::shared_ptr<FileIO> /*io*/) 
const {
   return RefsScan::Make(std::move(context));
 }
 
@@ -178,10 +178,7 @@ Result<std::unique_ptr<RefsScan>> 
RefsScan::Make(internal::MetadataScanContext c
       context.as_of_time_in_millis.has_value()) {
     return NotSupported("Metadata table does not support time travel");
   }
-  ICEBERG_PRECHECK(context.table_metadata != nullptr, "Table metadata cannot 
be null");
-  ICEBERG_PRECHECK(context.schema != nullptr, "Metadata table schema cannot be 
null");
-  ICEBERG_PRECHECK(context.projected_schema != nullptr,
-                   "Projected schema cannot be null");
+  ICEBERG_RETURN_UNEXPECTED(context.Validate());
   ICEBERG_RETURN_UNEXPECTED(internal::SelectAppendFns<RefRow>(
       *RefsTable::CanonicalSchema(), *context.projected_schema, kRefColumns));
   ICEBERG_ASSIGN_OR_RAISE(auto task,
diff --git a/src/iceberg/inspect/refs_table.h b/src/iceberg/inspect/refs_table.h
index 6135448f..e4188094 100644
--- a/src/iceberg/inspect/refs_table.h
+++ b/src/iceberg/inspect/refs_table.h
@@ -46,11 +46,11 @@ class ICEBERG_EXPORT RefsTable : public MetadataTable {
 
   MetadataTableKind kind() const noexcept override { return 
MetadataTableKind::kRefs; }
 
-  const std::shared_ptr<Schema>& schema() const override;
+  std::shared_ptr<Schema> schema() const override;
 
  protected:
   Result<std::unique_ptr<MetadataScan>> MakeScan(
-      internal::MetadataScanContext context) const override;
+      internal::MetadataScanContext context, std::shared_ptr<FileIO> io) const 
override;
 
  private:
   friend class MetadataScanTaskReader;
diff --git a/src/iceberg/inspect/snapshots_table.cc 
b/src/iceberg/inspect/snapshots_table.cc
index 6903388a..4d8c972f 100644
--- a/src/iceberg/inspect/snapshots_table.cc
+++ b/src/iceberg/inspect/snapshots_table.cc
@@ -100,9 +100,7 @@ SnapshotsTable::SnapshotsTable(std::shared_ptr<const Table> 
table)
 
 SnapshotsTable::~SnapshotsTable() = default;
 
-const std::shared_ptr<Schema>& SnapshotsTable::schema() const {
-  return CanonicalSchema();
-}
+std::shared_ptr<Schema> SnapshotsTable::schema() const { return 
CanonicalSchema(); }
 
 const std::shared_ptr<Schema>& SnapshotsTable::CanonicalSchema() {
   static const auto schema = std::make_shared<Schema>(std::vector<SchemaField>{
@@ -125,7 +123,7 @@ Result<std::unique_ptr<SnapshotsTable>> 
SnapshotsTable::Make(
 }
 
 Result<std::unique_ptr<MetadataScan>> SnapshotsTable::MakeScan(
-    internal::MetadataScanContext context) const {
+    internal::MetadataScanContext context, std::shared_ptr<FileIO> /*io*/) 
const {
   return SnapshotsScan::Make(std::move(context));
 }
 
@@ -164,10 +162,7 @@ Result<std::unique_ptr<SnapshotsScan>> SnapshotsScan::Make(
       context.as_of_time_in_millis.has_value()) {
     return NotSupported("Metadata table does not support time travel");
   }
-  ICEBERG_PRECHECK(context.table_metadata != nullptr, "Table metadata cannot 
be null");
-  ICEBERG_PRECHECK(context.schema != nullptr, "Metadata table schema cannot be 
null");
-  ICEBERG_PRECHECK(context.projected_schema != nullptr,
-                   "Projected schema cannot be null");
+  ICEBERG_RETURN_UNEXPECTED(context.Validate());
   ICEBERG_RETURN_UNEXPECTED(internal::SelectAppendFns<Snapshot>(
       *SnapshotsTable::CanonicalSchema(), *context.projected_schema, 
kSnapshotColumns));
   ICEBERG_ASSIGN_OR_RAISE(auto task,
diff --git a/src/iceberg/inspect/snapshots_table.h 
b/src/iceberg/inspect/snapshots_table.h
index df24b5f3..5c3975e7 100644
--- a/src/iceberg/inspect/snapshots_table.h
+++ b/src/iceberg/inspect/snapshots_table.h
@@ -48,11 +48,11 @@ class ICEBERG_EXPORT SnapshotsTable : public MetadataTable {
     return MetadataTableKind::kSnapshots;
   }
 
-  const std::shared_ptr<Schema>& schema() const override;
+  std::shared_ptr<Schema> schema() const override;
 
  protected:
   Result<std::unique_ptr<MetadataScan>> MakeScan(
-      internal::MetadataScanContext context) const override;
+      internal::MetadataScanContext context, std::shared_ptr<FileIO> io) const 
override;
 
  private:
   friend class MetadataScanTaskReader;
diff --git a/src/iceberg/test/CMakeLists.txt b/src/iceberg/test/CMakeLists.txt
index 1874fc25..59506b16 100644
--- a/src/iceberg/test/CMakeLists.txt
+++ b/src/iceberg/test/CMakeLists.txt
@@ -206,6 +206,7 @@ if(ICEBERG_BUILD_BUNDLE)
   add_iceberg_test(metadata_table_test
                    USE_BUNDLE
                    SOURCES
+                   inspect/metadata_snapshot_scan_test.cc
                    inspect/history_table_test.cc
                    inspect/metadata_table_test.cc
                    inspect/refs_table_test.cc
diff --git a/src/iceberg/test/inspect/metadata_snapshot_scan_test.cc 
b/src/iceberg/test/inspect/metadata_snapshot_scan_test.cc
new file mode 100644
index 00000000..e70e8f2d
--- /dev/null
+++ b/src/iceberg/test/inspect/metadata_snapshot_scan_test.cc
@@ -0,0 +1,252 @@
+/*
+ * 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 <cstdint>
+#include <memory>
+#include <optional>
+#include <utility>
+#include <vector>
+
+#include <arrow/array.h>
+#include <arrow/type.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <nanoarrow/nanoarrow.hpp>
+
+#include "iceberg/inspect/metadata_scan_task_reader.h"
+#include "iceberg/inspect/metadata_scan_util_internal.h"
+#include "iceberg/inspect/metadata_table.h"
+#include "iceberg/inspect/metadata_table_util_internal.h"
+#include "iceberg/partition_spec.h"
+#include "iceberg/schema.h"
+#include "iceberg/schema_field.h"
+#include "iceberg/test/inspect/metadata_table_test_base.h"
+#include "iceberg/test/matchers.h"
+#include "iceberg/transform.h"
+#include "iceberg/type.h"
+
+namespace iceberg::internal {
+namespace {
+
+std::shared_ptr<Schema> IntSchema() {
+  return std::make_shared<Schema>(
+      std::vector<SchemaField>{SchemaField::MakeRequired(1, "id", int64())});
+}
+
+Result<ArrowArrayStream> ReadIntTaskRows(const MetadataScanContext& context,
+                                         const std::shared_ptr<FileIO>& io,
+                                         int64_t batch_size) {
+  ICEBERG_PRECHECK(io != nullptr && context.table_metadata != nullptr,
+                   "Task lost its input owners");
+  const std::vector<MetadataTableColumn<int64_t>> columns{
+      {.field_id = 1, .append = [](ArrowArray* array, const int64_t& row) {
+         return AppendInt(array, row);
+       }}};
+  return MakeMetadataBatchStream<int64_t>(
+      context.schema, context.projected_schema, columns, 3, batch_size,
+      [metadata = context.table_metadata, io](size_t index) {
+        return static_cast<int64_t>(index + 1);
+      });
+}
+
+class TestSnapshotMetadataTable : public MetadataTable {
+ public:
+  explicit TestSnapshotMetadataTable(std::shared_ptr<const Table> table)
+      : MetadataTable(std::move(table)) {}
+
+  MetadataTableKind kind() const noexcept override { return 
MetadataTableKind::kFiles; }
+  std::shared_ptr<Schema> schema() const override { return IntSchema(); }
+
+ protected:
+  Result<std::unique_ptr<MetadataScan>> MakeScan(
+      MetadataScanContext context, std::shared_ptr<FileIO> io) const override {
+    return MakeSnapshotMetadataScan(std::move(context), std::move(io), 
ReadIntTaskRows);
+  }
+};
+
+class SnapshotMetadataSupportTest : public MetadataTableTestBase {
+ protected:
+  MetadataScanContext Context() {
+    auto schema = IntSchema();
+    return {.kind = MetadataTableKind::kFiles,
+            .table_metadata = metadata_,
+            .schema = schema,
+            .projected_schema = schema};
+  }
+};
+
+TEST_F(SnapshotMetadataSupportTest, TasksRetainOwnersAndCanBeReopened) {
+  ICEBERG_UNWRAP_OR_FAIL(auto scan,
+                         MakeSnapshotMetadataScan(Context(), io_, 
ReadIntTaskRows));
+  ICEBERG_UNWRAP_OR_FAIL(auto tasks, scan->PlanTasks());
+  ASSERT_EQ(tasks.size(), 1);
+  scan.reset();
+  table_.reset();
+  metadata_.reset();
+  io_.reset();
+  for (int attempt = 0; attempt < 2; ++attempt) {
+    ICEBERG_UNWRAP_OR_FAIL(auto reader, 
MetadataScanTaskReader::Make({.batch_size = 2}));
+    ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*tasks[0]));
+    reader.reset();
+    ICEBERG_UNWRAP_OR_FAIL(auto batches, ReadAllBatches(std::move(stream)));
+    ASSERT_EQ(batches.size(), 2);
+    EXPECT_EQ(batches[0]->num_rows(), 2);
+    EXPECT_EQ(batches[1]->num_rows(), 1);
+    ASSERT_EQ(batches[0]->column(0)->type_id(), ::arrow::Type::INT64);
+    auto ids = 
std::static_pointer_cast<::arrow::Int64Array>(batches[0]->column(0));
+    EXPECT_EQ(ids->Value(0), 1);
+  }
+}
+
+TEST_F(SnapshotMetadataSupportTest, BuilderCapturesFileIOAcrossRefresh) {
+  TestSnapshotMetadataTable metadata_table(table_);
+  ICEBERG_UNWRAP_OR_FAIL(auto builder, metadata_table.NewScan());
+  std::weak_ptr<FileIO> captured_io = io_;
+
+  ICEBERG_UNWRAP_OR_FAIL(
+      auto refreshed,
+      Table::Make(table_->name(), std::make_shared<TableMetadata>(*metadata_),
+                  "s3://bucket/refreshed.json", std::make_shared<MockFileIO>(),
+                  catalog_));
+  EXPECT_CALL(*catalog_, 
LoadTable(::testing::_)).WillOnce(::testing::Return(refreshed));
+  ASSERT_THAT(table_->Refresh(), IsOk());
+  EXPECT_NE(table_->io().get(), io_.get());
+  io_.reset();
+  EXPECT_FALSE(captured_io.expired());
+
+  ICEBERG_UNWRAP_OR_FAIL(auto scan, builder->Build());
+  ICEBERG_UNWRAP_OR_FAIL(auto tasks, scan->PlanTasks());
+  ASSERT_EQ(tasks.size(), 1);
+  builder.reset();
+  scan.reset();
+  EXPECT_FALSE(captured_io.expired());
+
+  ICEBERG_UNWRAP_OR_FAIL(auto reader, 
MetadataScanTaskReader::Make({.batch_size = 2}));
+  ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*tasks.front()));
+  tasks.clear();
+  reader.reset();
+  EXPECT_FALSE(captured_io.expired());
+  ICEBERG_UNWRAP_OR_FAIL(auto batches, ReadAllBatches(std::move(stream)));
+  ASSERT_EQ(batches.size(), 2);
+  EXPECT_EQ(batches[0]->num_rows(), 2);
+  EXPECT_EQ(batches[1]->num_rows(), 1);
+  EXPECT_TRUE(captured_io.expired());
+}
+
+TEST_F(SnapshotMetadataSupportTest, RejectsMissingInputs) {
+  auto context = Context();
+  context.table_metadata.reset();
+  EXPECT_THAT(MakeSnapshotMetadataScan(context, io_, ReadIntTaskRows),
+              IsError(ErrorKind::kInvalidArgument));
+  context = Context();
+  context.schema.reset();
+  EXPECT_THAT(MakeSnapshotMetadataScan(context, io_, ReadIntTaskRows),
+              IsError(ErrorKind::kInvalidArgument));
+  context = Context();
+  context.projected_schema.reset();
+  EXPECT_THAT(MakeSnapshotMetadataScan(context, io_, ReadIntTaskRows),
+              IsError(ErrorKind::kInvalidArgument));
+  context = Context();
+  EXPECT_THAT(MakeSnapshotMetadataScan(context, nullptr, ReadIntTaskRows),
+              IsError(ErrorKind::kInvalidArgument));
+}
+
+TEST_F(SnapshotMetadataSupportTest, RejectsInvalidProjectionAndReader) {
+  EXPECT_THAT(MakeSnapshotMetadataScan(Context(), io_, nullptr),
+              IsError(ErrorKind::kInvalidArgument));
+  auto context = Context();
+  context.projected_schema = std::make_shared<Schema>(
+      std::vector<SchemaField>{SchemaField::MakeRequired(99, "missing", 
int64())});
+  EXPECT_THAT(MakeSnapshotMetadataScan(context, io_, ReadIntTaskRows),
+              IsError(ErrorKind::kInvalidArgument));
+  context = Context();
+  context.ref_name = "dev";
+  context.snapshot_id = 1;
+  EXPECT_THAT(MakeSnapshotMetadataScan(context, io_, ReadIntTaskRows),
+              IsError(ErrorKind::kInvalidArgument));
+}
+
+TEST_F(SnapshotMetadataSupportTest, ResolvesSnapshotIdsReferencesAndTimes) {
+  auto first = std::make_shared<Snapshot>(
+      Snapshot{.snapshot_id = 10, .timestamp_ms = 
TimePointMsFromUnixMs(1000)});
+  auto second = std::make_shared<Snapshot>(
+      Snapshot{.snapshot_id = 20, .timestamp_ms = 
TimePointMsFromUnixMs(2000)});
+  auto metadata = metadata_;
+  metadata->snapshots = {first, second};
+  metadata->current_snapshot_id = 20;
+  metadata->refs["tag"] = std::make_shared<SnapshotRef>(
+      SnapshotRef{.snapshot_id = 10, .retention = SnapshotRef::Tag{}});
+  metadata->snapshot_log = {
+      {.timestamp_ms = TimePointMsFromUnixMs(1000), .snapshot_id = 10},
+      {.timestamp_ms = TimePointMsFromUnixMs(2000), .snapshot_id = 20}};
+  MetadataScanContext selection{.kind = MetadataTableKind::kFiles};
+  ICEBERG_UNWRAP_OR_FAIL(auto current,
+                         ResolveMetadataTableSnapshot(*metadata, selection));
+  EXPECT_EQ(current, second);
+  selection.snapshot_id = 10;
+  ICEBERG_UNWRAP_OR_FAIL(auto by_id, ResolveMetadataTableSnapshot(*metadata, 
selection));
+  EXPECT_EQ(by_id, first);
+  selection.snapshot_id.reset();
+  selection.ref_name = "tag";
+  ICEBERG_UNWRAP_OR_FAIL(auto by_ref, ResolveMetadataTableSnapshot(*metadata, 
selection));
+  EXPECT_EQ(by_ref, first);
+  selection.ref_name.clear();
+  selection.as_of_time_in_millis = 1500;
+  ICEBERG_UNWRAP_OR_FAIL(auto by_time,
+                         ResolveMetadataTableSnapshot(*metadata, selection));
+  EXPECT_EQ(by_time, first);
+  selection.ref_name = "tag";
+  EXPECT_THAT(ResolveMetadataTableSnapshot(*metadata, selection),
+              IsError(ErrorKind::kInvalidArgument));
+  selection.as_of_time_in_millis.reset();
+  selection.ref_name = "missing";
+  EXPECT_THAT(ResolveMetadataTableSnapshot(*metadata, selection),
+              IsError(ErrorKind::kInvalidArgument));
+}
+
+TEST_F(SnapshotMetadataSupportTest, 
PreservesSnapshotLookupErrorsAndEmptyTables) {
+  auto selection = Context();
+  for (const auto* ref : {"", "main"}) {
+    selection.ref_name = ref;
+    ICEBERG_UNWRAP_OR_FAIL(auto snapshot,
+                           ResolveMetadataTableSnapshot(*metadata_, 
selection));
+    EXPECT_EQ(snapshot, nullptr);
+  }
+
+  selection.ref_name = "missing";
+  EXPECT_THAT(ResolveMetadataTableSnapshot(*metadata_, selection),
+              IsError(ErrorKind::kInvalidArgument));
+  metadata_->refs["null"] = nullptr;
+  selection.ref_name = "null";
+  EXPECT_THAT(ResolveMetadataTableSnapshot(*metadata_, selection),
+              IsError(ErrorKind::kInvalidArgument));
+
+  metadata_->refs["dangling"] = std::make_shared<SnapshotRef>(
+      SnapshotRef{.snapshot_id = 999, .retention = SnapshotRef::Tag{}});
+  selection.ref_name = "dangling";
+  EXPECT_THAT(ResolveMetadataTableSnapshot(*metadata_, selection),
+              IsError(ErrorKind::kNotFound));
+  selection.ref_name = "main";
+  metadata_->current_snapshot_id = 999;
+  EXPECT_THAT(ResolveMetadataTableSnapshot(*metadata_, selection),
+              IsError(ErrorKind::kNotFound));
+}
+
+}  // namespace
+}  // namespace iceberg::internal
diff --git a/src/iceberg/test/inspect/snapshots_table_test.cc 
b/src/iceberg/test/inspect/snapshots_table_test.cc
index b5029dc4..773ab167 100644
--- a/src/iceberg/test/inspect/snapshots_table_test.cc
+++ b/src/iceberg/test/inspect/snapshots_table_test.cc
@@ -32,6 +32,7 @@
 #include <gtest/gtest.h>
 
 #include "iceberg/constants.h"
+#include "iceberg/inspect/metadata_scan_task.h"
 #include "iceberg/inspect/metadata_scan_task_reader.h"
 #include "iceberg/inspect/metadata_table.h"
 #include "iceberg/test/arrow_test_util.h"
@@ -241,6 +242,17 @@ TEST_F(SnapshotsTableTest, ScanProjectedColumns) {
   EXPECT_EQ(snapshot_ids->Value(1), 2);
 }
 
+TEST_F(SnapshotsTableTest, StaticTaskDoesNotRequireFileIO) {
+  ICEBERG_UNWRAP_OR_FAIL(auto task, StaticMetadataTask::Make(
+                                        MetadataTableKind::kSnapshots, 
table_->metadata(),
+                                        SnapshotsTable::CanonicalSchema()));
+  ICEBERG_UNWRAP_OR_FAIL(auto reader, MetadataScanTaskReader::Make({}));
+  ICEBERG_UNWRAP_OR_FAIL(auto stream, reader->Open(*task));
+  ICEBERG_UNWRAP_OR_FAIL(auto batches, ReadAllBatches(std::move(stream)));
+  ASSERT_EQ(batches.size(), 1);
+  EXPECT_EQ(batches.front()->num_rows(), 2);
+}
+
 TEST_F(SnapshotsTableTest, ScanRejectsInvalidProjection) {
   // An optional column cannot be projected as required.
   auto required_parent = std::make_shared<Schema>(
diff --git a/src/iceberg/util/snapshot_util.cc 
b/src/iceberg/util/snapshot_util.cc
index 885189c2..32048b4f 100644
--- a/src/iceberg/util/snapshot_util.cc
+++ b/src/iceberg/util/snapshot_util.cc
@@ -31,6 +31,10 @@
 
 namespace iceberg {
 
+bool SnapshotUtil::IsMainBranch(std::string_view ref) {
+  return ref.empty() || ref == SnapshotRef::kMainBranch;
+}
+
 // Shorthand to return for a NotFound error.
 #define ICEBERG_ACTION_FOR_NOT_FOUND(result, action)     \
   if (!result.has_value()) [[unlikely]] {                \
@@ -372,7 +376,7 @@ Result<std::shared_ptr<Schema>> 
SnapshotUtil::SchemaFor(const Table& table,
 
 Result<std::shared_ptr<Schema>> SnapshotUtil::SchemaFor(const Table& table,
                                                         const std::string& 
ref) {
-  if (ref.empty() || ref == SnapshotRef::kMainBranch) {
+  if (IsMainBranch(ref)) {
     return table.schema();
   }
 
@@ -387,7 +391,7 @@ Result<std::shared_ptr<Schema>> 
SnapshotUtil::SchemaFor(const Table& table,
 
 Result<std::shared_ptr<Schema>> SnapshotUtil::SchemaFor(const TableMetadata& 
metadata,
                                                         const std::string& 
ref) {
-  if (ref.empty() || ref == SnapshotRef::kMainBranch) {
+  if (IsMainBranch(ref)) {
     return metadata.Schema();
   }
 
@@ -411,7 +415,7 @@ Result<std::shared_ptr<Snapshot>> 
SnapshotUtil::LatestSnapshot(
 
 Result<std::shared_ptr<Snapshot>> SnapshotUtil::LatestSnapshot(
     const TableMetadata& metadata, const std::string& branch) {
-  if (branch.empty() || branch == SnapshotRef::kMainBranch) {
+  if (IsMainBranch(branch)) {
     return metadata.Snapshot();
   }
 
diff --git a/src/iceberg/util/snapshot_util.h b/src/iceberg/util/snapshot_util.h
index 5c832d65..f81c7b7b 100644
--- a/src/iceberg/util/snapshot_util.h
+++ b/src/iceberg/util/snapshot_util.h
@@ -26,6 +26,7 @@
 #include <memory>
 #include <optional>
 #include <string>
+#include <string_view>
 #include <vector>
 
 #include "iceberg/iceberg_export.h"
@@ -39,6 +40,10 @@ namespace iceberg {
 /// \note All the returned std::shared_ptr<Snapshot> are guaranteed to be not 
null.
 class ICEBERG_EXPORT SnapshotUtil {
  public:
+  /// \brief Return whether a reference selects the main branch.
+  /// \param ref Reference name (empty string means main branch)
+  static bool IsMainBranch(std::string_view ref);
+
   /// \brief Returns a vector of ancestors of the given snapshot.
   ///
   /// \param table The table

Reply via email to