Skip to content
Closed
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
46 changes: 38 additions & 8 deletions src/paimon/common/utils/rapidjson_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -89,18 +90,34 @@ class RapidJsonUtil {
if (!FromJson(json_str, &doc)) {
return Status::Invalid("deserialize failed: ", json_str);
}
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 DeserializeObject(doc, json_str, obj);
}
return Status::OK();
}

// T must have FromJson(). The view need not be NUL-terminated.
template <typename T>
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 <typename T>
static rapidjson::Value SerializeValue(const T& obj,
Expand All @@ -126,6 +143,19 @@ class RapidJsonUtil {
static Status CheckNoDuplicateMembers(const rapidjson::Value& value);

private:
template <typename T>
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;
Expand Down
20 changes: 20 additions & 0 deletions src/paimon/common/utils/rapidjson_util_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include <algorithm>
#include <map>
#include <string>
#include <string_view>
#include <vector>

#include "gtest/gtest.h"
Expand Down Expand Up @@ -152,6 +153,25 @@ TEST(RapidJsonUtilTest, TestRejectUnescapedNul) {
}
}

TEST(RapidJsonUtilTest, TestFromJsonViewUsesExactLength) {
struct SnapshotField {
void FromJson(const rapidjson::Value& doc) {
id = RapidJsonUtil::DeserializeKeyValue<int64_t>(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);
Expand Down
44 changes: 43 additions & 1 deletion 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 @@ -327,7 +336,40 @@ 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));
return Snapshot::FromJsonString(json_str);
}

Result<Snapshot> Snapshot::FromPath(const std::shared_ptr<FileSystem>& fs, const std::string& path,
MemoryPool& pool) {
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"));
if (length == 0) {
return Status::Invalid("empty snapshot: ", path);
}
PAIMON_RETURN_NOT_OK(ValidateValueInRange<size_t>(length, "snapshot buffer size"));
// MemoryPool::Malloc throws on refusal. Report it through the snapshot Result.
try {
json = Bytes(static_cast<size_t>(length), &pool);
} catch (const std::bad_alloc&) {
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));
}
}
Snapshot snapshot;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use doc.Parse(json.data(), json.size()) and rename the helper to FromJsonView()? This would remove the extra byte allocation, manual NUL terminator, and size() - 1, while keeping the embedded-NUL validation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FromJsonView() now parses exactly the file length, with no extra byte or manual terminator. It uses a bounded MemoryStream because this RapidJSON version’s Parse(data, size) consumes a leading UTF-8 BOM, which the original parser rejects. The embedded-NUL check remains.

PAIMON_RETURN_NOT_OK(
RapidJsonUtil::FromJsonView(std::string_view(json.data(), json.size()), path, &snapshot));
return snapshot;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, @realAaronWu In PR #584, your measurements showed schema JSON sizes of roughly 0.7–7.7 KB. Snapshot JSON appears even smaller—all 372 snapshots in this repository are under 1 KB—and its input buffer is short-lived.

Propagating the memory pool consistently through all snapshot-loading paths would touch several components. Could you share the motivating workload, expected snapshot sizes, concurrency, and memory budgets? It would help us understand whether this addresses a measurable memory issue or a requirement to account for every allocation, and assess the implementation cost accordingly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I measured the 372 numbered snapshot fixtures on the target base. The median is 572 B, p95 is 651 B, and the maximum is 716 B. The motivating case is one embedded database scan with a capped pool. In the controlled reproduction, padding the snapshot to 270,337 B with JSON whitespace let a 270,338 B input allocation bypass the 256 KiB pool on the old path. I don’t have production size or concurrency measurements, or evidence of meaningful RSS savings for ordinary snapshots. The case demonstrates an admission gap for this buffer. Would you prefer to keep this narrowly scoped to the data-scan path, or defer it to the broader planning controls? Reproduction

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The motivating workload is Sirius’s Paimon read integration. Our first target is a local append-only Parquet scan of an already-bound snapshot. Sirius supplies a capped pool to CreatePlan(); this snapshot buffer is allocated before Sirius gets a plan or batch it can admit.

In the #587 reproduction, we ran one scan with a 256 KiB pool and padded a valid 459 B snapshot to 270,337 B with JSON whitespace. The allocation trace recorded a successful 270,338 B heap allocation in ReadFile() outside the pool, before planning later failed. This demonstrates a budget bypass on the actual read path. The tested cap and padded size are stress inputs. We have no production size or concurrency measurements.

The proposed change routes only the numbered snapshot input buffer for data scans through the existing caller pool. The regression verifies refusal before reading, stream closure, and successful retry. This closes the specific gap we measured while keeping write, commit, and standalone metadata paths outside the change.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After internal discussion, our understanding is that both #588 and #592 aim to make memory usage during scan planning more tightly bounded. Although 256 KiB is a stress-test quota rather than a production requirement, manifest limits and accounting for JSON buffers alone would still leave many allocations outside the budget. Fully enforcing such a limit across the planning path could require intrusive changes and create a substantial maintenance burden.

We suggest either exploring a scan-limit design aligned with Java Paimon to mitigate planning memory pressure, or maintaining downstream patches for your integration’s stricter requirements. Based on the workload evidence shared so far, it is not yet clear that precise memory-budget enforcement is a broadly applicable requirement that justifies the added code complexity and maintenance burden.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for discussing the scope and maintenance cost. We tested a Sirius-side alternative with unmodified Paimon C++. Sirius checks the numbered snapshot size, manifest references, and Zstandard decoded block bounds before entering planning.

For our fixed local append-only fixture, healthy reads and retry returned the expected rows. The oversized snapshot, decode amplification, manifest fanout, and unknown decoded-size cases were refused before the SDK ran.

We will carry this forward on the Sirius side and close this PR. Sirius validation draft

}

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

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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We added default parameters in the official code, so other places can compile even if they don’t call the updated APIs—it's easy to miss necessary changes. However, if we remove the default parameters, we’d likely need to update most areas related to snapshots. @lucasfang What do you think?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the new default arguments. The existing Snapshot::FromPath(fs, path) and manager constructors keep their original behavior. The pooled overload requires a MemoryPool&, and the data-scan factory requires an explicit pool.

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 = GetSnapshotManagerForScan(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: 5 additions & 0 deletions src/paimon/core/table/file_store_table.h
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ class FileStoreTable : public Table {
return std::make_shared<SnapshotManager>(file_system_, root_path_, CurrentBranch());
}

std::shared_ptr<SnapshotManager> GetSnapshotManagerForScan(
const std::shared_ptr<MemoryPool>& pool) const {
return std::make_shared<SnapshotManager>(file_system_, root_path_, CurrentBranch(), pool);
Comment thread
realAaronWu marked this conversation as resolved.
Resolved
}

std::string Name() const override {
return identifier_.GetObjectName();
}
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(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_);
}

Expand Down
Loading