From 2fba071cfdec20d6bee938d7a7a25148516788b3 Mon Sep 17 00:00:00 2001 From: Aaron Wu Date: Sun, 22 Nov 2026 23:43:30 +0800 Subject: [PATCH 1/4] fix(scan): allocate snapshot buffers from the scan memory pool Generated-by: OpenAI Codex (GPT-6) --- include/paimon/scan_context.h | 2 + src/paimon/common/utils/rapidjson_util.h | 34 +++---- src/paimon/core/snapshot.cpp | 50 +++++++++- src/paimon/core/snapshot.h | 4 +- .../table/append_only_file_store_table.cpp | 5 +- src/paimon/core/table/file_store_table.h | 5 +- .../table/primary_key_file_store_table.cpp | 8 +- .../source/scan_exception_safety_test.cpp | 99 ++++++++++++++++++- src/paimon/core/utils/snapshot_manager.cpp | 10 +- src/paimon/core/utils/snapshot_manager.h | 3 +- .../utils/counting_reader_file_system.h | 17 +++- 11 files changed, 195 insertions(+), 42 deletions(-) diff --git a/include/paimon/scan_context.h b/include/paimon/scan_context.h index 93f3ba2db..61af8a78e 100644 --- a/include/paimon/scan_context.h +++ b/include/paimon/scan_context.h @@ -251,6 +251,8 @@ class PAIMON_EXPORT ScanContextBuilder { /// @param memory_pool The memory pool to use. /// @return Reference to this builder for method chaining. /// @note if not set, memory_pool is default pool + /// With a custom pool, native data scans load numbered snapshot files through FileSystem::Open + /// into a buffer allocated from that pool. /// A custom pool controls only allocations routed through it, not all planning memory. /// Keep it alive while any plan, split, cache entry, or executor task can retain its /// allocations; destroying the scan alone does not release all such objects. diff --git a/src/paimon/common/utils/rapidjson_util.h b/src/paimon/common/utils/rapidjson_util.h index bac1b9ba0..1096e8041 100644 --- a/src/paimon/common/utils/rapidjson_util.h +++ b/src/paimon/common/utils/rapidjson_util.h @@ -75,19 +75,27 @@ class RapidJsonUtil { // if T is custom type, T must have FromJson() template static inline Status FromJsonString(const std::string& json_str, T* obj) { + return FromNullTerminatedJson(json_str, obj, json_str); + } + + // The view excludes the final NUL, which must follow it in the backing buffer. + template + static inline Status FromNullTerminatedJson(std::string_view json_str, T* obj, + std::string_view diagnostic) { if (!obj) { return Status::Invalid("deserialize failed: obj is nullptr"); } // RapidJSON treats an unescaped NUL as end-of-input, even with an explicit length. - if (json_str.find('\0') != std::string::npos) { + if (json_str.find('\0') != std::string_view::npos) { return Status::Invalid("deserialize failed: JSON contains an unescaped NUL byte"); } if constexpr (std::is_same_v>) { - PAIMON_ASSIGN_OR_RAISE(*obj, MapFromJsonString(json_str)); + PAIMON_ASSIGN_OR_RAISE(*obj, MapFromJsonString(json_str.data(), diagnostic)); } else { rapidjson::Document doc; - if (!FromJson(json_str, &doc)) { - return Status::Invalid("deserialize failed: ", json_str); + doc.Parse(json_str.data()); + if (doc.HasParseError()) { + return Status::Invalid("deserialize failed: ", diagnostic); } try { obj->FromJson(doc); @@ -95,7 +103,7 @@ class RapidJsonUtil { return Status::Invalid("deserialize failed, possibly type incompatible: ", e.what()); } catch (...) { - return Status::Invalid("deserialize failed, reason unknown: ", json_str); + return Status::Invalid("deserialize failed, reason unknown: ", diagnostic); } } return Status::OK(); @@ -137,14 +145,6 @@ class RapidJsonUtil { return true; } - static inline bool FromJson(const std::string& json_str, rapidjson::Document* doc) { - doc->Parse(json_str.c_str()); - if (doc->HasParseError()) { - return false; - } - return true; - } - template static rapidjson::Value SerializeMap(const T& map, rapidjson::Document::AllocatorType* allocator); @@ -179,19 +179,19 @@ class RapidJsonUtil { return buffer.GetString(); } static Result> MapFromJsonString( - const std::string& json_str) { + const char* json_str, std::string_view diagnostic) { rapidjson::Document doc; - doc.Parse(json_str.c_str()); + doc.Parse(json_str); if (doc.HasParseError() || !doc.IsObject()) { return Status::Invalid("deserialize failed: parse error or not JSON object: ", - json_str); + diagnostic); } std::map result; for (auto it = doc.MemberBegin(); it != doc.MemberEnd(); ++it) { if (!it->name.IsString() || !it->value.IsString()) { return Status::Invalid( - "deserialize failed: non-string key or value in JSON object: ", json_str); + "deserialize failed: non-string key or value in JSON object: ", diagnostic); } result[it->name.GetString()] = it->value.GetString(); } diff --git a/src/paimon/core/snapshot.cpp b/src/paimon/core/snapshot.cpp index 6b27c8fa1..964cbb8c7 100644 --- a/src/paimon/core/snapshot.cpp +++ b/src/paimon/core/snapshot.cpp @@ -19,14 +19,23 @@ #include "paimon/core/snapshot.h" #include +#include +#include +#include #include #include +#include #include +#include "fmt/format.h" +#include "paimon/common/utils/math.h" #include "paimon/common/utils/rapidjson_util.h" +#include "paimon/common/utils/scope_guard.h" #include "paimon/common/utils/uuid.h" #include "paimon/fs/file_system.h" #include "paimon/macros.h" +#include "paimon/memory/bytes.h" +#include "paimon/memory/memory_pool.h" #include "paimon/result.h" #include "paimon/status.h" #include "rapidjson/allocators.h" @@ -323,11 +332,42 @@ void Snapshot::FromJson(const rapidjson::Value& obj) noexcept(false) { RapidJsonUtil::DeserializeKeyValue>(obj, FIELD_NEXT_ROW_ID); } -Result Snapshot::FromPath(const std::shared_ptr& fs, - const std::string& path) { - std::string json_str; - PAIMON_RETURN_NOT_OK(fs->ReadFile(path, &json_str)); - PAIMON_ASSIGN_OR_RAISE(Snapshot snapshot, Snapshot::FromJsonString(json_str)); +Result Snapshot::FromPath(const std::shared_ptr& fs, const std::string& path, + MemoryPool* pool) { + if (pool == nullptr || pool == GetDefaultPool().get()) { + std::string json_str; + PAIMON_RETURN_NOT_OK(fs->ReadFile(path, &json_str)); + return Snapshot::FromJsonString(json_str); + } + + Bytes json; + { + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr input, fs->Open(path)); + if (input == nullptr) { + return Status::Invalid("input stream is not suppose to be a null pointer, path: ", + path); + } + ScopeGuard close([&input]() { (void)input->Close(); }); + PAIMON_ASSIGN_OR_RAISE(int64_t length, input->Length()); + PAIMON_RETURN_NOT_OK(ValidateValueNonNegative(length, "read length")); + const uint64_t allocation_size = static_cast(length) + 1; + PAIMON_RETURN_NOT_OK(ValidateValueInRange(allocation_size, "snapshot buffer size")); + try { + json = Bytes(static_cast(allocation_size), pool); + } catch (const std::bad_alloc&) { + return Status::OutOfMemory("cannot allocate ", allocation_size, " bytes for snapshot ", + path); + } + PAIMON_ASSIGN_OR_RAISE(int64_t read_length, input->Read(json.data(), length)); + if (read_length != length) { + return Status::IOError(fmt::format("path {}, expect read len {}, actual read len {}", + path, length, read_length)); + } + json.data()[length] = '\0'; + } + Snapshot snapshot; + PAIMON_RETURN_NOT_OK(RapidJsonUtil::FromNullTerminatedJson( + std::string_view(json.data(), json.size() - 1), &snapshot, path)); return snapshot; } diff --git a/src/paimon/core/snapshot.h b/src/paimon/core/snapshot.h index 31adc6b13..235528150 100644 --- a/src/paimon/core/snapshot.h +++ b/src/paimon/core/snapshot.h @@ -242,8 +242,8 @@ class Snapshot : public Jsonizable { void FromJson(const rapidjson::Value& obj) noexcept(false) override; - static Result FromPath(const std::shared_ptr& fs, - const std::string& path); + static Result FromPath(const std::shared_ptr& fs, const std::string& path, + MemoryPool* pool = nullptr); private: // version of snapshot diff --git a/src/paimon/core/table/append_only_file_store_table.cpp b/src/paimon/core/table/append_only_file_store_table.cpp index b8e3906f6..4a23f17a1 100644 --- a/src/paimon/core/table/append_only_file_store_table.cpp +++ b/src/paimon/core/table/append_only_file_store_table.cpp @@ -158,16 +158,17 @@ Result> AppendOnlyFileStoreTable::NewFileStoreSca const ScanContext* context) const { // TODO(liancheng.lsz): support fallback branch in scan std::shared_ptr table_schema = checked_pointer_cast(schema_); + const auto snapshot_manager = GetSnapshotManager(memory_pool); std::unique_ptr scan; if (core_options.DataEvolutionEnabled()) { PAIMON_ASSIGN_OR_RAISE( - scan, DataEvolutionFileStoreScan::Create(GetSnapshotManager(), GetSchemaManager(), + scan, DataEvolutionFileStoreScan::Create(snapshot_manager, GetSchemaManager(), manifest_list, manifest_file, table_schema, arrow_schema, context->GetScanFilters(), core_options, executor, memory_pool)); } else { PAIMON_ASSIGN_OR_RAISE( - scan, AppendOnlyFileStoreScan::Create(GetSnapshotManager(), GetSchemaManager(), + scan, AppendOnlyFileStoreScan::Create(snapshot_manager, GetSchemaManager(), manifest_list, manifest_file, table_schema, arrow_schema, context->GetScanFilters(), core_options, executor, memory_pool)); diff --git a/src/paimon/core/table/file_store_table.h b/src/paimon/core/table/file_store_table.h index e9e34adf6..6aefe868f 100644 --- a/src/paimon/core/table/file_store_table.h +++ b/src/paimon/core/table/file_store_table.h @@ -76,8 +76,9 @@ class FileStoreTable : public Table { return schema_manager_; } - std::shared_ptr GetSnapshotManager() const { - return std::make_shared(file_system_, root_path_, CurrentBranch()); + std::shared_ptr GetSnapshotManager( + const std::shared_ptr& pool = nullptr) const { + return std::make_shared(file_system_, root_path_, CurrentBranch(), pool); } std::string Name() const override { diff --git a/src/paimon/core/table/primary_key_file_store_table.cpp b/src/paimon/core/table/primary_key_file_store_table.cpp index 54b31e585..2dd74fdf4 100644 --- a/src/paimon/core/table/primary_key_file_store_table.cpp +++ b/src/paimon/core/table/primary_key_file_store_table.cpp @@ -233,10 +233,10 @@ Result> PrimaryKeyFileStoreTable::NewFileStoreSca std::shared_ptr table_schema = checked_pointer_cast(schema_); std::unique_ptr scan; PAIMON_ASSIGN_OR_RAISE( - scan, KeyValueFileStoreScan::Create(GetSnapshotManager(), GetSchemaManager(), manifest_list, - manifest_file, table_schema, arrow_schema, - context->GetScanFilters(), core_options, executor, - memory_pool)); + scan, KeyValueFileStoreScan::Create(GetSnapshotManager(memory_pool), GetSchemaManager(), + manifest_list, manifest_file, table_schema, + arrow_schema, context->GetScanFilters(), core_options, + executor, memory_pool)); return WithTablePath(std::move(scan), root_path_); } diff --git a/src/paimon/core/table/source/scan_exception_safety_test.cpp b/src/paimon/core/table/source/scan_exception_safety_test.cpp index 246ab10f7..33fe5bded 100644 --- a/src/paimon/core/table/source/scan_exception_safety_test.cpp +++ b/src/paimon/core/table/source/scan_exception_safety_test.cpp @@ -16,6 +16,7 @@ * limitations under the License. */ +#include #include #include #include @@ -35,9 +36,11 @@ #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/executor.h" #include "paimon/fs/local/local_file_system.h" +#include "paimon/memory/bytes.h" #include "paimon/memory/memory_pool.h" #include "paimon/scan_context.h" #include "paimon/table/source/table_scan.h" +#include "paimon/testing/utils/counting_reader_file_system.h" #include "paimon/testing/utils/testharness.h" namespace paimon::test { @@ -55,15 +58,18 @@ class InlinePlanningExecutor final : public Executor { class PlanningFaultPool final : public MemoryPool { public: + explicit PlanningFaultPool(uint64_t capacity = std::numeric_limits::max()) + : capacity_(capacity) {} + void* Malloc(uint64_t size, uint64_t alignment) override { std::lock_guard lock(mutex_); - Check(); + Check(size); ++malloc_calls; return upstream_->Malloc(size, alignment); } void* Realloc(void* pointer, size_t old_size, size_t new_size, uint64_t alignment) override { std::lock_guard lock(mutex_); - Check(); + Check(new_size - std::min(old_size, new_size)); ++realloc_calls; return upstream_->Realloc(pointer, old_size, new_size, alignment); } @@ -86,14 +92,20 @@ class PlanningFaultPool final : public MemoryPool { std::atomic malloc_calls{0}; std::atomic realloc_calls{0}; std::atomic rejected{false}; + std::atomic refused_bytes{0}; private: - void Check() { + void Check(uint64_t additional_bytes) { if (calls.fetch_add(1) == fail_at.load()) { rejected = true; throw std::bad_alloc(); } + if (additional_bytes > capacity_ - upstream_->CurrentUsage()) { + refused_bytes = additional_bytes; + throw std::bad_alloc(); + } } + const uint64_t capacity_; std::unique_ptr upstream_ = GetMemoryPool(); std::mutex mutex_; }; @@ -108,6 +120,7 @@ struct PlanningInput { std::shared_ptr cache; std::optional bucket; std::shared_ptr file_system; + std::optional scan_mode; }; Result> OrdinaryScan( @@ -120,6 +133,7 @@ Result> OrdinaryScan( ScanContextBuilder builder(input.path); builder.SetTableSchema(schema).WithMemoryPool(pool).WithExecutor(executor).AddOption( "scan.snapshot-id", input.snapshot); + if (input.scan_mode) builder.AddOption("scan.mode", *input.scan_mode); if (input.cache) { builder.WithCache(input.cache) .AddOption("scan.manifest-entry-cache.max-snapshots", "8") @@ -291,6 +305,85 @@ TEST(ScanExceptionSafetyTest, RetainedSplitRemainsUsableWithCallerOwnedPool) { EXPECT_EQ(pool->CurrentUsage(), 0); } +TEST(ScanExceptionSafetyTest, SnapshotBufferUsesScanPoolBeforeReading) { + // Leave headroom for the fixture's manifest readers on the successful path. + constexpr size_t kPoolCapacity = 8 * 1024 * 1024; + auto temp_dir = UniqueTestDirectory::Create(); + ASSERT_NE(temp_dir, nullptr); + PlanningInput input; + input.path = temp_dir->Str(); + ASSERT_TRUE(TestUtil::CopyDirectory(PlanningFixture(), input.path)); + const std::string snapshot_path = input.path + "/snapshot/snapshot-1"; + auto fs = std::make_shared("/snapshot/snapshot-1"); + input.file_system = fs; + input.scan_mode = "from-snapshot-full"; + std::string snapshot_json; + ASSERT_OK(fs->ReadFile(snapshot_path, &snapshot_json)); + auto pool = std::make_shared(kPoolCapacity); + auto executor = std::make_shared(); + + std::string oversized_snapshot = snapshot_json; + // The file fits in an empty pool, but other query memory has already been admitted. + oversized_snapshot.resize(kPoolCapacity / 2 + 1, ' '); + ASSERT_OK(fs->WriteFile(snapshot_path, oversized_snapshot, /*overwrite=*/true)); + { + Bytes existing_buffer(kPoolCapacity / 2, pool.get()); + ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); + const auto usage_before = pool->CurrentUsage(); + const auto opens_before = fs->counts->opens.load(); + const auto closes_before = fs->counts->closes.load(); + const auto reads_before = fs->counts->reads.load(); + auto plan = scan->CreatePlan(); + EXPECT_FALSE(plan.ok()); + EXPECT_TRUE(plan.status().IsOutOfMemory()) << plan.status(); + EXPECT_EQ(pool->refused_bytes.load(), oversized_snapshot.size() + 1); + EXPECT_LE(pool->MaxMemoryUsage(), kPoolCapacity); + EXPECT_EQ(fs->counts->opens.load(), opens_before + 1); + EXPECT_EQ(fs->counts->closes.load(), closes_before + 1); + EXPECT_EQ(fs->counts->reads.load(), reads_before); + EXPECT_EQ(fs->counts->live.load(), 0); + EXPECT_EQ(pool->CurrentUsage(), usage_before); + } + EXPECT_EQ(pool->CurrentUsage(), 0); + + ASSERT_OK(fs->WriteFile(snapshot_path, snapshot_json + '\0', /*overwrite=*/true)); + { + ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); + const auto usage_before = pool->CurrentUsage(); + auto plan = scan->CreatePlan(); + EXPECT_TRUE(plan.status().IsInvalid()) << plan.status(); + EXPECT_EQ(fs->counts->live.load(), 0); + EXPECT_EQ(pool->CurrentUsage(), usage_before); + } + EXPECT_EQ(pool->CurrentUsage(), 0); + + ASSERT_OK(fs->WriteFile(snapshot_path, snapshot_json, /*overwrite=*/true)); + fs->length_override = static_cast(snapshot_json.size()) + 1; + { + ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); + const auto usage_before = pool->CurrentUsage(); + const auto closes_before = fs->counts->closes.load(); + auto plan = scan->CreatePlan(); + EXPECT_TRUE(plan.status().IsIOError()) << plan.status(); + EXPECT_EQ(fs->counts->closes.load(), closes_before + 1); + EXPECT_EQ(fs->counts->live.load(), 0); + EXPECT_EQ(pool->CurrentUsage(), usage_before); + } + EXPECT_EQ(pool->CurrentUsage(), 0); + + fs->length_override.reset(); + const auto reads_before = fs->counts->reads.load(); + { + ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); + ASSERT_OK_AND_ASSIGN(auto plan, scan->CreatePlan()); + EXPECT_EQ(plan->SnapshotId(), 1); + EXPECT_FALSE(plan->Splits().empty()); + } + EXPECT_EQ(fs->counts->reads.load(), reads_before + 1); + EXPECT_EQ(fs->counts->live.load(), 0); + EXPECT_EQ(pool->CurrentUsage(), 0); +} + TEST(ScanExceptionSafetyTest, RefusedArrowReallocationPreservesExistingBuffer) { auto pool = std::make_shared(); auto arrow_pool = GetArrowPool(pool); diff --git a/src/paimon/core/utils/snapshot_manager.cpp b/src/paimon/core/utils/snapshot_manager.cpp index 3e6c85eaa..f7981d4f0 100644 --- a/src/paimon/core/utils/snapshot_manager.cpp +++ b/src/paimon/core/utils/snapshot_manager.cpp @@ -40,8 +40,12 @@ SnapshotManager::SnapshotManager(const std::shared_ptr& fs, : SnapshotManager(fs, root_path, BranchManager::DEFAULT_MAIN_BRANCH) {} SnapshotManager::SnapshotManager(const std::shared_ptr& fs, - const std::string& root_path, const std::string& branch) - : fs_(fs), root_path_(root_path), branch_(BranchManager::NormalizeBranch(branch)) {} + const std::string& root_path, const std::string& branch, + const std::shared_ptr& pool) + : fs_(fs), + root_path_(root_path), + branch_(BranchManager::NormalizeBranch(branch)), + pool_(pool) {} SnapshotManager::~SnapshotManager() = default; @@ -124,7 +128,7 @@ bool SnapshotManager::ExpiredSinceBoundaryWasRead(int64_t id) const { } Result SnapshotManager::LoadSnapshot(int64_t snapshot_id) const { - return Snapshot::FromPath(fs_, SnapshotPath(snapshot_id)); + return Snapshot::FromPath(fs_, SnapshotPath(snapshot_id), pool_.get()); } void SnapshotManager::SetSnapshotLoader(SnapshotLoader loader) { diff --git a/src/paimon/core/utils/snapshot_manager.h b/src/paimon/core/utils/snapshot_manager.h index 5b346fe91..ee3f195cd 100644 --- a/src/paimon/core/utils/snapshot_manager.h +++ b/src/paimon/core/utils/snapshot_manager.h @@ -48,7 +48,7 @@ class SnapshotManager { SnapshotManager(const std::shared_ptr& fs, const std::string& root_path); SnapshotManager(const std::shared_ptr& fs, const std::string& root_path, - const std::string& branch); + const std::string& branch, const std::shared_ptr& pool = nullptr); ~SnapshotManager(); /// Sets the loader for `LatestSnapshot()` and `LatestSnapshotId()`. @@ -126,6 +126,7 @@ class SnapshotManager { std::string root_path_; std::string branch_; SnapshotLoader snapshot_loader_; + std::shared_ptr pool_; }; } // namespace paimon diff --git a/src/paimon/testing/utils/counting_reader_file_system.h b/src/paimon/testing/utils/counting_reader_file_system.h index e93daae76..e4c07e06e 100644 --- a/src/paimon/testing/utils/counting_reader_file_system.h +++ b/src/paimon/testing/utils/counting_reader_file_system.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include @@ -35,6 +36,7 @@ class CountingReaderFileSystem : public LocalFileSystem { public: struct Counts { std::atomic opens = 0; + std::atomic closes = 0; std::atomic live = 0; std::atomic peak = 0; std::atomic reads = 0; @@ -54,17 +56,21 @@ class CountingReaderFileSystem : public LocalFileSystem { PAIMON_RETURN_NOT_OK(before_open(path)); } PAIMON_ASSIGN_OR_RAISE(std::unique_ptr input, LocalFileSystem::Open(path)); - return std::make_unique(std::move(input), counts); + return std::make_unique(std::move(input), counts, length_override); } std::shared_ptr counts = std::make_shared(); std::function before_open; + std::optional length_override; private: class CountedInput : public InputStream { public: - CountedInput(std::unique_ptr input, std::shared_ptr counts) - : input_(std::move(input)), counts_(std::move(counts)) { + CountedInput(std::unique_ptr input, std::shared_ptr counts, + std::optional length_override) + : input_(std::move(input)), + counts_(std::move(counts)), + length_override_(length_override) { const uint64_t live = ++counts_->live; uint64_t peak = counts_->peak.load(); while (peak < live && !counts_->peak.compare_exchange_weak(peak, live)) { @@ -74,6 +80,7 @@ class CountingReaderFileSystem : public LocalFileSystem { counts_->live--; } Status Close() override { + counts_->closes++; return input_->Close(); } Status Seek(int64_t offset, SeekOrigin origin) override { @@ -110,12 +117,16 @@ class CountingReaderFileSystem : public LocalFileSystem { return input_->GetUri(); } Result Length() const override { + if (length_override_) { + return *length_override_; + } return input_->Length(); } private: std::unique_ptr input_; std::shared_ptr counts_; + std::optional length_override_; }; std::string suffix_; From dfefccce67890d255fd524fb21ee16fcea022918 Mon Sep 17 00:00:00 2001 From: Aaron Wu Date: Sun, 22 Nov 2026 23:56:40 +0800 Subject: [PATCH 2/4] fix(scan): preserve JSON helper and exercise short snapshot reads Generated-by: OpenAI Codex (GPT-6) --- src/paimon/common/utils/rapidjson_util.h | 12 ++++++++++-- .../table/source/scan_exception_safety_test.cpp | 5 +++-- .../testing/utils/counting_reader_file_system.h | 17 +++++++++-------- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/paimon/common/utils/rapidjson_util.h b/src/paimon/common/utils/rapidjson_util.h index 1096e8041..1096bca60 100644 --- a/src/paimon/common/utils/rapidjson_util.h +++ b/src/paimon/common/utils/rapidjson_util.h @@ -93,8 +93,7 @@ class RapidJsonUtil { PAIMON_ASSIGN_OR_RAISE(*obj, MapFromJsonString(json_str.data(), diagnostic)); } else { rapidjson::Document doc; - doc.Parse(json_str.data()); - if (doc.HasParseError()) { + if (!FromJson(json_str.data(), &doc)) { return Status::Invalid("deserialize failed: ", diagnostic); } try { @@ -145,6 +144,15 @@ class RapidJsonUtil { return true; } + static inline bool FromJson(const std::string& json_str, rapidjson::Document* doc) { + return FromJson(json_str.c_str(), doc); + } + + static inline bool FromJson(const char* json_str, rapidjson::Document* doc) { + doc->Parse(json_str); + return !doc->HasParseError(); + } + template static rapidjson::Value SerializeMap(const T& map, rapidjson::Document::AllocatorType* allocator); diff --git a/src/paimon/core/table/source/scan_exception_safety_test.cpp b/src/paimon/core/table/source/scan_exception_safety_test.cpp index 33fe5bded..f209ec3ca 100644 --- a/src/paimon/core/table/source/scan_exception_safety_test.cpp +++ b/src/paimon/core/table/source/scan_exception_safety_test.cpp @@ -358,20 +358,21 @@ TEST(ScanExceptionSafetyTest, SnapshotBufferUsesScanPoolBeforeReading) { EXPECT_EQ(pool->CurrentUsage(), 0); ASSERT_OK(fs->WriteFile(snapshot_path, snapshot_json, /*overwrite=*/true)); - fs->length_override = static_cast(snapshot_json.size()) + 1; + fs->sequential_read_limit = static_cast(snapshot_json.size()) - 1; { ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); const auto usage_before = pool->CurrentUsage(); const auto closes_before = fs->counts->closes.load(); auto plan = scan->CreatePlan(); EXPECT_TRUE(plan.status().IsIOError()) << plan.status(); + ASSERT_NOK_WITH_MSG(plan.status(), "expect read len"); EXPECT_EQ(fs->counts->closes.load(), closes_before + 1); EXPECT_EQ(fs->counts->live.load(), 0); EXPECT_EQ(pool->CurrentUsage(), usage_before); } EXPECT_EQ(pool->CurrentUsage(), 0); - fs->length_override.reset(); + fs->sequential_read_limit.reset(); const auto reads_before = fs->counts->reads.load(); { ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); diff --git a/src/paimon/testing/utils/counting_reader_file_system.h b/src/paimon/testing/utils/counting_reader_file_system.h index e4c07e06e..e83d4edbd 100644 --- a/src/paimon/testing/utils/counting_reader_file_system.h +++ b/src/paimon/testing/utils/counting_reader_file_system.h @@ -19,6 +19,7 @@ #pragma once +#include #include #include #include @@ -56,21 +57,21 @@ class CountingReaderFileSystem : public LocalFileSystem { PAIMON_RETURN_NOT_OK(before_open(path)); } PAIMON_ASSIGN_OR_RAISE(std::unique_ptr input, LocalFileSystem::Open(path)); - return std::make_unique(std::move(input), counts, length_override); + return std::make_unique(std::move(input), counts, sequential_read_limit); } std::shared_ptr counts = std::make_shared(); std::function before_open; - std::optional length_override; + std::optional sequential_read_limit; private: class CountedInput : public InputStream { public: CountedInput(std::unique_ptr input, std::shared_ptr counts, - std::optional length_override) + std::optional sequential_read_limit) : input_(std::move(input)), counts_(std::move(counts)), - length_override_(length_override) { + sequential_read_limit_(sequential_read_limit) { const uint64_t live = ++counts_->live; uint64_t peak = counts_->peak.load(); while (peak < live && !counts_->peak.compare_exchange_weak(peak, live)) { @@ -91,6 +92,9 @@ class CountingReaderFileSystem : public LocalFileSystem { } Result Read(char* buffer, int64_t size) override { counts_->reads++; + if (sequential_read_limit_) { + size = std::min(size, *sequential_read_limit_); + } PAIMON_ASSIGN_OR_RAISE(int64_t bytes, input_->Read(buffer, size)); counts_->bytes += bytes; return bytes; @@ -117,16 +121,13 @@ class CountingReaderFileSystem : public LocalFileSystem { return input_->GetUri(); } Result Length() const override { - if (length_override_) { - return *length_override_; - } return input_->Length(); } private: std::unique_ptr input_; std::shared_ptr counts_; - std::optional length_override_; + std::optional sequential_read_limit_; }; std::string suffix_; From bcf77e50cc73388df95cf7275c66c4b6a11e5204 Mon Sep 17 00:00:00 2001 From: Aaron Wu Date: Sun, 22 Nov 2026 23:57:55 +0800 Subject: [PATCH 3/4] test(scan): verify the default snapshot read path Generated-by: OpenAI Codex (GPT-6) --- .../table/source/scan_exception_safety_test.cpp | 13 +++++++++++-- .../testing/utils/counting_reader_file_system.h | 8 ++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/paimon/core/table/source/scan_exception_safety_test.cpp b/src/paimon/core/table/source/scan_exception_safety_test.cpp index f209ec3ca..d95388d6c 100644 --- a/src/paimon/core/table/source/scan_exception_safety_test.cpp +++ b/src/paimon/core/table/source/scan_exception_safety_test.cpp @@ -131,8 +131,9 @@ Result> OrdinaryScan( std::string schema{std::istreambuf_iterator(schema_file), std::istreambuf_iterator()}; ScanContextBuilder builder(input.path); - builder.SetTableSchema(schema).WithMemoryPool(pool).WithExecutor(executor).AddOption( - "scan.snapshot-id", input.snapshot); + builder.SetTableSchema(schema).WithExecutor(executor).AddOption("scan.snapshot-id", + input.snapshot); + if (pool) builder.WithMemoryPool(pool); if (input.scan_mode) builder.AddOption("scan.mode", *input.scan_mode); if (input.cache) { builder.WithCache(input.cache) @@ -374,6 +375,7 @@ TEST(ScanExceptionSafetyTest, SnapshotBufferUsesScanPoolBeforeReading) { fs->sequential_read_limit.reset(); const auto reads_before = fs->counts->reads.load(); + const auto read_file_calls_before = fs->counts->read_file_calls.load(); { ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); ASSERT_OK_AND_ASSIGN(auto plan, scan->CreatePlan()); @@ -381,8 +383,15 @@ TEST(ScanExceptionSafetyTest, SnapshotBufferUsesScanPoolBeforeReading) { EXPECT_FALSE(plan->Splits().empty()); } EXPECT_EQ(fs->counts->reads.load(), reads_before + 1); + EXPECT_EQ(fs->counts->read_file_calls.load(), read_file_calls_before); EXPECT_EQ(fs->counts->live.load(), 0); EXPECT_EQ(pool->CurrentUsage(), 0); + + ASSERT_OK_AND_ASSIGN(auto default_scan, OrdinaryScan(nullptr, executor, input)); + ASSERT_OK_AND_ASSIGN(auto default_plan, default_scan->CreatePlan()); + EXPECT_EQ(default_plan->SnapshotId(), 1); + EXPECT_FALSE(default_plan->Splits().empty()); + EXPECT_EQ(fs->counts->read_file_calls.load(), read_file_calls_before + 1); } TEST(ScanExceptionSafetyTest, RefusedArrowReallocationPreservesExistingBuffer) { diff --git a/src/paimon/testing/utils/counting_reader_file_system.h b/src/paimon/testing/utils/counting_reader_file_system.h index e83d4edbd..1dbd1dd83 100644 --- a/src/paimon/testing/utils/counting_reader_file_system.h +++ b/src/paimon/testing/utils/counting_reader_file_system.h @@ -42,12 +42,20 @@ class CountingReaderFileSystem : public LocalFileSystem { std::atomic peak = 0; std::atomic reads = 0; std::atomic bytes = 0; + std::atomic read_file_calls = 0; }; explicit CountingReaderFileSystem(std::string suffix) : suffix_(std::move(suffix)) {} using LocalFileSystem::Open; + Status ReadFile(const std::string& path, std::string* content) override { + if (StringUtils::EndsWith(path, suffix_)) { + counts->read_file_calls++; + } + return LocalFileSystem::ReadFile(path, content); + } + Result> Open(const std::string& path) const override { if (!StringUtils::EndsWith(path, suffix_)) { return LocalFileSystem::Open(path); From 2bf362ac98ae74ddf47a4b3205bac35fd81ace2c Mon Sep 17 00:00:00 2001 From: Aaron Wu Date: Mon, 23 Nov 2026 22:21:11 +0800 Subject: [PATCH 4/4] fix(scan): make snapshot pool routing explicit Generated-by: OpenAI Codex (GPT-6) --- include/paimon/scan_context.h | 2 - src/paimon/common/utils/rapidjson_util.h | 80 ++++++++++++------- .../common/utils/rapidjson_util_test.cpp | 20 +++++ src/paimon/core/snapshot.cpp | 32 ++++---- src/paimon/core/snapshot.h | 4 +- .../table/append_only_file_store_table.cpp | 2 +- src/paimon/core/table/file_store_table.h | 8 +- .../table/primary_key_file_store_table.cpp | 8 +- .../source/scan_exception_safety_test.cpp | 14 +++- src/paimon/core/utils/snapshot_manager.cpp | 17 ++-- src/paimon/core/utils/snapshot_manager.h | 4 +- 11 files changed, 130 insertions(+), 61 deletions(-) diff --git a/include/paimon/scan_context.h b/include/paimon/scan_context.h index 61af8a78e..93f3ba2db 100644 --- a/include/paimon/scan_context.h +++ b/include/paimon/scan_context.h @@ -251,8 +251,6 @@ class PAIMON_EXPORT ScanContextBuilder { /// @param memory_pool The memory pool to use. /// @return Reference to this builder for method chaining. /// @note if not set, memory_pool is default pool - /// With a custom pool, native data scans load numbered snapshot files through FileSystem::Open - /// into a buffer allocated from that pool. /// A custom pool controls only allocations routed through it, not all planning memory. /// Keep it alive while any plan, split, cache entry, or executor task can retain its /// allocations; destroying the scan alone does not release all such objects. diff --git a/src/paimon/common/utils/rapidjson_util.h b/src/paimon/common/utils/rapidjson_util.h index 1096bca60..77e72a3c6 100644 --- a/src/paimon/common/utils/rapidjson_util.h +++ b/src/paimon/common/utils/rapidjson_util.h @@ -34,6 +34,7 @@ #include "rapidjson/allocators.h" #include "rapidjson/document.h" #include "rapidjson/encodings.h" +#include "rapidjson/memorystream.h" #include "rapidjson/prettywriter.h" #include "rapidjson/rapidjson.h" #include "rapidjson/stringbuffer.h" @@ -75,39 +76,48 @@ class RapidJsonUtil { // if T is custom type, T must have FromJson() template static inline Status FromJsonString(const std::string& json_str, T* obj) { - return FromNullTerminatedJson(json_str, obj, json_str); - } - - // The view excludes the final NUL, which must follow it in the backing buffer. - template - static inline Status FromNullTerminatedJson(std::string_view json_str, T* obj, - std::string_view diagnostic) { if (!obj) { return Status::Invalid("deserialize failed: obj is nullptr"); } // RapidJSON treats an unescaped NUL as end-of-input, even with an explicit length. - if (json_str.find('\0') != std::string_view::npos) { + if (json_str.find('\0') != std::string::npos) { return Status::Invalid("deserialize failed: JSON contains an unescaped NUL byte"); } if constexpr (std::is_same_v>) { - PAIMON_ASSIGN_OR_RAISE(*obj, MapFromJsonString(json_str.data(), diagnostic)); + PAIMON_ASSIGN_OR_RAISE(*obj, MapFromJsonString(json_str)); } else { rapidjson::Document doc; - if (!FromJson(json_str.data(), &doc)) { - return Status::Invalid("deserialize failed: ", diagnostic); - } - try { - obj->FromJson(doc); - } catch (const std::invalid_argument& e) { - return Status::Invalid("deserialize failed, possibly type incompatible: ", - e.what()); - } catch (...) { - return Status::Invalid("deserialize failed, reason unknown: ", diagnostic); + if (!FromJson(json_str, &doc)) { + return Status::Invalid("deserialize failed: ", json_str); } + return DeserializeObject(doc, json_str, obj); } return Status::OK(); } + // T must have FromJson(). The view need not be NUL-terminated. + template + static Status FromJsonView(std::string_view json, std::string_view diagnostic, T* obj) { + if (!obj) { + return Status::Invalid("deserialize failed: obj is nullptr"); + } + if (json.empty()) { + return Status::Invalid("deserialize failed: ", diagnostic); + } + if (json.find('\0') != std::string_view::npos) { + return Status::Invalid("deserialize failed: JSON contains an unescaped NUL byte"); + } + // Parse(data, size) uses an encoded stream that consumes a leading BOM. + // Keep the same JSON syntax as FromJsonString's UTF-8 string stream. + rapidjson::MemoryStream stream(json.data(), json.size()); + rapidjson::Document doc; + doc.ParseStream(stream); + if (doc.HasParseError()) { + return Status::Invalid("deserialize failed: ", diagnostic); + } + return DeserializeObject(doc, diagnostic, obj); + } + // if T is std::nullopt, will use rapid_json null_value template static rapidjson::Value SerializeValue(const T& obj, @@ -133,6 +143,19 @@ class RapidJsonUtil { static Status CheckNoDuplicateMembers(const rapidjson::Value& value); private: + template + static Status DeserializeObject(const rapidjson::Document& doc, std::string_view diagnostic, + T* obj) { + try { + obj->FromJson(doc); + } catch (const std::invalid_argument& e) { + return Status::Invalid("deserialize failed, possibly type incompatible: ", e.what()); + } catch (...) { + return Status::Invalid("deserialize failed, reason unknown: ", diagnostic); + } + return Status::OK(); + } + static inline bool ToJson(const rapidjson::Value& value, std::string* json_str) { assert(json_str); rapidjson::StringBuffer buffer; @@ -145,12 +168,11 @@ class RapidJsonUtil { } static inline bool FromJson(const std::string& json_str, rapidjson::Document* doc) { - return FromJson(json_str.c_str(), doc); - } - - static inline bool FromJson(const char* json_str, rapidjson::Document* doc) { - doc->Parse(json_str); - return !doc->HasParseError(); + doc->Parse(json_str.c_str()); + if (doc->HasParseError()) { + return false; + } + return true; } template @@ -187,19 +209,19 @@ class RapidJsonUtil { return buffer.GetString(); } static Result> MapFromJsonString( - const char* json_str, std::string_view diagnostic) { + const std::string& json_str) { rapidjson::Document doc; - doc.Parse(json_str); + doc.Parse(json_str.c_str()); if (doc.HasParseError() || !doc.IsObject()) { return Status::Invalid("deserialize failed: parse error or not JSON object: ", - diagnostic); + json_str); } std::map result; for (auto it = doc.MemberBegin(); it != doc.MemberEnd(); ++it) { if (!it->name.IsString() || !it->value.IsString()) { return Status::Invalid( - "deserialize failed: non-string key or value in JSON object: ", diagnostic); + "deserialize failed: non-string key or value in JSON object: ", json_str); } result[it->name.GetString()] = it->value.GetString(); } diff --git a/src/paimon/common/utils/rapidjson_util_test.cpp b/src/paimon/common/utils/rapidjson_util_test.cpp index 2a2774392..e89e7337a 100644 --- a/src/paimon/common/utils/rapidjson_util_test.cpp +++ b/src/paimon/common/utils/rapidjson_util_test.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include "gtest/gtest.h" @@ -152,6 +153,25 @@ TEST(RapidJsonUtilTest, TestRejectUnescapedNul) { } } +TEST(RapidJsonUtilTest, TestFromJsonViewUsesExactLength) { + struct SnapshotField { + void FromJson(const rapidjson::Value& doc) { + id = RapidJsonUtil::DeserializeKeyValue(doc, "id"); + } + int64_t id = 0; + } value; + constexpr std::string_view json = R"({"id":17}trailing)"; + ASSERT_OK(RapidJsonUtil::FromJsonView(json.substr(0, 9), "snapshot", &value)); + EXPECT_EQ(17, value.id); + ASSERT_NOK_WITH_MSG(RapidJsonUtil::FromJsonView(json, "snapshot", &value), "snapshot"); + + const std::string bom_json = + "\xEF\xBB\xBF" + R"({"id":17})"; + ASSERT_NOK_WITH_MSG(RapidJsonUtil::FromJsonString(bom_json, &value), "deserialize failed"); + ASSERT_NOK_WITH_MSG(RapidJsonUtil::FromJsonView(bom_json, "snapshot", &value), "snapshot"); +} + TEST(RapidJsonUtilTest, TestSerializeStringWithEmbeddedNul) { rapidjson::Document doc; const std::string text("name\0secret", 11); diff --git a/src/paimon/core/snapshot.cpp b/src/paimon/core/snapshot.cpp index 964cbb8c7..87d56bbd1 100644 --- a/src/paimon/core/snapshot.cpp +++ b/src/paimon/core/snapshot.cpp @@ -332,14 +332,15 @@ void Snapshot::FromJson(const rapidjson::Value& obj) noexcept(false) { RapidJsonUtil::DeserializeKeyValue>(obj, FIELD_NEXT_ROW_ID); } -Result Snapshot::FromPath(const std::shared_ptr& fs, const std::string& path, - MemoryPool* pool) { - if (pool == nullptr || pool == GetDefaultPool().get()) { - std::string json_str; - PAIMON_RETURN_NOT_OK(fs->ReadFile(path, &json_str)); - return Snapshot::FromJsonString(json_str); - } +Result Snapshot::FromPath(const std::shared_ptr& fs, + const std::string& path) { + std::string json_str; + PAIMON_RETURN_NOT_OK(fs->ReadFile(path, &json_str)); + return Snapshot::FromJsonString(json_str); +} +Result Snapshot::FromPath(const std::shared_ptr& fs, const std::string& path, + MemoryPool& pool) { Bytes json; { PAIMON_ASSIGN_OR_RAISE(std::unique_ptr input, fs->Open(path)); @@ -350,24 +351,25 @@ Result Snapshot::FromPath(const std::shared_ptr& fs, const ScopeGuard close([&input]() { (void)input->Close(); }); PAIMON_ASSIGN_OR_RAISE(int64_t length, input->Length()); PAIMON_RETURN_NOT_OK(ValidateValueNonNegative(length, "read length")); - const uint64_t allocation_size = static_cast(length) + 1; - PAIMON_RETURN_NOT_OK(ValidateValueInRange(allocation_size, "snapshot buffer size")); + if (length == 0) { + return Status::Invalid("empty snapshot: ", path); + } + PAIMON_RETURN_NOT_OK(ValidateValueInRange(length, "snapshot buffer size")); + // MemoryPool::Malloc throws on refusal. Report it through the snapshot Result. try { - json = Bytes(static_cast(allocation_size), pool); + json = Bytes(static_cast(length), &pool); } catch (const std::bad_alloc&) { - return Status::OutOfMemory("cannot allocate ", allocation_size, " bytes for snapshot ", - path); + return Status::OutOfMemory("cannot allocate ", length, " bytes for snapshot ", path); } PAIMON_ASSIGN_OR_RAISE(int64_t read_length, input->Read(json.data(), length)); if (read_length != length) { return Status::IOError(fmt::format("path {}, expect read len {}, actual read len {}", path, length, read_length)); } - json.data()[length] = '\0'; } Snapshot snapshot; - PAIMON_RETURN_NOT_OK(RapidJsonUtil::FromNullTerminatedJson( - std::string_view(json.data(), json.size() - 1), &snapshot, path)); + PAIMON_RETURN_NOT_OK( + RapidJsonUtil::FromJsonView(std::string_view(json.data(), json.size()), path, &snapshot)); return snapshot; } diff --git a/src/paimon/core/snapshot.h b/src/paimon/core/snapshot.h index 235528150..91191f35c 100644 --- a/src/paimon/core/snapshot.h +++ b/src/paimon/core/snapshot.h @@ -242,8 +242,10 @@ class Snapshot : public Jsonizable { void FromJson(const rapidjson::Value& obj) noexcept(false) override; + static Result FromPath(const std::shared_ptr& fs, + const std::string& path); static Result FromPath(const std::shared_ptr& fs, const std::string& path, - MemoryPool* pool = nullptr); + MemoryPool& pool); private: // version of snapshot diff --git a/src/paimon/core/table/append_only_file_store_table.cpp b/src/paimon/core/table/append_only_file_store_table.cpp index 4a23f17a1..5da959a36 100644 --- a/src/paimon/core/table/append_only_file_store_table.cpp +++ b/src/paimon/core/table/append_only_file_store_table.cpp @@ -158,7 +158,7 @@ Result> AppendOnlyFileStoreTable::NewFileStoreSca const ScanContext* context) const { // TODO(liancheng.lsz): support fallback branch in scan std::shared_ptr table_schema = checked_pointer_cast(schema_); - const auto snapshot_manager = GetSnapshotManager(memory_pool); + const auto snapshot_manager = GetSnapshotManagerForScan(memory_pool); std::unique_ptr scan; if (core_options.DataEvolutionEnabled()) { PAIMON_ASSIGN_OR_RAISE( diff --git a/src/paimon/core/table/file_store_table.h b/src/paimon/core/table/file_store_table.h index 6aefe868f..5e13ba80f 100644 --- a/src/paimon/core/table/file_store_table.h +++ b/src/paimon/core/table/file_store_table.h @@ -76,8 +76,12 @@ class FileStoreTable : public Table { return schema_manager_; } - std::shared_ptr GetSnapshotManager( - const std::shared_ptr& pool = nullptr) const { + std::shared_ptr GetSnapshotManager() const { + return std::make_shared(file_system_, root_path_, CurrentBranch()); + } + + std::shared_ptr GetSnapshotManagerForScan( + const std::shared_ptr& pool) const { return std::make_shared(file_system_, root_path_, CurrentBranch(), pool); } diff --git a/src/paimon/core/table/primary_key_file_store_table.cpp b/src/paimon/core/table/primary_key_file_store_table.cpp index 2dd74fdf4..b3dc72bd3 100644 --- a/src/paimon/core/table/primary_key_file_store_table.cpp +++ b/src/paimon/core/table/primary_key_file_store_table.cpp @@ -233,10 +233,10 @@ Result> PrimaryKeyFileStoreTable::NewFileStoreSca std::shared_ptr table_schema = checked_pointer_cast(schema_); std::unique_ptr scan; PAIMON_ASSIGN_OR_RAISE( - scan, KeyValueFileStoreScan::Create(GetSnapshotManager(memory_pool), GetSchemaManager(), - manifest_list, manifest_file, table_schema, - arrow_schema, context->GetScanFilters(), core_options, - executor, memory_pool)); + scan, KeyValueFileStoreScan::Create(GetSnapshotManagerForScan(memory_pool), + GetSchemaManager(), manifest_list, manifest_file, + table_schema, arrow_schema, context->GetScanFilters(), + core_options, executor, memory_pool)); return WithTablePath(std::move(scan), root_path_); } diff --git a/src/paimon/core/table/source/scan_exception_safety_test.cpp b/src/paimon/core/table/source/scan_exception_safety_test.cpp index d95388d6c..c08df9825 100644 --- a/src/paimon/core/table/source/scan_exception_safety_test.cpp +++ b/src/paimon/core/table/source/scan_exception_safety_test.cpp @@ -337,7 +337,7 @@ TEST(ScanExceptionSafetyTest, SnapshotBufferUsesScanPoolBeforeReading) { auto plan = scan->CreatePlan(); EXPECT_FALSE(plan.ok()); EXPECT_TRUE(plan.status().IsOutOfMemory()) << plan.status(); - EXPECT_EQ(pool->refused_bytes.load(), oversized_snapshot.size() + 1); + EXPECT_EQ(pool->refused_bytes.load(), oversized_snapshot.size()); EXPECT_LE(pool->MaxMemoryUsage(), kPoolCapacity); EXPECT_EQ(fs->counts->opens.load(), opens_before + 1); EXPECT_EQ(fs->counts->closes.load(), closes_before + 1); @@ -347,6 +347,18 @@ TEST(ScanExceptionSafetyTest, SnapshotBufferUsesScanPoolBeforeReading) { } EXPECT_EQ(pool->CurrentUsage(), 0); + // An empty file has no input bytes to charge and is invalid JSON. + ASSERT_OK(fs->WriteFile(snapshot_path, "", /*overwrite=*/true)); + { + ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); + const auto usage_before = pool->CurrentUsage(); + auto plan = scan->CreatePlan(); + EXPECT_TRUE(plan.status().IsInvalid()) << plan.status(); + EXPECT_EQ(fs->counts->live.load(), 0); + EXPECT_EQ(pool->CurrentUsage(), usage_before); + } + EXPECT_EQ(pool->CurrentUsage(), 0); + ASSERT_OK(fs->WriteFile(snapshot_path, snapshot_json + '\0', /*overwrite=*/true)); { ASSERT_OK_AND_ASSIGN(auto scan, OrdinaryScan(pool, executor, input)); diff --git a/src/paimon/core/utils/snapshot_manager.cpp b/src/paimon/core/utils/snapshot_manager.cpp index f7981d4f0..f0ce484f5 100644 --- a/src/paimon/core/utils/snapshot_manager.cpp +++ b/src/paimon/core/utils/snapshot_manager.cpp @@ -31,6 +31,7 @@ #include "paimon/core/utils/branch_manager.h" #include "paimon/core/utils/file_utils.h" #include "paimon/fs/file_system.h" +#include "paimon/memory/memory_pool.h" #include "paimon/result.h" namespace paimon { @@ -39,13 +40,18 @@ SnapshotManager::SnapshotManager(const std::shared_ptr& fs, const std::string& root_path) : SnapshotManager(fs, root_path, BranchManager::DEFAULT_MAIN_BRANCH) {} +SnapshotManager::SnapshotManager(const std::shared_ptr& fs, + const std::string& root_path, const std::string& branch) + : fs_(fs), root_path_(root_path), branch_(BranchManager::NormalizeBranch(branch)) {} + SnapshotManager::SnapshotManager(const std::shared_ptr& fs, const std::string& root_path, const std::string& branch, const std::shared_ptr& pool) - : fs_(fs), - root_path_(root_path), - branch_(BranchManager::NormalizeBranch(branch)), - pool_(pool) {} + : SnapshotManager(fs, root_path, branch) { + if (pool && pool != GetDefaultPool()) { + pool_ = pool; + } +} SnapshotManager::~SnapshotManager() = default; @@ -128,7 +134,8 @@ bool SnapshotManager::ExpiredSinceBoundaryWasRead(int64_t id) const { } Result SnapshotManager::LoadSnapshot(int64_t snapshot_id) const { - return Snapshot::FromPath(fs_, SnapshotPath(snapshot_id), pool_.get()); + const std::string path = SnapshotPath(snapshot_id); + return pool_ ? Snapshot::FromPath(fs_, path, *pool_) : Snapshot::FromPath(fs_, path); } void SnapshotManager::SetSnapshotLoader(SnapshotLoader loader) { diff --git a/src/paimon/core/utils/snapshot_manager.h b/src/paimon/core/utils/snapshot_manager.h index ee3f195cd..9a7358888 100644 --- a/src/paimon/core/utils/snapshot_manager.h +++ b/src/paimon/core/utils/snapshot_manager.h @@ -48,7 +48,9 @@ class SnapshotManager { SnapshotManager(const std::shared_ptr& fs, const std::string& root_path); SnapshotManager(const std::shared_ptr& fs, const std::string& root_path, - const std::string& branch, const std::shared_ptr& pool = nullptr); + const std::string& branch); + SnapshotManager(const std::shared_ptr& fs, const std::string& root_path, + const std::string& branch, const std::shared_ptr& pool); ~SnapshotManager(); /// Sets the loader for `LatestSnapshot()` and `LatestSnapshotId()`.