Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions include/paimon/scan_context.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
36 changes: 22 additions & 14 deletions src/paimon/common/utils/rapidjson_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -75,27 +75,34 @@ class RapidJsonUtil {
// if T is custom type, T must have FromJson()
template <typename T>
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 <typename T>
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<T, std::map<std::string, std::string>>) {
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);
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: ", json_str);
return Status::Invalid("deserialize failed, reason unknown: ", diagnostic);
}
}
return Status::OK();
Expand Down Expand Up @@ -138,11 +145,12 @@ class RapidJsonUtil {
}

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;
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 <typename T>
Expand Down Expand Up @@ -179,19 +187,19 @@ class RapidJsonUtil {
return buffer.GetString();
}
static Result<std::map<std::string, std::string>> 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<std::string, std::string> 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();
}
Expand Down
50 changes: 45 additions & 5 deletions src/paimon/core/snapshot.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,23 @@
#include "paimon/core/snapshot.h"

#include <cassert>
#include <cstddef>
#include <cstdint>
#include <new>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>

#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"
Expand Down Expand Up @@ -323,11 +332,42 @@ void Snapshot::FromJson(const rapidjson::Value& obj) noexcept(false) {
RapidJsonUtil::DeserializeKeyValue<std::optional<int64_t>>(obj, FIELD_NEXT_ROW_ID);
}

Result<Snapshot> Snapshot::FromPath(const std::shared_ptr<FileSystem>& 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> Snapshot::FromPath(const std::shared_ptr<FileSystem>& 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<InputStream> 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<uint64_t>(length) + 1;
PAIMON_RETURN_NOT_OK(ValidateValueInRange<size_t>(allocation_size, "snapshot buffer size"));
try {
json = Bytes(static_cast<size_t>(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;
}

Expand Down
4 changes: 2 additions & 2 deletions src/paimon/core/snapshot.h
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,8 @@ class Snapshot : public Jsonizable<Snapshot> {

void FromJson(const rapidjson::Value& obj) noexcept(false) override;

static Result<Snapshot> FromPath(const std::shared_ptr<FileSystem>& fs,
const std::string& path);
static Result<Snapshot> FromPath(const std::shared_ptr<FileSystem>& fs, const std::string& path,
MemoryPool* pool = nullptr);

private:
// version of snapshot
Expand Down
5 changes: 3 additions & 2 deletions src/paimon/core/table/append_only_file_store_table.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -158,16 +158,17 @@ Result<std::unique_ptr<FileStoreScan>> AppendOnlyFileStoreTable::NewFileStoreSca
const ScanContext* context) const {
// TODO(liancheng.lsz): support fallback branch in scan
std::shared_ptr<TableSchema> table_schema = checked_pointer_cast<TableSchema>(schema_);
const auto snapshot_manager = GetSnapshotManager(memory_pool);
std::unique_ptr<FileStoreScan> 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));
Expand Down
5 changes: 3 additions & 2 deletions src/paimon/core/table/file_store_table.h
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@ class FileStoreTable : public Table {
return schema_manager_;
}

std::shared_ptr<SnapshotManager> GetSnapshotManager() const {
return std::make_shared<SnapshotManager>(file_system_, root_path_, CurrentBranch());
std::shared_ptr<SnapshotManager> GetSnapshotManager(
const std::shared_ptr<MemoryPool>& pool = nullptr) const {
return std::make_shared<SnapshotManager>(file_system_, root_path_, CurrentBranch(), pool);
}

std::string Name() const override {
Expand Down
8 changes: 4 additions & 4 deletions src/paimon/core/table/primary_key_file_store_table.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,10 @@ Result<std::unique_ptr<FileStoreScan>> PrimaryKeyFileStoreTable::NewFileStoreSca
std::shared_ptr<TableSchema> table_schema = checked_pointer_cast<TableSchema>(schema_);
std::unique_ptr<FileStoreScan> 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_);
}

Expand Down
113 changes: 108 additions & 5 deletions src/paimon/core/table/source/scan_exception_safety_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* limitations under the License.
*/

#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
Expand All @@ -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 {
Expand All @@ -55,15 +58,18 @@ class InlinePlanningExecutor final : public Executor {

class PlanningFaultPool final : public MemoryPool {
public:
explicit PlanningFaultPool(uint64_t capacity = std::numeric_limits<uint64_t>::max())
: capacity_(capacity) {}

void* Malloc(uint64_t size, uint64_t alignment) override {
std::lock_guard<std::mutex> 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<std::mutex> lock(mutex_);
Check();
Check(new_size - std::min(old_size, new_size));
++realloc_calls;
return upstream_->Realloc(pointer, old_size, new_size, alignment);
}
Expand All @@ -86,14 +92,20 @@ class PlanningFaultPool final : public MemoryPool {
std::atomic<uint64_t> malloc_calls{0};
std::atomic<uint64_t> realloc_calls{0};
std::atomic<bool> rejected{false};
std::atomic<uint64_t> 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<MemoryPool> upstream_ = GetMemoryPool();
std::mutex mutex_;
};
Expand All @@ -108,6 +120,7 @@ struct PlanningInput {
std::shared_ptr<Cache> cache;
std::optional<int32_t> bucket;
std::shared_ptr<FileSystem> file_system;
std::optional<std::string> scan_mode;
};

Result<std::unique_ptr<TableScan>> OrdinaryScan(
Expand All @@ -118,8 +131,10 @@ Result<std::unique_ptr<TableScan>> OrdinaryScan(
std::string schema{std::istreambuf_iterator<char>(schema_file),
std::istreambuf_iterator<char>()};
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)
.AddOption("scan.manifest-entry-cache.max-snapshots", "8")
Expand Down Expand Up @@ -291,6 +306,94 @@ 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<CountingReaderFileSystem>("/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<PlanningFaultPool>(kPoolCapacity);
auto executor = std::make_shared<InlinePlanningExecutor>();

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->sequential_read_limit = static_cast<int64_t>(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->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());
EXPECT_EQ(plan->SnapshotId(), 1);
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) {
auto pool = std::make_shared<PlanningFaultPool>();
auto arrow_pool = GetArrowPool(pool);
Expand Down
Loading