diff --git a/include/paimon/table/source/table_scan.h b/include/paimon/table/source/table_scan.h index 8bae74c41..73b3a7d50 100644 --- a/include/paimon/table/source/table_scan.h +++ b/include/paimon/table/source/table_scan.h @@ -19,6 +19,8 @@ #pragma once +#include +#include #include #include #include @@ -33,6 +35,25 @@ namespace paimon { class ScanContext; +/// Per-plan limits for an uncached managed append-only batch scan of a full snapshot with Avro +/// manifests. Row ranges are unsupported. A default limit imposes no count restriction. +/// Set explicit finite limits to bound objects. Each zero allows no such objects. +/// +/// These counts exclude table and snapshot discovery, schema and index/statistics buffers, +/// decoding buffers (including Arrow and Avro), variable-length field bytes, and container +/// capacity. +struct PlanningLimits { + /// Total rows in the base and delta manifest lists, charged before conversion to objects. + std::size_t max_manifest_list_rows = std::numeric_limits::max(); + /// Rows charged across all selected manifests. With lazy entry decoding, only rows that + /// pass the early partition row filter are charged. Otherwise each decoded Arrow batch + /// is charged in full. Data-column predicates run after these charges. + std::size_t max_manifest_entry_rows = std::numeric_limits::max(); + /// Actual split count before applying the row limit, checked after a bucket is packed and + /// before creating its split objects. Packing groups are bounded by the admitted entries. + std::size_t max_splits = std::numeric_limits::max(); +}; + /// A scanner interface for reading table's meta and create a plan. class PAIMON_EXPORT TableScan { public: @@ -42,6 +63,11 @@ class PAIMON_EXPORT TableScan { /// @return A Result containing a unique pointer to the `TableScan` instance. static Result> Create(std::unique_ptr context); + /// Opt in to planning object limits using the existing executor. + /// Unsupported routes return `NotImplemented`. A limit refusal returns `CapacityError`. + static Result> Create(std::unique_ptr context, + const PlanningLimits& limits); + virtual ~TableScan() = default; /// Create a scan plan. diff --git a/src/paimon/core/manifest/manifest_file.cpp b/src/paimon/core/manifest/manifest_file.cpp index f47a63a9c..3044fe961 100644 --- a/src/paimon/core/manifest/manifest_file.cpp +++ b/src/paimon/core/manifest/manifest_file.cpp @@ -138,14 +138,14 @@ Status ManifestFile::ReadSelectedEntries( const std::string& file_name, std::optional file_size, const RowRangeIndex* row_ranges, const std::function(const InternalRow&)>& row_filter, const std::function(const ManifestEntry&)>& entry_filter, - std::vector* entries) const { + std::vector* entries, ManifestRowLimit* row_limit) const { if (!row_ranges && !row_filter) { - return Read(file_name, entry_filter, file_size, entries); + return Read(file_name, entry_filter, file_size, entries, row_limit); } return ReadArrowBatches( file_name, file_size, - [this, row_ranges, &row_filter, &entry_filter, - entries](const std::shared_ptr& batch) -> Status { + [this, row_ranges, &row_filter, &entry_filter, entries, + row_limit](const std::shared_ptr& batch) -> Status { // ManifestMetaReader has aligned both the entry and its nested file schema. // Only row-range scans need to probe the file columns before entry decoding. std::shared_ptr files; @@ -194,6 +194,9 @@ Status ManifestFile::ReadSelectedEntries( continue; } } + if (row_limit) { + PAIMON_RETURN_NOT_OK(row_limit->Admit(1)); + } PAIMON_ASSIGN_OR_RAISE(ManifestEntry entry, serializer_->FromRow(row)); if (entry_filter) { PAIMON_ASSIGN_OR_RAISE(bool keep, entry_filter(entry)); @@ -205,7 +208,7 @@ Status ManifestFile::ReadSelectedEntries( } return Status::OK(); }, - /*prepare_reader=*/nullptr); + /*prepare_reader=*/nullptr, /*allow_cache=*/!row_limit); } Status ManifestFile::PrepareBucketRead(int32_t bucket, diff --git a/src/paimon/core/manifest/manifest_file.h b/src/paimon/core/manifest/manifest_file.h index 22ffba497..8487abb8c 100644 --- a/src/paimon/core/manifest/manifest_file.h +++ b/src/paimon/core/manifest/manifest_file.h @@ -18,6 +18,7 @@ #pragma once +#include #include #include #include @@ -82,12 +83,13 @@ class ManifestFile : public ObjectsFile { /// A null row_ranges or row_filter disables that selection. Unknown ranges are retained. /// Add and Delete entries use the same selection. The entry filter runs after decoding. /// The reader validates the entry version before inspecting row ranges or invoking the filter. + /// The optional row_limit limits the selected entries before materializing each object. Status ReadSelectedEntries( const std::string& file_name, std::optional file_size, const RowRangeIndex* row_ranges, const std::function(const InternalRow&)>& row_filter, const std::function(const ManifestEntry&)>& entry_filter, - std::vector* entries) const; + std::vector* entries, ManifestRowLimit* row_limit = nullptr) const; private: Status PrepareBucketRead(int32_t bucket, const std::optional& expected_total_buckets, diff --git a/src/paimon/core/manifest/manifest_file_test.cpp b/src/paimon/core/manifest/manifest_file_test.cpp index 551075b21..73e9e46c9 100644 --- a/src/paimon/core/manifest/manifest_file_test.cpp +++ b/src/paimon/core/manifest/manifest_file_test.cpp @@ -410,6 +410,101 @@ TEST_F(ManifestFileTest, TestReadBucketEntriesMaterializesOnlySelectedBucket) { ASSERT_EQ(1, manifest_cache->SupplierCallCount()); } +TEST_F(ManifestFileTest, SelectedEntryLimitAppliesAfterRowSelection) { + auto pool = GetDefaultPool(); + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + // Rewrite a pair of known buckets as an ordinary Avro manifest in the test directory. + const auto entries = ReadManifestEntry("orc", GetDataDir() + "/orc/append_09.db/append_09", + "manifest-3a44a0da-1008-463c-914e-28d271375e24-0", pool); + ASSERT_EQ(2, entries.size()); + ASSERT_NE(entries[0].Bucket(), entries[1].Bucket()); + auto partition_schema = arrow::schema({arrow::field("f1", arrow::int32())}); + ASSERT_OK_AND_ASSIGN(std::shared_ptr avro, FileFormatFactory::Get("avro", {})); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr paths, + FileStorePathFactory::Create( + dir->Str(), partition_schema, {"f1"}, /*default_part_value=*/"", avro->Identifier(), + /*data_file_prefix=*/"data-", /*legacy_partition_name_enabled=*/true, + /*external_paths=*/{}, /*global_index_external_paths=*/{}, + /*index_file_in_data_file_dir=*/false, /*external_path_weights=*/{}, pool)); + ASSERT_OK_AND_ASSIGN(CoreOptions options, CoreOptions::FromMap({})); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr file, + ManifestFile::Create(dir->GetFileSystem(), avro, "zstd", paths, + /*target_file_size=*/1024 * 1024, pool, options, partition_schema)); + ASSERT_OK_AND_ASSIGN(std::vector metas, file->Write(entries)); + ASSERT_EQ(1, metas.size()); + const auto& meta = metas.front(); + const auto matches_second = [bucket = + entries[1].Bucket()](const InternalRow& row) -> Result { + return ManifestEntrySerializer::GetBucket(row) == bucket; + }; + + std::vector selected; + int decoded = 0; + const auto count_decoded = [&decoded](const ManifestEntry&) -> Result { + ++decoded; + return true; + }; + ManifestRowLimit reject_selected(0); + auto refusal = + file->ReadSelectedEntries(meta.FileName(), meta.FileSize(), nullptr, matches_second, + count_decoded, &selected, &reject_selected); + EXPECT_TRUE(refusal.IsCapacityError()) << refusal.ToString(); + EXPECT_EQ(0, decoded); + EXPECT_TRUE(selected.empty()); + + ManifestRowLimit admit_selected(1); + ASSERT_OK(file->ReadSelectedEntries(meta.FileName(), meta.FileSize(), nullptr, matches_second, + count_decoded, &selected, &admit_selected)); + EXPECT_EQ(1, decoded); + EXPECT_EQ(std::vector({entries[1]}), selected); + + ASSERT_OK_AND_ASSIGN(std::vector later_metas, file->Write(entries)); + ASSERT_EQ(1, later_metas.size()); + ASSERT_NE(meta.FileName(), later_metas[0].FileName()); + std::vector later_entries; + const auto& later_meta = later_metas[0]; + const auto later_refusal = + file->ReadSelectedEntries(later_meta.FileName(), later_meta.FileSize(), nullptr, + matches_second, count_decoded, &later_entries, &admit_selected); + EXPECT_TRUE(later_refusal.IsCapacityError()) << later_refusal.ToString(); + EXPECT_TRUE(later_entries.empty()); + EXPECT_EQ(1, decoded); + + // Filtering out an already decoded entry cannot restore its admission allowance. + std::vector post_filtered; + ManifestRowLimit admit_one(1); + const auto admit_either = [](const InternalRow&) -> Result { return true; }; + const int32_t kept_bucket = entries[1].Bucket(); + const auto post_filter = [kept_bucket](const ManifestEntry& entry) -> Result { + return entry.Bucket() == kept_bucket; + }; + const auto post_filter_refusal = + file->ReadSelectedEntries(meta.FileName(), meta.FileSize(), nullptr, admit_either, + post_filter, &post_filtered, &admit_one); + EXPECT_TRUE(post_filter_refusal.IsCapacityError()) << post_filter_refusal.ToString(); + EXPECT_TRUE(post_filtered.empty()); + + // The row passes selection, but materializing it would reject its file kind. + ManifestEntry invalid(FileKind(static_cast(2)), entries[1].Partition(), + entries[1].Bucket(), entries[1].TotalBuckets(), entries[1].File()); + using WrittenFile = std::pair; + ASSERT_OK_AND_ASSIGN(WrittenFile malformed, file->WriteWithoutRolling({invalid})); + ManifestRowLimit reject_before_decode(0); + auto rejected = + file->ReadSelectedEntries(malformed.first, malformed.second, nullptr, matches_second, + count_decoded, &selected, &reject_before_decode); + EXPECT_TRUE(rejected.IsCapacityError()) << rejected.ToString(); + ManifestRowLimit allow_decode(1); + ASSERT_NOK_WITH_MSG( + file->ReadSelectedEntries(malformed.first, malformed.second, nullptr, matches_second, + count_decoded, &selected, &allow_decode), + "Unsupported byte value 2 for file kind."); + EXPECT_EQ(std::vector({entries[1]}), selected); +} + // A scan reads manifests whose length the manifest list already recorded. Handing that length over // is what lets the store skip the metadata request a bare open issues, which on a remote store is // a round trip paid before any of the file is read. diff --git a/src/paimon/core/manifest/manifest_list.h b/src/paimon/core/manifest/manifest_list.h index 918d04918..2adbb3f3b 100644 --- a/src/paimon/core/manifest/manifest_list.h +++ b/src/paimon/core/manifest/manifest_list.h @@ -88,10 +88,10 @@ class ManifestList : public ObjectsFile { /// @param snapshot The input snapshot. /// @param manifests The vector to store the manifest file metadata. /// @return Status indicating whether the operation was successful or not. - Status ReadBaseManifests(const Snapshot& snapshot, - std::vector* manifests) const { + Status ReadBaseManifests(const Snapshot& snapshot, std::vector* manifests, + ManifestRowLimit* row_limit = nullptr) const { return Read(snapshot.BaseManifestList(), /*filter=*/nullptr, - snapshot.BaseManifestListSize(), manifests); + snapshot.BaseManifestListSize(), manifests, row_limit); } /// Return a `ManifestFileMeta` for each delta manifest in this snapshot. @@ -99,10 +99,10 @@ class ManifestList : public ObjectsFile { /// @param snapshot The input snapshot. /// @param manifests The vector to store the manifest file metadata. /// @return Status indicating whether the operation was successful or not. - Status ReadDeltaManifests(const Snapshot& snapshot, - std::vector* manifests) const { + Status ReadDeltaManifests(const Snapshot& snapshot, std::vector* manifests, + ManifestRowLimit* row_limit = nullptr) const { return Read(snapshot.DeltaManifestList(), /*filter=*/nullptr, - snapshot.DeltaManifestListSize(), manifests); + snapshot.DeltaManifestListSize(), manifests, row_limit); } /// Return a `ManifestFileMeta` for each changelog manifest in this snapshot. diff --git a/src/paimon/core/manifest/manifest_list_test.cpp b/src/paimon/core/manifest/manifest_list_test.cpp index 094876e29..ec0e70917 100644 --- a/src/paimon/core/manifest/manifest_list_test.cpp +++ b/src/paimon/core/manifest/manifest_list_test.cpp @@ -131,6 +131,28 @@ class ManifestListTest : public testing::Test { } }; +TEST_F(ManifestListTest, LimitsRowsBeforeReservingManifestMetadata) { + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + auto manifest_list = CreateManifestList("avro", dir->Str(), GetDefaultPool()); + const std::vector expected = {MakeMeta("manifest-a", 100, 1, 0), + MakeMeta("manifest-b", 200, 1, 0)}; + using WrittenFile = std::pair; + ASSERT_OK_AND_ASSIGN(WrittenFile written, manifest_list->Write(expected)); + + std::vector metas; + const auto initial_capacity = metas.capacity(); + ManifestRowLimit reject_two(1); + auto refusal = manifest_list->Read(written.first, nullptr, written.second, &metas, &reject_two); + EXPECT_TRUE(refusal.IsCapacityError()) << refusal.ToString(); + EXPECT_TRUE(metas.empty()); + EXPECT_EQ(initial_capacity, metas.capacity()); + + ManifestRowLimit admit_two(2); + ASSERT_OK(manifest_list->Read(written.first, nullptr, written.second, &metas, &admit_two)); + EXPECT_EQ(expected, metas); +} + TEST_F(ManifestListTest, DecodedCacheReusesIpcAcrossReaders) { auto dir = UniqueTestDirectory::Create(); ASSERT_TRUE(dir); diff --git a/src/paimon/core/operation/append_only_file_store_scan_test.cpp b/src/paimon/core/operation/append_only_file_store_scan_test.cpp index 6e121c9fc..5c06586a7 100644 --- a/src/paimon/core/operation/append_only_file_store_scan_test.cpp +++ b/src/paimon/core/operation/append_only_file_store_scan_test.cpp @@ -20,7 +20,10 @@ #include #include +#include #include +#include +#include #include #include #include @@ -33,6 +36,7 @@ #include "paimon/common/data/binary_row.h" #include "paimon/common/data/binary_row_writer.h" #include "paimon/common/data/serializer/binary_row_serializer.h" +#include "paimon/common/executor/future.h" #include "paimon/common/io/cache/lru_cache.h" #include "paimon/common/io/memory_segment_output_stream.h" #include "paimon/common/utils/math.h" @@ -49,6 +53,7 @@ #include "paimon/core/table/source/abstract_table_scan.h" #include "paimon/core/table/source/snapshot/snapshot_reader.h" #include "paimon/core/utils/file_store_path_factory.h" +#include "paimon/core/utils/snapshot_manager.h" #include "paimon/defs.h" #include "paimon/executor.h" #include "paimon/format/file_format_factory.h" @@ -60,12 +65,15 @@ #include "paimon/predicate/predicate_builder.h" #include "paimon/scan_context.h" #include "paimon/status.h" +#include "paimon/table/source/data_split.h" #include "paimon/table/source/scan_metrics.h" #include "paimon/table/source/table_scan.h" #include "paimon/testing/mock/mock_file_batch_reader.h" #include "paimon/testing/mock/mock_format_reader_builder.h" #include "paimon/testing/utils/binary_row_generator.h" +#include "paimon/testing/utils/blocking_file_system.h" #include "paimon/testing/utils/counting_cache_test_utils.h" +#include "paimon/testing/utils/counting_reader_file_system.h" #include "paimon/testing/utils/test_helper.h" #include "paimon/testing/utils/testharness.h" #include "paimon/testing/utils/timezone_guard.h" @@ -1071,6 +1079,321 @@ TEST(AppendOnlyFileStoreScanTest, SnapshotCacheRebuildsCorruptValues) { } } +TEST(AppendOnlyFileStoreScanTest, ControlledPlanRespectsLimits) { + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + const arrow::FieldVector fields = {arrow::field("f0", arrow::int32()), + arrow::field("f1", arrow::int32())}; + const std::map options = { + {Options::BUCKET, "1"}, {Options::BUCKET_KEY, "f0"}, {Options::FILE_FORMAT, "orc"}}; + ASSERT_OK_AND_ASSIGN(std::unique_ptr writer, + TestHelper::Create(dir->Str(), arrow::schema(fields), {"f1"}, {}, options, + /*is_streaming_mode=*/false)); + std::vector> batches; + for (int32_t partition : {10, 20}) { + ASSERT_OK_AND_ASSIGN( + std::unique_ptr batch, + TestHelper::MakeRecordBatch(arrow::struct_(fields), fmt::format("[[1, {}]]", partition), + {{"f1", fmt::format("{}", partition)}}, /*bucket=*/0, + {RecordBatch::RowKind::INSERT})); + batches.push_back(std::move(batch)); + } + ASSERT_OK(writer->WriteAndCommit(std::move(batches), 0, std::nullopt)); + writer.reset(); + + const std::string table_path = dir->Str() + "/foo.db/bar"; + std::shared_ptr pool = GetMemoryPool(); + auto create_scan = [&](const PlanningLimits& limits) -> Result> { + ScanContextBuilder builder(table_path); + builder.WithMemoryPool(pool).SetLimit(1).SetPredicate( + PredicateBuilder::Equal(1, "f1", FieldType::INT, Literal(10))); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr context, builder.Finish()); + return TableScan::Create(std::move(context), limits); + }; + + ASSERT_OK_AND_ASSIGN(auto list_limited, create_scan({0, 32, 32})); + auto list_refusal = list_limited->CreatePlan(); + EXPECT_TRUE(list_refusal.status().IsCapacityError()); + EXPECT_NE(std::string::npos, list_refusal.status().ToString().find("manifest list")); + EXPECT_EQ(0, pool->CurrentUsage()); + + ASSERT_OK_AND_ASSIGN(auto entry_limited, create_scan({32, 0, 32})); + auto entry_refusal = entry_limited->CreatePlan(); + EXPECT_TRUE(entry_refusal.status().IsCapacityError()); + EXPECT_NE(std::string::npos, entry_refusal.status().ToString().find("manifest entries")); + EXPECT_EQ(0, pool->CurrentUsage()); + + ASSERT_OK_AND_ASSIGN(auto split_limited, create_scan({32, 1, 0})); + auto split_refusal = split_limited->CreatePlan(); + EXPECT_TRUE(split_refusal.status().IsCapacityError()); + EXPECT_NE(std::string::npos, split_refusal.status().ToString().find("split limit")); + EXPECT_EQ(0, pool->CurrentUsage()); + + ASSERT_OK_AND_ASSIGN(auto exact, create_scan({32, 1, 1})); + ASSERT_OK_AND_ASSIGN(auto plan, exact->CreatePlan()); + EXPECT_EQ(1, plan->SnapshotId()); + EXPECT_EQ(1, plan->Splits().size()); +} + +TEST(AppendOnlyFileStoreScanTest, ControlledPlanCountsAcrossBaseAndDeltaWithLazyDecodeOff) { + const std::string path = GetDataDir() + "/avro/append_multiple.db/append_multiple"; + SnapshotManager snapshots(std::make_shared(), path); + ASSERT_OK_AND_ASSIGN(Snapshot snapshot, snapshots.LoadSnapshot(2)); + const auto fixture_scan = BuildScan(path, /*cache=*/nullptr); + std::vector manifests; + ASSERT_OK(fixture_scan->manifest_list_->ReadBaseManifests(snapshot, &manifests)); + ASSERT_EQ(1u, manifests.size()); + ASSERT_OK(fixture_scan->manifest_list_->ReadDeltaManifests(snapshot, &manifests)); + ASSERT_EQ(2u, manifests.size()); + ASSERT_NE(manifests[0].FileName(), manifests[1].FileName()); + for (const auto& manifest : manifests) { + ASSERT_EQ(3, manifest.NumAddedFiles()); + ASSERT_EQ(0, manifest.NumDeletedFiles()); + } + + auto delta = std::make_shared(manifests[1].FileName()); + std::shared_ptr pool = GetMemoryPool(); + auto create_scan = [&](const PlanningLimits& limits, + bool lazy = false) -> Result> { + ScanContextBuilder builder(path); + builder.AddOption(Options::SCAN_SNAPSHOT_ID, "2") + .AddOption(Options::SCAN_MANIFEST_ENTRY_LAZY_DECODE_ENABLED, lazy ? "true" : "false") + .SetPartitionFilter({{{"f1", "10"}}}) + .WithFileSystem(delta) + .WithMemoryPool(pool); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr context, builder.Finish()); + return TableScan::Create(std::move(context), limits); + }; + + ASSERT_OK_AND_ASSIGN(auto list_limited, create_scan({1, 6, 6})); + const auto list_refusal = list_limited->CreatePlan(); + EXPECT_TRUE(list_refusal.status().IsCapacityError()); + EXPECT_NE(std::string::npos, list_refusal.status().ToString().find("manifest list")); + EXPECT_EQ(0, delta->counts->opens.load()); + EXPECT_EQ(0, pool->CurrentUsage()); + + ASSERT_OK_AND_ASSIGN(auto entry_limited, create_scan({2, 5, 6})); + const auto entry_refusal = entry_limited->CreatePlan(); + EXPECT_TRUE(entry_refusal.status().IsCapacityError()); + EXPECT_NE(std::string::npos, entry_refusal.status().ToString().find("manifest entries")); + EXPECT_EQ(1, delta->counts->opens.load()); + EXPECT_EQ(0, delta->counts->live.load()); + EXPECT_EQ(0, pool->CurrentUsage()); + + for (bool lazy : {false, true}) { + SCOPED_TRACE(lazy); + const size_t entry_limit = lazy ? 4 : 6; + ASSERT_OK_AND_ASSIGN(auto exact, create_scan({2, entry_limit, 6}, lazy)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, exact->CreatePlan()); + EXPECT_EQ(2, plan->SnapshotId()); + EXPECT_FALSE(plan->Splits().empty()); + ASSERT_OK_AND_ASSIGN(uint64_t files, exact->GetMetrics()->GetCounter( + ScanMetrics::LAST_SCAN_RESULTED_TABLE_FILES)); + EXPECT_EQ(4, files); + } + EXPECT_EQ(3, delta->counts->opens.load()); + EXPECT_EQ(0, delta->counts->live.load()); + EXPECT_EQ(0, pool->CurrentUsage()); +} + +TEST(AppendOnlyFileStoreScanTest, PlanningLimitSharesParallelManifestLists) { + const std::string path = GetDataDir() + "/avro/append_multiple.db/append_multiple"; + SnapshotManager snapshots(std::make_shared(), path); + ASSERT_OK_AND_ASSIGN(Snapshot snapshot, snapshots.LoadSnapshot(2)); + const auto counted = std::make_shared(snapshot.DeltaManifestList()); + std::promise delta_open; + auto delta_seen = delta_open.get_future(); + counted->before_open = [&delta_open](const std::string&) { + delta_open.set_value(); + return Status::OK(); + }; + auto filesystem = std::make_shared(counted); + ASSERT_OK_AND_ASSIGN(std::unique_ptr workers, CreateDefaultExecutor(2)); + std::shared_ptr executor(std::move(workers)); + ScanContextBuilder builder(path); + builder.AddOption(Options::SCAN_SNAPSHOT_ID, "2") + .WithFileSystem(filesystem) + .WithExecutor(executor); + ASSERT_OK_AND_ASSIGN(auto context, builder.Finish()); + ASSERT_OK_AND_ASSIGN(auto scan, TableScan::Create(std::move(context), {1, 6, 3})); + + auto base = filesystem->BlockNext( + BlockingFileSystem::Operation::OPEN, + FileStorePathFactory::ManifestPath(path) + "/" + snapshot.BaseManifestList()); + auto result = std::async(std::launch::async, [&] { return scan->CreatePlan(); }); + EXPECT_TRUE(base->WaitForArrival()); + EXPECT_EQ(std::future_status::ready, delta_seen.wait_for(std::chrono::seconds(5))); + EXPECT_EQ(std::future_status::timeout, result.wait_for(std::chrono::milliseconds(0))); + base->Release(); + const auto plan = result.get(); + EXPECT_TRUE(plan.status().IsCapacityError()); + EXPECT_NE(std::string::npos, plan.status().ToString().find("manifest list")); + EXPECT_EQ(1, counted->counts->opens.load()); + EXPECT_EQ(0, counted->counts->live.load()); +} + +TEST(AppendOnlyFileStoreScanTest, ControlledPlanChargesEntriesBeforeDataPredicate) { + const std::string path = GetDataDir() + "/avro/append_multiple.db/append_multiple"; + std::shared_ptr pool = GetMemoryPool(); + auto make_context = [&](const std::shared_ptr& predicate) { + return ScanContextBuilder(path) + .AddOption(Options::SCAN_SNAPSHOT_ID, "2") + .AddOption(Options::SCAN_MANIFEST_ENTRY_LAZY_DECODE_ENABLED, "false") + .SetPredicate(predicate) + .WithMemoryPool(pool) + .Finish(); + }; + + const auto no_match = + PredicateBuilder::GreaterThan(3, "f3", FieldType::BIGINT, Literal(int64_t{100})); + ASSERT_OK_AND_ASSIGN(auto legacy_context, make_context(no_match)); + ASSERT_OK_AND_ASSIGN(auto legacy, TableScan::Create(std::move(legacy_context))); + ASSERT_OK_AND_ASSIGN(auto legacy_plan, legacy->CreatePlan()); + ASSERT_EQ(2, legacy_plan->SnapshotId()); + ASSERT_TRUE(legacy_plan->Splits().empty()); + legacy.reset(); + EXPECT_EQ(0, pool->CurrentUsage()); + + ASSERT_OK_AND_ASSIGN(auto limited_context, make_context(no_match)); + ASSERT_OK_AND_ASSIGN(auto limited, TableScan::Create(std::move(limited_context), {2, 5, 0})); + const auto refusal = limited->CreatePlan(); + EXPECT_TRUE(refusal.status().IsCapacityError()); + EXPECT_NE(std::string::npos, refusal.status().ToString().find("manifest entries")); + limited.reset(); + EXPECT_EQ(0, pool->CurrentUsage()); + + ASSERT_OK_AND_ASSIGN(auto exact_context, make_context(no_match)); + ASSERT_OK_AND_ASSIGN(auto exact, TableScan::Create(std::move(exact_context), {2, 6, 0})); + ASSERT_OK_AND_ASSIGN(auto plan, exact->CreatePlan()); + EXPECT_EQ(legacy_plan->SnapshotId(), plan->SnapshotId()); + EXPECT_TRUE(plan->Splits().empty()); + exact.reset(); + EXPECT_EQ(0, pool->CurrentUsage()); + + const auto selective = + PredicateBuilder::GreaterThan(0, "f0", FieldType::TINYINT, Literal(int8_t{4})); + ASSERT_OK_AND_ASSIGN(auto selected_context, make_context(selective)); + ASSERT_OK_AND_ASSIGN(auto selected, TableScan::Create(std::move(selected_context), {2, 6, 3})); + ASSERT_OK_AND_ASSIGN(auto selected_plan, selected->CreatePlan()); + EXPECT_EQ(2, selected_plan->SnapshotId()); + EXPECT_EQ(3, selected_plan->Splits().size()); + ASSERT_OK_AND_ASSIGN(uint64_t files, selected->GetMetrics()->GetCounter( + ScanMetrics::LAST_SCAN_RESULTED_TABLE_FILES)); + EXPECT_EQ(3, files); +} + +TEST(AppendOnlyFileStoreScanTest, ControlledPlanLimitsPackedSplits) { + const std::string path = GetDataDir() + "/avro/append_multiple.db/append_multiple"; + auto make_context = [&](std::optional row_limit = std::nullopt) { + ScanContextBuilder builder(path); + builder.AddOption(Options::SCAN_SNAPSHOT_ID, "2") + .AddOption(Options::SOURCE_SPLIT_TARGET_SIZE, "1GB"); + if (row_limit) { + builder.SetLimit(*row_limit); + } + return builder.Finish(); + }; + + ASSERT_OK_AND_ASSIGN(auto limited_context, make_context()); + ASSERT_OK_AND_ASSIGN(auto limited, TableScan::Create(std::move(limited_context), {2, 6, 2})); + const auto refusal = limited->CreatePlan(); + EXPECT_TRUE(refusal.status().IsCapacityError()); + EXPECT_NE(std::string::npos, refusal.status().ToString().find("split limit")); + + ASSERT_OK_AND_ASSIGN(auto exact_context, make_context()); + ASSERT_OK_AND_ASSIGN(auto exact, TableScan::Create(std::move(exact_context), {2, 6, 3})); + ASSERT_OK_AND_ASSIGN(auto plan, exact->CreatePlan()); + EXPECT_EQ(2, plan->SnapshotId()); + EXPECT_EQ(3, plan->Splits().size()); + + ASSERT_OK_AND_ASSIGN(auto default_context, make_context()); + ASSERT_OK_AND_ASSIGN(auto defaults, TableScan::Create(std::move(default_context), {})); + ASSERT_OK_AND_ASSIGN(auto default_plan, defaults->CreatePlan()); + EXPECT_EQ(3, default_plan->Splits().size()); + + ASSERT_OK_AND_ASSIGN(auto row_limit_context, make_context(1)); + ASSERT_OK_AND_ASSIGN(auto row_limited, TableScan::Create(std::move(row_limit_context))); + ASSERT_OK_AND_ASSIGN(auto row_limited_plan, row_limited->CreatePlan()); + EXPECT_EQ(1, row_limited_plan->Splits().size()); + + ASSERT_OK_AND_ASSIGN(auto both_limits_context, make_context(1)); + ASSERT_OK_AND_ASSIGN(auto both_limits, + TableScan::Create(std::move(both_limits_context), {2, 6, 2})); + const auto both_limits_refusal = both_limits->CreatePlan(); + EXPECT_TRUE(both_limits_refusal.status().IsCapacityError()); + EXPECT_NE(std::string::npos, both_limits_refusal.status().ToString().find("split limit")); +} + +TEST(AppendOnlyFileStoreScanTest, ControlledPlanCountsAcrossManySmallManifests) { + constexpr int32_t kManifestCount = 24; + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + const arrow::FieldVector fields = {arrow::field("f0", arrow::int32())}; + const std::map options = { + {Options::BUCKET, "1"}, + {Options::BUCKET_KEY, "f0"}, + {Options::FILE_FORMAT, "orc"}, + {Options::WRITE_ONLY, "true"}, + {Options::MANIFEST_MERGE_MIN_COUNT, "1000"}, + }; + // The fixture commits multiple snapshots through one writer, then plans a batch scan. + ASSERT_OK_AND_ASSIGN(std::unique_ptr writer, + TestHelper::Create(dir->Str(), arrow::schema(fields), {}, {}, options, + /*is_streaming_mode=*/true)); + for (int32_t i = 0; i < kManifestCount; ++i) { + ASSERT_OK_AND_ASSIGN( + std::unique_ptr batch, + TestHelper::MakeRecordBatch(arrow::struct_(fields), fmt::format("[[{}]]", i), {}, + /*bucket=*/0, {RecordBatch::RowKind::INSERT})); + ASSERT_OK(writer->WriteAndCommit(std::move(batch), i, std::nullopt)); + } + writer.reset(); + + const std::string path = dir->Str() + "/foo.db/bar"; + SnapshotManager snapshots(dir->GetFileSystem(), path); + ASSERT_OK_AND_ASSIGN(Snapshot snapshot, snapshots.LoadSnapshot(kManifestCount)); + const auto file_store_scan = BuildScan(path, /*cache=*/nullptr); + std::vector manifests; + ASSERT_OK(file_store_scan->manifest_list_->ReadDataManifests(snapshot, &manifests)); + ASSERT_EQ(kManifestCount, manifests.size()); + for (const auto& manifest : manifests) { + ASSERT_EQ(1, manifest.NumAddedFiles()); + ASSERT_EQ(0, manifest.NumDeletedFiles()); + } + + auto create_scan = + [&](const PlanningLimits& limits, + const std::shared_ptr& fs) -> Result> { + ScanContextBuilder builder(path); + builder.WithFileSystem(fs) + .AddOption(Options::SCAN_SNAPSHOT_ID, fmt::format("{}", kManifestCount)) + .AddOption(Options::SOURCE_SPLIT_TARGET_SIZE, "1GB"); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr context, builder.Finish()); + return TableScan::Create(std::move(context), limits); + }; + auto counted = std::make_shared(manifests.back().FileName()); + ASSERT_OK_AND_ASSIGN(auto list_limited, + create_scan({kManifestCount - 1, kManifestCount, 1}, counted)); + EXPECT_TRUE(list_limited->CreatePlan().status().IsCapacityError()); + EXPECT_EQ(0, counted->counts->opens.load()); + + ASSERT_OK_AND_ASSIGN(auto entries_limited, + create_scan({kManifestCount, kManifestCount - 1, 1}, counted)); + EXPECT_TRUE(entries_limited->CreatePlan().status().IsCapacityError()); + EXPECT_EQ(1, counted->counts->opens.load()); + EXPECT_EQ(0, counted->counts->live.load()); + + ASSERT_OK_AND_ASSIGN(auto exact, create_scan({kManifestCount, kManifestCount, 1}, counted)); + ASSERT_OK_AND_ASSIGN(auto plan, exact->CreatePlan()); + EXPECT_EQ(kManifestCount, plan->SnapshotId()); + ASSERT_EQ(1, plan->Splits().size()); + const auto split = std::dynamic_pointer_cast(plan->Splits().front()); + ASSERT_TRUE(split); + EXPECT_EQ(kManifestCount, split->GetFileList().size()); + EXPECT_EQ(2, counted->counts->opens.load()); + EXPECT_EQ(0, counted->counts->live.load()); +} + TEST(AppendOnlyFileStoreScanTest, PartitionPruningAcrossCacheModes) { auto dir = UniqueTestDirectory::Create(); ASSERT_TRUE(dir); diff --git a/src/paimon/core/operation/file_store_scan.cpp b/src/paimon/core/operation/file_store_scan.cpp index a40be6742..98615ee50 100644 --- a/src/paimon/core/operation/file_store_scan.cpp +++ b/src/paimon/core/operation/file_store_scan.cpp @@ -52,11 +52,13 @@ #include "paimon/core/schema/table_schema.h" #include "paimon/core/stats/simple_stats.h" #include "paimon/core/stats/simple_stats_evolution.h" +#include "paimon/core/table/source/planning_control.h" #include "paimon/core/utils/branch_manager.h" #include "paimon/core/utils/duration.h" #include "paimon/core/utils/field_mapping.h" #include "paimon/core/utils/snapshot_manager.h" #include "paimon/file_index/file_index_result.h" +#include "paimon/format/file_format.h" #include "paimon/memory/bytes.h" #include "paimon/memory/memory_segment.h" #include "paimon/predicate/literal.h" @@ -156,6 +158,9 @@ FileStoreScan::RawPlan::GroupFiles FileStoreScan::RawPlan::GroupByPartFiles( } Result> FileStoreScan::ReadPartitionEntries() const { + if (planning_control_) { + return Status::NotImplemented("controlled planning applies only to CreatePlan"); + } std::optional snapshot; std::vector all_manifest_file_metas; std::vector filtered_manifest_file_metas; @@ -178,6 +183,7 @@ Result> FileStoreScan::ReadPartitionEntries() const } Result> FileStoreScan::CreatePlan() const { + PAIMON_RETURN_NOT_OK(ValidateControlledScanProfile()); Duration duration; Duration manifest_read_duration; metrics_->SetCounter(ScanMetrics::LAST_SNAPSHOT_CACHE_LOAD_DURATION, 0); @@ -312,6 +318,21 @@ Status FileStoreScan::ReadManifestLists(const std::optional& snapshot, return Status::OK(); } +Status FileStoreScan::ValidateControlledScanProfile() const { + if (!planning_control_) { + return Status::OK(); + } + if (scan_mode_ != ScanMode::ALL || !table_schema_->PrimaryKeys().empty() || + core_options_.DataEvolutionEnabled() || core_options_.DeletionVectorsEnabled() || + core_options_.GetCache() || core_options_.GetManifestFormat()->Identifier() != "avro" || + row_range_index_) { + return Status::NotImplemented( + "controlled planning requires an uncached append-only Avro full snapshot " + "without row ranges"); + } + return Status::OK(); +} + Status FileStoreScan::ReadManifestsWithSnapshot(const Snapshot& snapshot, std::vector* manifests) const { switch (scan_mode_) { @@ -322,8 +343,11 @@ Status FileStoreScan::ReadManifestsWithSnapshot(const Snapshot& snapshot, // ReadDataManifests produced. auto read_list = [this, &snapshot](bool base) -> Result> { std::vector metas; - PAIMON_RETURN_NOT_OK(base ? manifest_list_->ReadBaseManifests(snapshot, &metas) - : manifest_list_->ReadDeltaManifests(snapshot, &metas)); + auto* row_limit = + planning_control_ ? &planning_control_->manifest_list_rows : nullptr; + PAIMON_RETURN_NOT_OK( + base ? manifest_list_->ReadBaseManifests(snapshot, &metas, row_limit) + : manifest_list_->ReadDeltaManifests(snapshot, &metas, row_limit)); return metas; }; std::vector>>> futures; @@ -341,7 +365,10 @@ Status FileStoreScan::ReadManifestsWithSnapshot(const Snapshot& snapshot, Via(executor_.get(), [read_list]() { return read_list(/*base=*/false); })); for (auto& metas : CollectAll(futures)) { if (!metas.ok()) { - return metas.status(); + const auto& status = metas.status(); + return planning_control_ && status.IsCapacityError() + ? status.WithMessage("manifest list: ", status.message()) + : status; } for (auto& meta : metas.value()) { manifests->emplace_back(std::move(meta)); @@ -375,11 +402,12 @@ Status FileStoreScan::ReadFileEntries(const std::vector& manif auto read_meta_task = [this, meta, apply_scan_filter]() -> Result> { std::vector tmp_entries; + auto* row_limit = planning_control_ ? &planning_control_->manifest_entry_rows : nullptr; if (apply_scan_filter) { - PAIMON_RETURN_NOT_OK(ReadManifestFileMeta(meta, &tmp_entries)); + PAIMON_RETURN_NOT_OK(ReadManifestFileMeta(meta, &tmp_entries, row_limit)); } else { - PAIMON_RETURN_NOT_OK(manifest_file_->Read(meta.FileName(), /*filter=*/nullptr, - meta.FileSize(), &tmp_entries)); + PAIMON_RETURN_NOT_OK(manifest_file_->Read( + meta.FileName(), /*filter=*/nullptr, meta.FileSize(), &tmp_entries, row_limit)); } return tmp_entries; }; @@ -390,7 +418,10 @@ Status FileStoreScan::ReadFileEntries(const std::vector& manif auto unfiltered_entries = CollectAll(futures); for (auto& entry_list : unfiltered_entries) { if (!entry_list.ok()) { - return entry_list.status(); + const auto& status = entry_list.status(); + return planning_control_ && status.IsCapacityError() + ? status.WithMessage("manifest entries: ", status.message()) + : status; } manifest_entries->reserve(manifest_entries->size() + entry_list.value().size()); for (auto& entry : entry_list.value()) { @@ -669,7 +700,8 @@ bool FileStoreScan::FilterManifestByRowRanges(const ManifestFileMeta& manifest) } Status FileStoreScan::ReadManifestFileMeta(const ManifestFileMeta& manifest, - std::vector* entries) const { + std::vector* entries, + ManifestRowLimit* row_limit) const { const RowRangeIndex* row_ranges = nullptr; if (row_range_index_ && core_options_.DataEvolutionEnabled() && core_options_.ScanManifestEntryLazyDecodeEnabled()) { @@ -683,7 +715,7 @@ Status FileStoreScan::ReadManifestFileMeta(const ManifestFileMeta& manifest, return partition_filtered ? FilterNonPartitionManifestEntry(entry) : FilterManifestEntry(entry); }, - entries); + entries, row_limit); } std::function(const InternalRow&)> FileStoreScan::CreateManifestEntryRowFilter( diff --git a/src/paimon/core/operation/file_store_scan.h b/src/paimon/core/operation/file_store_scan.h index df8c6d614..8a8e1eb60 100644 --- a/src/paimon/core/operation/file_store_scan.h +++ b/src/paimon/core/operation/file_store_scan.h @@ -19,6 +19,7 @@ #pragma once #include +#include #include #include #include @@ -67,6 +68,7 @@ class InternalRow; class ManifestFile; class ManifestFileMeta; class ManifestList; +class ManifestRowLimit; class MemoryPool; class Predicate; class ScanFilter; @@ -75,6 +77,7 @@ class SimpleStatsEvolution; class SnapshotManager; class TableSchema; struct DataFileMeta; +struct PlanningControl; /// Scan operation which produces a plan. class FileStoreScan { @@ -111,6 +114,16 @@ class FileStoreScan { return this; } + void WithPlanningControl(std::shared_ptr control) { + planning_control_ = std::move(control); + } + + const std::shared_ptr& GetPlanningControl() const { + return planning_control_; + } + + Status ValidateControlledScanProfile() const; + const std::optional& GetSpecifiedSnapshot() const { return specified_snapshot_; } @@ -322,7 +335,8 @@ class FileStoreScan { bool FilterManifestByRowRanges(const ManifestFileMeta& manifest) const; Status ReadManifestFileMeta(const ManifestFileMeta& manifest, - std::vector* entries) const; + std::vector* entries, + ManifestRowLimit* row_limit = nullptr) const; /// If provided, predicate_failed must initially be false and outlive the synchronous callback. /// Only predicate evaluation errors set it; partition decoding errors leave it unchanged. @@ -356,6 +370,7 @@ class FileStoreScan { std::function level_filter_; std::optional specified_snapshot_; std::shared_ptr metrics_; + std::shared_ptr planning_control_; std::string table_path_; bool drop_stats_ = false; }; diff --git a/src/paimon/core/table/source/data_table_batch_scan.cpp b/src/paimon/core/table/source/data_table_batch_scan.cpp index e06e665aa..7c09c91e9 100644 --- a/src/paimon/core/table/source/data_table_batch_scan.cpp +++ b/src/paimon/core/table/source/data_table_batch_scan.cpp @@ -28,6 +28,7 @@ #include "paimon/core/table/bucket_mode.h" #include "paimon/core/table/source/data_split_impl.h" #include "paimon/core/table/source/plan_impl.h" +#include "paimon/core/table/source/planning_control.h" #include "paimon/core/table/source/snapshot/snapshot_reader.h" #include "paimon/status.h" @@ -64,6 +65,11 @@ DataTableBatchScan::DataTableBatchScan(bool pk_table, const CoreOptions& core_op } } +Status DataTableBatchScan::SetPlanningLimits(const PlanningLimits& limits) { + return snapshot_reader_->SetPlanningControl(std::make_shared( + limits.max_manifest_list_rows, limits.max_manifest_entry_rows, limits.max_splits)); +} + Result> DataTableBatchScan::CreatePlan() { if (starting_scanner_ == nullptr) { PAIMON_ASSIGN_OR_RAISE(starting_scanner_, CreateStartingScanner(/*is_streaming=*/false)); diff --git a/src/paimon/core/table/source/data_table_batch_scan.h b/src/paimon/core/table/source/data_table_batch_scan.h index 4f0ef65e3..842eb8e15 100644 --- a/src/paimon/core/table/source/data_table_batch_scan.h +++ b/src/paimon/core/table/source/data_table_batch_scan.h @@ -41,6 +41,8 @@ class DataTableBatchScan : public AbstractTableScan { Result> CreatePlan() override; + Status SetPlanningLimits(const PlanningLimits& limits); + std::shared_ptr GetNonPartitionPredicate() const { return snapshot_reader_->GetNonPartitionPredicate(); } diff --git a/src/paimon/core/table/source/planning_control.h b/src/paimon/core/table/source/planning_control.h new file mode 100644 index 000000000..0390b1e09 --- /dev/null +++ b/src/paimon/core/table/source/planning_control.h @@ -0,0 +1,59 @@ +/* + * 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 +#include + +#include "paimon/status.h" + +namespace paimon { + +/// One cumulative object allowance shared by tasks in a single scan. +class ManifestRowLimit { + public: + explicit ManifestRowLimit(size_t rows) : remaining_(rows) {} + + Status Admit(size_t rows) { + auto remaining = remaining_.load(std::memory_order_relaxed); + while (rows <= remaining) { + if (remaining_.compare_exchange_weak(remaining, remaining - rows, + std::memory_order_relaxed)) { + return Status::OK(); + } + } + return Status::CapacityError("manifest object row limit exceeded"); + } + + private: + std::atomic remaining_; +}; + +/// Per-plan object allowances. Counters do not govern decoder or buffer allocations. +struct PlanningControl { + PlanningControl(size_t list_rows, size_t entry_rows, size_t splits) + : manifest_list_rows(list_rows), manifest_entry_rows(entry_rows), split_count(splits) {} + + ManifestRowLimit manifest_list_rows; + ManifestRowLimit manifest_entry_rows; + const size_t split_count; +}; + +} // namespace paimon diff --git a/src/paimon/core/table/source/snapshot/snapshot_reader.cpp b/src/paimon/core/table/source/snapshot/snapshot_reader.cpp index 0e98b5cf7..1bfb3848c 100644 --- a/src/paimon/core/table/source/snapshot/snapshot_reader.cpp +++ b/src/paimon/core/table/source/snapshot/snapshot_reader.cpp @@ -36,6 +36,7 @@ #include "paimon/core/snapshot.h" #include "paimon/core/table/source/data_split_impl.h" #include "paimon/core/table/source/plan_impl.h" +#include "paimon/core/table/source/planning_control.h" #include "paimon/core/utils/file_store_path_factory.h" namespace paimon { @@ -55,6 +56,7 @@ Result>> SnapshotReader::GenerateSplits( const std::unique_ptr& split_generator, FileStoreScan::RawPlan::GroupFiles&& grouped_manifest_entries) const { std::vector> splits; + const auto& control = GetPlanningControl(); // Read deletion indexes at once to reduce file IO std::unordered_map, std::vector>> deletion_index_files_map; @@ -86,6 +88,9 @@ Result>> SnapshotReader::GenerateSplits( PAIMON_ASSIGN_OR_RAISE(split_groups, split_generator->SplitForBatch(std::move(files))); } + if (control && split_groups.size() > control->split_count - splits.size()) { + return Status::CapacityError("split limit exceeded"); + } for (auto& split_group : split_groups) { std::vector>& data_files = split_group.files; PAIMON_ASSIGN_OR_RAISE(std::string bucket_path, diff --git a/src/paimon/core/table/source/snapshot/snapshot_reader.h b/src/paimon/core/table/source/snapshot/snapshot_reader.h index 6faadb9fe..41e25976a 100644 --- a/src/paimon/core/table/source/snapshot/snapshot_reader.h +++ b/src/paimon/core/table/source/snapshot/snapshot_reader.h @@ -48,6 +48,15 @@ struct DataFileMeta; class SnapshotReader { public: + Status SetPlanningControl(std::shared_ptr control) { + scan_->WithPlanningControl(std::move(control)); + return scan_->ValidateControlledScanProfile(); + } + + const std::shared_ptr& GetPlanningControl() const { + return scan_->GetPlanningControl(); + } + SnapshotReader(const std::shared_ptr& scan, const std::shared_ptr& path_factory, std::unique_ptr&& split_generator, diff --git a/src/paimon/core/table/source/table_scan_test.cpp b/src/paimon/core/table/source/table_scan_test.cpp index 435e2254f..9c9442126 100644 --- a/src/paimon/core/table/source/table_scan_test.cpp +++ b/src/paimon/core/table/source/table_scan_test.cpp @@ -67,6 +67,34 @@ TEST(TableScanTest, TestNoSnapshot) { ASSERT_OK_AND_ASSIGN(auto plan, table_scan->CreatePlan()); ASSERT_FALSE(plan->SnapshotId()); ASSERT_TRUE(plan->Splits().empty()); + + builder.AddOption("manifest.format", "avro"); + ASSERT_OK_AND_ASSIGN(context, builder.Finish()); + ASSERT_OK_AND_ASSIGN(table_scan, TableScan::Create(std::move(context), {0, 0, 0})); + ASSERT_OK_AND_ASSIGN(plan, table_scan->CreatePlan()); + EXPECT_FALSE(plan->SnapshotId()); + EXPECT_TRUE(plan->Splits().empty()); + + builder.AddOption("manifest.format", "orc"); + ASSERT_OK_AND_ASSIGN(context, builder.Finish()); + auto unsupported = TableScan::Create(std::move(context), {0, 0, 0}); + EXPECT_TRUE(unsupported.status().IsNotImplemented()); +} + +TEST(TableScanTest, ControlledScanRejectsDelegatedSystemTable) { + const std::string path = + GetDataDir() + "/orc/append_table_with_nested_type.db/append_table_with_nested_type$ro"; + ScanContextBuilder builder(path); + builder.AddOption("manifest.format", "avro"); + ASSERT_OK_AND_ASSIGN(std::unique_ptr context, builder.Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr legacy, TableScan::Create(std::move(context))); + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, legacy->CreatePlan()); + EXPECT_TRUE(plan->Splits().empty()); + + builder.AddOption("manifest.format", "avro"); + ASSERT_OK_AND_ASSIGN(context, builder.Finish()); + auto controlled = TableScan::Create(std::move(context), {32, 32, 32}); + EXPECT_TRUE(controlled.status().IsNotImplemented()); } TEST(TableScanTest, TestNonExistTable) { diff --git a/src/paimon/core/table/table_factory.cpp b/src/paimon/core/table/table_factory.cpp index b9a2bc6b1..f7489c3e3 100644 --- a/src/paimon/core/table/table_factory.cpp +++ b/src/paimon/core/table/table_factory.cpp @@ -37,6 +37,7 @@ #include "paimon/core/schema/table_schema.h" #include "paimon/core/table/file_store_table.h" #include "paimon/core/table/format/format_table_loader.h" +#include "paimon/core/table/source/data_table_batch_scan.h" #include "paimon/core/table/system/system_table.h" #include "paimon/core/utils/branch_manager.h" #include "paimon/core/utils/context_utils.h" @@ -375,6 +376,22 @@ Result> TableScan::Create(std::unique_ptrNewScan(std::move(context)); } +Result> TableScan::Create(std::unique_ptr context, + const PlanningLimits& limits) { + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr table, TableFactory::Create(context.get())); + // Some system tables delegate NewScan and return an ordinary managed batch scan. + if (dynamic_cast(table.get()) == nullptr) { + return Status::NotImplemented("planning limits require a managed data table"); + } + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr scan, table->NewScan(std::move(context))); + auto* batch = dynamic_cast(scan.get()); + if (!batch) { + return Status::NotImplemented("planning limits require an unwrapped managed batch scan"); + } + PAIMON_RETURN_NOT_OK(batch->SetPlanningLimits(limits)); + return scan; +} + Result> TableRead::Create(std::unique_ptr context) { PAIMON_RETURN_NOT_OK(ContextUtils::CheckOperatorContext(context, "read")); PAIMON_ASSIGN_OR_RAISE(std::shared_ptr
table, TableFactory::Create(context.get())); diff --git a/src/paimon/core/table/table_test.cpp b/src/paimon/core/table/table_test.cpp index 78b14adc0..0a682db85 100644 --- a/src/paimon/core/table/table_test.cpp +++ b/src/paimon/core/table/table_test.cpp @@ -1152,6 +1152,12 @@ TEST(TableTest, TestQueryAuthScanPushesTheLimitPastARowFilterOnPartitionKeys) { ASSERT_EQ(2u, plan->Splits().size()); ASSERT_OK_AND_ASSIGN(plan, PlanQueryAuth(path, catalog, /*predicate=*/nullptr, /*limit=*/1)); ASSERT_EQ(1u, plan->Splits().size()); + + ScanContextBuilder builder(path); + builder.WithCatalog(catalog, Identifier("foo", "bar")); + ASSERT_OK_AND_ASSIGN(std::unique_ptr context, builder.Finish()); + const auto unsupported = TableScan::Create(std::move(context), {32, 32, 32}); + EXPECT_TRUE(unsupported.status().IsNotImplemented()); } TEST(TableTest, TestQueryAuthTableAppliesTheSameRulesToEachFileFormat) { diff --git a/src/paimon/core/utils/objects_file.h b/src/paimon/core/utils/objects_file.h index 36ba10e05..2fe7bc1cb 100644 --- a/src/paimon/core/utils/objects_file.h +++ b/src/paimon/core/utils/objects_file.h @@ -18,6 +18,8 @@ #pragma once +#include +#include #include #include #include @@ -40,6 +42,7 @@ #include "paimon/common/utils/path_util.h" #include "paimon/common/utils/scope_guard.h" #include "paimon/core/io/meta_to_arrow_array_converter.h" +#include "paimon/core/table/source/planning_control.h" #include "paimon/core/utils/manifest_meta_reader.h" #include "paimon/core/utils/object_serializer.h" #include "paimon/core/utils/path_factory.h" @@ -69,8 +72,11 @@ class ObjectsFile { /// skip the metadata request a bare `Open` issues on a remote store. Pass /// std::nullopt when the length is not known; the read then discovers it /// itself. + /// @param row_limit Optional cumulative count of objects admitted for decoding. The reader may + /// already hold a decoded Arrow batch when it checks this limit. Status Read(const std::string& file_name, const std::function(const T&)>& filter, - std::optional file_size, std::vector* result) const; + std::optional file_size, std::vector* result, + ManifestRowLimit* row_limit = nullptr) const; Status ReadIfFileExist(const std::string& file_name, const std::function(const T&)>& filter, std::optional file_size, std::vector* result) const; @@ -97,7 +103,8 @@ class ObjectsFile { Status ReadArrowBatches( const std::string& file_name, std::optional file_size, const std::function&)>& consumer, - const std::function*)>& prepare_reader) const; + const std::function*)>& prepare_reader, + bool allow_cache = true) const; std::shared_ptr path_factory_; std::shared_ptr pool_; @@ -165,10 +172,19 @@ Status ObjectsFile::ReadIfFileExist(const std::string& file_name, template Status ObjectsFile::Read(const std::string& file_name, const std::function(const T&)>& filter, - std::optional file_size, std::vector* result) const { + std::optional file_size, std::vector* result, + ManifestRowLimit* row_limit) const { return ReadArrowBatches( file_name, file_size, - [this, &filter, result](const std::shared_ptr& struct_array) -> Status { + [this, &filter, result, + row_limit](const std::shared_ptr& struct_array) -> Status { + if (row_limit) { + auto rows = static_cast(struct_array->length()); + if (rows > result->max_size() - result->size()) { + return Status::CapacityError("manifest object row limit exceeded"); + } + PAIMON_RETURN_NOT_OK(row_limit->Admit(static_cast(rows))); + } result->reserve(result->size() + struct_array->length()); const arrow::ArrayVector& fields = struct_array->fields(); ColumnarRow row(fields, pool_, /*row_id=*/0); @@ -186,7 +202,7 @@ Status ObjectsFile::Read(const std::string& file_name, } return Status::OK(); }, - /*prepare_reader=*/nullptr); + /*prepare_reader=*/nullptr, /*allow_cache=*/!row_limit); } template @@ -313,10 +329,14 @@ template Status ObjectsFile::ReadArrowBatches( const std::string& file_name, std::optional file_size, const std::function&)>& consumer, - const std::function*)>& prepare_reader) const { + const std::function*)>& prepare_reader, + bool allow_cache) const { if (!cache_) { return ReadUncachedArrowBatches(file_name, file_size, consumer, prepare_reader); } + if (!allow_cache) { + return Status::NotImplemented("manifest planning controls require an uncached reader"); + } const std::string path = path_factory_->ToPath(file_name); auto key = CacheKey::ForKind(path, /*position=*/0, /*length=*/-1, CacheKind::MANIFEST); std::optional read_status;