From 97f132042a8b17b292dcfb2abd772b433c8a7b04 Mon Sep 17 00:00:00 2001 From: "lisizhuo.lsz" Date: Thu, 26 Nov 2026 08:38:38 +0000 Subject: [PATCH 1/2] feat(read): support predicates on non-projected fields --- docs/source/user_guide/file_index.rst | 7 +- docs/source/user_guide/format_table.rst | 5 +- docs/source/user_guide/realtime.rst | 5 +- include/paimon/predicate/predicate_builder.h | 8 +- include/paimon/read_context.h | 11 +- include/paimon/scan_context.h | 3 +- src/paimon/CMakeLists.txt | 2 + .../common/predicate/predicate_validator.h | 19 +- .../predicate/predicate_validator_test.cpp | 163 ++++-------------- .../late_materializing_file_batch_reader.cpp | 4 +- .../common/reader/predicate_batch_reader.cpp | 3 +- .../common/reader/projection_batch_reader.cpp | 103 +++++++++++ .../common/reader/projection_batch_reader.h | 64 +++++++ .../reader/projection_batch_reader_test.cpp | 146 ++++++++++++++++ src/paimon/common/table/special_fields.h | 23 +++ .../common/table/special_fields_test.cpp | 30 ++++ .../global_index/global_index_scan_impl.cpp | 14 ++ .../complete_row_tracking_fields_reader.cpp | 9 +- src/paimon/core/manifest/manifest_file.cpp | 4 +- .../core/operation/abstract_split_read.cpp | 8 +- .../operation/data_evolution_split_read.cpp | 23 ++- .../operation/data_evolution_split_read.h | 4 +- src/paimon/core/operation/file_store_scan.cpp | 19 +- .../core/operation/internal_read_context.cpp | 59 +++++-- .../core/operation/internal_read_context.h | 16 +- .../operation/internal_read_context_test.cpp | 83 +++++++-- .../core/operation/merge_file_split_read.cpp | 20 ++- .../core/operation/merge_file_split_read.h | 4 +- .../core/operation/raw_file_split_read.cpp | 11 +- .../core/operation/raw_file_split_read.h | 3 +- src/paimon/core/table/file_store_table.cpp | 22 ++- .../core/table/format/format_table_read.cpp | 46 +++-- .../core/table/format/format_table_test.cpp | 45 +++-- .../table/source/append_only_table_read.cpp | 18 ++ .../source/data_evolution_full_text_read.cpp | 3 +- .../data_evolution_full_text_read_test.cpp | 3 +- .../table/source/filtered_row_id_reader.cpp | 18 +- .../table/source/full_text_search_builder.cpp | 12 +- .../table/source/query_auth_table_read.cpp | 75 ++++---- .../core/table/source/query_auth_table_read.h | 10 +- .../source/query_auth_table_read_test.cpp | 74 +++++++- .../table/source/query_auth_table_scan.cpp | 9 + .../core/table/source/table_read_test.cpp | 115 ++++++++---- .../core/table/source/topk_batch_reader.cpp | 3 +- src/paimon/core/utils/read_schema_plan.h | 83 +++++++++ test/inte/data_evolution_table_test.cpp | 9 + test/inte/read_inte_test.cpp | 44 +++++ test/inte/realtime_write_inte_test.cpp | 116 ++++++++++--- .../write_and_read_inte_with_index_test.cpp | 10 +- 49 files changed, 1207 insertions(+), 381 deletions(-) create mode 100644 src/paimon/common/reader/projection_batch_reader.cpp create mode 100644 src/paimon/common/reader/projection_batch_reader.h create mode 100644 src/paimon/common/reader/projection_batch_reader_test.cpp create mode 100644 src/paimon/core/utils/read_schema_plan.h diff --git a/docs/source/user_guide/file_index.rst b/docs/source/user_guide/file_index.rst index 5a8378748..236f05d43 100644 --- a/docs/source/user_guide/file_index.rst +++ b/docs/source/user_guide/file_index.rst @@ -46,9 +46,10 @@ whose query uses the same JSON DSL as ``FullTextSearch``. Do not modify a reques after passing it to a predicate or read context. Compose full-text and scalar predicates with the existing -``PredicateBuilder::And`` and ``PredicateBuilder::Or`` factories. Every field -referenced by this tree must appear in the read schema; field indices refer to -positions in that schema. For example, the following constructs +``PredicateBuilder::And`` and ``PredicateBuilder::Or`` factories. Referenced fields +need not appear in the output projection; field indices refer to zero-based +positions in the complete table schema. For example, for a table whose first two +columns are ``body`` and ``price``, the following constructs ``body matches "apple" OR price < 10``: .. code-block:: cpp diff --git a/docs/source/user_guide/format_table.rst b/docs/source/user_guide/format_table.rst index 5bef8f4b9..f3b83d18e 100644 --- a/docs/source/user_guide/format_table.rst +++ b/docs/source/user_guide/format_table.rst @@ -85,8 +85,9 @@ is read past. A column the file does not hold is filled with nulls, which is how before a column was added is still read - unless the table declares that column ``NOT NULL``, when the file is refused instead, as Java's ``VectorizedParquetRecordReader`` refuses it. Only the columns a read actually asks a file for are held to the table's schema: a partition column is -rebuilt from the directory name whether or not the file stores one of its own, and a column -outside the projection is never read, which is how Java scopes the same checks. +rebuilt from the directory name whether or not the file stores one of its own. The internal +read schema includes both projected columns and predicate dependencies; columns needed only +for a predicate are removed from the final output after filtering. ``FormatTable`` is the only format-table type in the public API. The classes behind it - ``FormatTableScan``, ``FormatTableRead``, ``FormatTableWrite``, ``FormatTableCommit``, diff --git a/docs/source/user_guide/realtime.rst b/docs/source/user_guide/realtime.rst index 4b4479a9c..efcceb6cd 100644 --- a/docs/source/user_guide/realtime.rst +++ b/docs/source/user_guide/realtime.rst @@ -431,8 +431,9 @@ For ``id = 7 AND score > 100``, an index supporting equality on ``id`` selects candidate offsets; statistics can then skip batches whose maximum ``score`` is at most 100. Statistics cover entire batches, so mixed batches still need row-level -filtering. Keep predicate fields in the read schema and enable -``ReadContextBuilder::EnablePredicateFilter(true)`` for exact filtering. +filtering. Enable ``ReadContextBuilder::EnablePredicateFilter(true)`` for exact +filtering. Predicate indices refer to the complete table schema; the reader +fetches any unprojected predicate columns internally. In-memory and disk indexes are configured independently. Use ``file-index..columns`` to enable indexes for committed files. diff --git a/include/paimon/predicate/predicate_builder.h b/include/paimon/predicate/predicate_builder.h index 1f2c98856..117bf28e8 100644 --- a/include/paimon/predicate/predicate_builder.h +++ b/include/paimon/predicate/predicate_builder.h @@ -35,6 +35,8 @@ enum class FieldType; /// /// PredicateBuilder provides static factory methods to create various types of predicates /// that can be used for filtering data in Paimon tables. +/// For table queries, field_index is the zero-based position in the complete table schema, +/// not a persistent field ID or a position in the output projection. class PAIMON_EXPORT PredicateBuilder { public: PredicateBuilder() = delete; @@ -43,7 +45,7 @@ class PAIMON_EXPORT PredicateBuilder { /// Create a full-text predicate returning all matching rows without TopK truncation. /// The field must have STRING type and a full-text index. /// Project `__INDEX_SCORE` in the read schema to request score output. - /// @param field_index The index of the field in read schema (0-based). + /// @param field_index The index of the field in the complete table schema (0-based). /// @param match The full-text request, including the field name, JSON DSL query and /// optional eligible row ids. static Result> FullTextMatch( @@ -51,7 +53,7 @@ class PAIMON_EXPORT PredicateBuilder { /// Create an equality predicate (field == literal). /// - /// @param field_index The index of the field in read schema (0-based). + /// @param field_index The index of the field in the complete table schema (0-based). /// @param field_name The name of the field. /// @param field_type The data type of the field. /// @param literal The literal value to compare against. @@ -113,7 +115,7 @@ class PAIMON_EXPORT PredicateBuilder { /// /// Tests whether the field value falls within the specified range (inclusive on both ends). /// - /// @param field_index The index of the field in read schema (0-based). + /// @param field_index The index of the field in the complete table schema (0-based). /// @param field_name The name of the field. /// @param field_type The data type of the field. /// @param included_lower_bound The lower bound of the range (inclusive). diff --git a/include/paimon/read_context.h b/include/paimon/read_context.h index dbefd974a..4e12c2222 100644 --- a/include/paimon/read_context.h +++ b/include/paimon/read_context.h @@ -358,13 +358,12 @@ class PAIMON_EXPORT ReadContextBuilder { /// It can significantly improve performance by reducing the amount of data /// that needs to be read and processed. /// - /// All referenced fields, including full-text match fields, must be projected in the read - /// schema. - /// TODO(lisizhuo.lsz): Align with Java Paimon so fields referenced by predicates no longer need - /// to appear in the projection. + /// Referenced fields, including full-text match fields, need not be projected. Field indices + /// are zero-based positions in the complete table schema, not field IDs or projection indices. /// Full-text matches can be combined with scalar predicates using PredicateBuilder::And/Or. - /// Predicates on virtual index score columns (_INDEX_SCORE or __INDEX_SCORE) are not - /// supported. + /// Supplied indices are not validated; execution positions are bound by field name. + /// Among system fields, only _ROW_ID and _SEQUENCE_NUMBER support user predicates, subject + /// to their option requirements. Their indices do not require fixed table-schema positions. /// /// @param predicate Shared pointer to the predicate for data filtering. /// @return Reference to this builder for method chaining. diff --git a/include/paimon/scan_context.h b/include/paimon/scan_context.h index 93f3ba2db..d8d8a8cc9 100644 --- a/include/paimon/scan_context.h +++ b/include/paimon/scan_context.h @@ -216,7 +216,8 @@ class PAIMON_EXPORT ScanContextBuilder { /// partition_filters is {{k1=1,k2=10}, {k1=2,k2=20}} => OR(AND(k1=1,k2=10), AND(k1=2,k2=20)) ScanContextBuilder& SetPartitionFilter( const std::vector>& partition_filters); - /// Set a predicate for filtering data. + /// Set a predicate for filtering data. Field indices are zero-based positions in the + /// complete table schema, independently of the requested output fields. ScanContextBuilder& SetPredicate(const std::shared_ptr& predicate); /// Set the columns the query reads. A table with `query-auth.enabled=true` asks its catalog /// for the rules of these columns plus those of the predicate and the partition filter; by diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt index 4ab30167d..f70fd456d 100644 --- a/src/paimon/CMakeLists.txt +++ b/src/paimon/CMakeLists.txt @@ -156,6 +156,7 @@ set(PAIMON_COMMON_SRCS common/reader/late_materializing_file_batch_reader.cpp common/reader/data_file_reader_factory.cpp common/reader/predicate_batch_reader.cpp + common/reader/projection_batch_reader.cpp common/reader/prefetch_file_batch_reader_impl.cpp common/reader/reader_utils.cpp common/reader/blob_fallback_batch_reader.cpp @@ -750,6 +751,7 @@ if(PAIMON_BUILD_TESTS) common/reader/data_file_reader_factory_test.cpp common/reader/late_materializing_file_batch_reader_test.cpp common/reader/predicate_batch_reader_test.cpp + common/reader/projection_batch_reader_test.cpp common/reader/prefetch_file_batch_reader_impl_test.cpp common/reader/reader_utils_test.cpp common/reader/complete_row_kind_batch_reader_test.cpp diff --git a/src/paimon/common/predicate/predicate_validator.h b/src/paimon/common/predicate/predicate_validator.h index 00241723f..a0273293b 100644 --- a/src/paimon/common/predicate/predicate_validator.h +++ b/src/paimon/common/predicate/predicate_validator.h @@ -45,10 +45,9 @@ class PredicateValidator { ~PredicateValidator() = delete; static Status ValidatePredicateWithSchema(const arrow::Schema& schema, - const std::shared_ptr& predicate, - bool validate_field_idx) { + const std::shared_ptr& predicate) { PAIMON_RETURN_NOT_OK(ValidatePredicateWithLiterals(predicate)); - return ValidatePredicateWithSchemaImpl(schema, predicate, validate_field_idx); + return ValidatePredicateWithSchemaImpl(schema, predicate); } private: @@ -90,22 +89,15 @@ class PredicateValidator { } static Status ValidatePredicateWithSchemaImpl(const arrow::Schema& schema, - const std::shared_ptr& predicate, - bool validate_field_idx) { + const std::shared_ptr& predicate) { if (auto leaf_predicate = std::dynamic_pointer_cast(predicate)) { const auto& field_name = leaf_predicate->FieldName(); - // check field index + // check field existence int32_t schema_field_idx = schema.GetFieldIndex(field_name); if (schema_field_idx == -1) { return Status::Invalid( fmt::format("field {} does not exist in schema", field_name)); } - if (validate_field_idx && schema_field_idx != leaf_predicate->FieldIndex()) { - return Status::Invalid( - fmt::format("field {} has field idx {} in input schema, mismatch field idx " - "{} in predicate", - field_name, schema_field_idx, leaf_predicate->FieldIndex())); - } // check field type (schema vs. predicate) const std::shared_ptr& schema_type = schema.field(schema_field_idx)->type(); @@ -121,8 +113,7 @@ class PredicateValidator { std::dynamic_pointer_cast(predicate)) { const auto& children = compound_predicate->Children(); for (const auto& child : children) { - PAIMON_RETURN_NOT_OK( - ValidatePredicateWithSchemaImpl(schema, child, validate_field_idx)); + PAIMON_RETURN_NOT_OK(ValidatePredicateWithSchemaImpl(schema, child)); } } return Status::OK(); diff --git a/src/paimon/common/predicate/predicate_validator_test.cpp b/src/paimon/common/predicate/predicate_validator_test.cpp index 487482db9..6c25f833b 100644 --- a/src/paimon/common/predicate/predicate_validator_test.cpp +++ b/src/paimon/common/predicate/predicate_validator_test.cpp @@ -32,25 +32,19 @@ class Schema; } // namespace arrow namespace paimon::test { -TEST(PredicateValidatorTest, TestFullTextMatchRequiresProjectedStringField) { +TEST(PredicateValidatorTest, TestFullTextMatchRequiresStringField) { auto schema = arrow::schema({arrow::field("id", arrow::int32()), arrow::field("text", arrow::utf8())}); auto match = std::make_shared("text", R"({"match":{"query":"apple"}})"); ASSERT_OK_AND_ASSIGN(std::shared_ptr text, PredicateBuilder::FullTextMatch(1, match)); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, text, true)); - ASSERT_OK_AND_ASSIGN(std::shared_ptr wrong_index, - PredicateBuilder::FullTextMatch(0, match)); - ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, wrong_index, true), - "field text has field idx 1 in input schema, mismatch field idx 0 in predicate"); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, wrong_index, false)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, text)); auto missing = arrow::schema({arrow::field("id", arrow::int32())}); - ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*missing, text, true), + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*missing, text), "field text does not exist in schema"); auto numeric = arrow::schema({arrow::field("id", arrow::int32()), arrow::field("text", arrow::int32())}); - ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*numeric, text, true), + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*numeric, text), "schema type int32 mismatches predicate field type STRING"); } @@ -68,10 +62,10 @@ TEST(PredicateValidatorTest, TestFullTextMatchAllowsOrAndRepeatedFields) { auto scalar = PredicateBuilder::Equal(0, "id", FieldType::INT, Literal(7)); ASSERT_OK_AND_ASSIGN(std::shared_ptr conjunction, PredicateBuilder::And({apple, orange})); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, conjunction, true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, conjunction)); ASSERT_OK_AND_ASSIGN(std::shared_ptr disjunction, PredicateBuilder::Or({conjunction, scalar})); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, disjunction, true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, disjunction)); } TEST(PredicateValidatorTest, TestRejectEmptyInLiterals) { @@ -83,12 +77,9 @@ TEST(PredicateValidatorTest, TestRejectEmptyInLiterals) { PredicateBuilder::And({valid, predicate})); ASSERT_OK_AND_ASSIGN(std::shared_ptr disjunction, PredicateBuilder::Or({valid, conjunction})); - for (bool validate_field_idx : {false, true}) { - for (const auto& candidate : {predicate, conjunction, disjunction}) { - ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema( - *schema, candidate, validate_field_idx), - "literals cannot be empty"); - } + for (const auto& candidate : {predicate, conjunction, disjunction}) { + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*schema, candidate), + "literals cannot be empty"); } } } @@ -101,7 +92,7 @@ TEST(PredicateValidatorTest, TestAcceptNonEmptyInAndNullChecks) { PredicateBuilder::IsNull(0, "f0", FieldType::INT), PredicateBuilder::IsNotNull(0, "f0", FieldType::INT), }) { - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate)); } } @@ -145,8 +136,7 @@ TEST(PredicateValidatorTest, TestValidateLiterals) { PredicateBuilder::Equal(/*field_index=*/9, /*field_name=*/"f9", FieldType::BINARY, Literal(FieldType::BINARY, str.data(), str.size())), })); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate)); } { // f1 field type is FLOAT, literal type is BIGINT @@ -163,8 +153,7 @@ TEST(PredicateValidatorTest, TestValidateLiterals) { Literal(true)), })); ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), + PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "field f1 has field type BIGINT in literal, mismatch field type FLOAT in predicate"); } { @@ -182,8 +171,7 @@ TEST(PredicateValidatorTest, TestValidateLiterals) { Literal(true)), })); ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), + PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "field f2 has field type BINARY in literal, mismatch field type STRING in predicate"); } { @@ -200,10 +188,8 @@ TEST(PredicateValidatorTest, TestValidateLiterals) { PredicateBuilder::Equal(/*field_index=*/3, /*field_name=*/"f3", FieldType::BOOLEAN, Literal(true)), })); - ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), - "literal cannot be null in predicate, field name f2"); + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), + "literal cannot be null in predicate, field name f2"); } } @@ -245,8 +231,7 @@ TEST(PredicateValidatorTest, TestValidateSchema) { PredicateBuilder::Equal(/*field_index=*/8, /*field_name=*/"f8", FieldType::TINYINT, Literal(static_cast(20))), })); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate)); } { // f2 schema type is DECIMAL(23,5), but the literal scale is 4. @@ -270,64 +255,10 @@ TEST(PredicateValidatorTest, TestValidateSchema) { Literal(true)), })); ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), + PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "decimal literal for field f2 has scale 4, expected 5; rescale the literal before " "building the predicate"); } - { - // predicate field idx mismatch - std::shared_ptr schema = arrow::schema(arrow::FieldVector({ - arrow::field("f0", arrow::int64()), - arrow::field("f1", arrow::float32()), - arrow::field("f2", arrow::utf8()), - arrow::field("f3", arrow::boolean()), - })); - - ASSERT_OK_AND_ASSIGN( - auto predicate, - PredicateBuilder::And({ - PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"f0", FieldType::BIGINT, - Literal(3l)), - PredicateBuilder::Equal(/*field_index=*/2, /*field_name=*/"f1", FieldType::FLOAT, - Literal(static_cast(5.5))), - PredicateBuilder::Equal(/*field_index=*/2, /*field_name=*/"f2", FieldType::STRING, - Literal(FieldType::STRING, str.data(), str.size())), - PredicateBuilder::Equal(/*field_index=*/3, /*field_name=*/"f3", FieldType::BOOLEAN, - Literal(true)), - })); - - ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), - "field f1 has field idx 1 in input schema, mismatch " - "field idx 2 in predicate"); - } - { - // predicate field idx mismatch, but not validate - std::shared_ptr schema = arrow::schema(arrow::FieldVector({ - arrow::field("f0", arrow::int64()), - arrow::field("f1", arrow::float32()), - arrow::field("f2", arrow::utf8()), - arrow::field("f3", arrow::boolean()), - })); - - ASSERT_OK_AND_ASSIGN( - auto predicate, - PredicateBuilder::And({ - PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"f0", FieldType::BIGINT, - Literal(3l)), - PredicateBuilder::Equal(/*field_index=*/2, /*field_name=*/"f1", FieldType::FLOAT, - Literal(static_cast(5.5))), - PredicateBuilder::Equal(/*field_index=*/2, /*field_name=*/"f2", FieldType::STRING, - Literal(FieldType::STRING, str.data(), str.size())), - PredicateBuilder::Equal(/*field_index=*/3, /*field_name=*/"f3", FieldType::BOOLEAN, - Literal(true)), - })); - - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/false)); - } { // f0 is uint16 std::shared_ptr schema = arrow::schema(arrow::FieldVector({ @@ -349,10 +280,8 @@ TEST(PredicateValidatorTest, TestValidateSchema) { PredicateBuilder::Equal(/*field_index=*/3, /*field_name=*/"f3", FieldType::BOOLEAN, Literal(true)), })); - ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), - "Invalid type uint16 for predicate"); + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), + "Invalid type uint16 for predicate"); } { // f2 schema type is DOUBLE, predicate type is STRING @@ -375,10 +304,8 @@ TEST(PredicateValidatorTest, TestValidateSchema) { PredicateBuilder::Equal(/*field_index=*/3, /*field_name=*/"f3", FieldType::BOOLEAN, Literal(true)), })); - ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), - "schema type double mismatches predicate field type STRING"); + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), + "schema type double mismatches predicate field type STRING"); } { // f2 schema type is BINARY, predicate type is STRING @@ -401,10 +328,8 @@ TEST(PredicateValidatorTest, TestValidateSchema) { PredicateBuilder::Equal(/*field_index=*/3, /*field_name=*/"f3", FieldType::BOOLEAN, Literal(true)), })); - ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), - "schema type binary mismatches predicate field type STRING"); + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), + "schema type binary mismatches predicate field type STRING"); } { // f2 in predicate does not exist in schema @@ -427,10 +352,8 @@ TEST(PredicateValidatorTest, TestValidateSchema) { Literal(true)), })); - ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), - "field f2 does not exist in schema"); + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), + "field f2 does not exist in schema"); } } @@ -442,31 +365,27 @@ TEST(PredicateValidatorTest, TestValidateDecimalLiteral) { auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"amount", FieldType::DECIMAL, Literal(Decimal(10, 2, 12345))); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate)); } { // Literal precision metadata may be smaller than the field precision. auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"amount", FieldType::DECIMAL, Literal(Decimal(9, 2, 12345))); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate)); } { // Literal precision metadata may be larger than the field precision if the value fits. auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"amount", FieldType::DECIMAL, Literal(Decimal(12, 2, 12345))); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate)); } { auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"amount", FieldType::DECIMAL, Literal(Decimal(10, 1, 12345))); ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), + PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "decimal literal for field amount has scale 1, expected 2; rescale the literal before " "building the predicate"); } @@ -475,8 +394,7 @@ TEST(PredicateValidatorTest, TestValidateDecimalLiteral) { /*field_index=*/0, /*field_name=*/"amount", FieldType::DECIMAL, {Literal(Decimal(10, 2, 12345)), Literal(Decimal(10, 3, 123450))}); ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), + PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "decimal literal for field amount has scale 3, expected 2; rescale the literal before " "building the predicate"); } @@ -485,8 +403,7 @@ TEST(PredicateValidatorTest, TestValidateDecimalLiteral) { PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"amount", FieldType::DECIMAL, Literal(Decimal(10, 2, 10000000000LL))); ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), + PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "decimal literal 100000000.00 for field amount does not fit field type DECIMAL(10, " "2)"); } @@ -507,27 +424,23 @@ TEST(PredicateValidatorTest, TestValidateTime) { Literal(FieldType::TIME, 86399999)), PredicateBuilder::IsNotNull(/*field_index=*/0, /*field_name=*/"t", FieldType::TIME), })); - ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate)); } for (int32_t value : {-1, 86400000}) { auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"t", FieldType::TIME, Literal(FieldType::TIME, value)); ASSERT_NOK_WITH_MSG( - PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, - /*validate_field_idx=*/true), + PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "time literal " + std::to_string(value) + " for field t is out of range"); } { auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"t", FieldType::INT, Literal(1)); - ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema( - *schema, predicate, /*validate_field_idx=*/true), + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "mismatches predicate field type INT"); predicate = PredicateBuilder::Equal(/*field_index=*/1, /*field_name=*/"i", FieldType::TIME, Literal(FieldType::TIME, 1)); - ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema( - *schema, predicate, /*validate_field_idx=*/true), + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate), "mismatches predicate field type TIME"); } { @@ -535,9 +448,9 @@ TEST(PredicateValidatorTest, TestValidateTime) { arrow::FieldVector({arrow::field("t", arrow::time32(arrow::TimeUnit::SECOND))})); auto predicate = PredicateBuilder::Equal(/*field_index=*/0, /*field_name=*/"t", FieldType::TIME, Literal(FieldType::TIME, 1)); - ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateWithSchema( - *seconds_schema, predicate, /*validate_field_idx=*/true), - "TIME requires time32[ms]"); + ASSERT_NOK_WITH_MSG( + PredicateValidator::ValidatePredicateWithSchema(*seconds_schema, predicate), + "TIME requires time32[ms]"); } } } // namespace paimon::test diff --git a/src/paimon/common/reader/late_materializing_file_batch_reader.cpp b/src/paimon/common/reader/late_materializing_file_batch_reader.cpp index 10bdaea18..bea63af0a 100644 --- a/src/paimon/common/reader/late_materializing_file_batch_reader.cpp +++ b/src/paimon/common/reader/late_materializing_file_batch_reader.cpp @@ -305,8 +305,8 @@ Status LateMaterializingFileBatchReader::SetReadSchema( if (!probe_fields.empty() && !payload_fields.empty()) { probe_schema_ = arrow::schema(probe_fields, full_schema_->metadata()); payload_schema_ = arrow::schema(payload_fields, full_schema_->metadata()); - PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( - *probe_schema_, predicate_, /*validate_field_idx=*/false)); + PAIMON_RETURN_NOT_OK( + PredicateValidator::ValidatePredicateWithSchema(*probe_schema_, predicate_)); std::map name_to_idx; for (int32_t i = 0; i < probe_schema_->num_fields(); ++i) { name_to_idx.emplace(probe_schema_->field(i)->name(), i); diff --git a/src/paimon/common/reader/predicate_batch_reader.cpp b/src/paimon/common/reader/predicate_batch_reader.cpp index fb9a5f974..5f8ecccca 100644 --- a/src/paimon/common/reader/predicate_batch_reader.cpp +++ b/src/paimon/common/reader/predicate_batch_reader.cpp @@ -105,8 +105,7 @@ Status PredicateBatchReader::BindPredicateToArray(const arrow::Array& array) { } const auto& struct_type = checked_cast(*array.type()); std::shared_ptr schema = arrow::schema(struct_type.fields()); - PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( - *schema, predicate_, /*validate_field_idx=*/false)); + PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, predicate_)); std::map field_name_to_index; for (int32_t i = 0; i < schema->num_fields(); ++i) { diff --git a/src/paimon/common/reader/projection_batch_reader.cpp b/src/paimon/common/reader/projection_batch_reader.cpp new file mode 100644 index 000000000..e64319ff2 --- /dev/null +++ b/src/paimon/common/reader/projection_batch_reader.cpp @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "paimon/common/reader/projection_batch_reader.h" + +#include + +#include "arrow/array.h" +#include "arrow/c/bridge.h" +#include "paimon/common/reader/reader_utils.h" +#include "paimon/common/table/special_fields.h" +#include "paimon/common/utils/arrow/mem_utils.h" +#include "paimon/common/utils/arrow/status_utils.h" +#include "paimon/common/utils/checked_cast.h" +#include "paimon/common/utils/scope_guard.h" + +namespace paimon { + +Result ProjectionBatchReader::NextBatch() { + PAIMON_ASSIGN_OR_RAISE(ReadBatchWithBitmap batch_with_bitmap, NextBatchWithBitmap()); + PAIMON_ASSIGN_OR_RAISE(ReadBatch batch, ReaderUtils::ApplyBitmapToReadBatch( + std::move(batch_with_bitmap), arrow_pool_)); + return batch; +} + +Result ProjectionBatchReader::NextBatchWithBitmap() { + PAIMON_ASSIGN_OR_RAISE(ReadBatchWithBitmap batch, reader_->NextBatchWithBitmap()); + PAIMON_RETURN_NOT_OK(Project(&batch.first)); + return batch; +} + +Status ProjectionBatchReader::Project(ReadBatch* batch) const { + if (IsEofBatch(*batch)) { + return Status::OK(); + } + ScopeGuard release([batch]() { ReaderUtils::ReleaseReadBatch(std::move(*batch)); }); + auto& [c_array, c_schema] = *batch; + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr root, + arrow::ImportField(c_schema.get())); + if (root->type()->id() != arrow::Type::STRUCT) { + return Status::Invalid("projection batch reader requires a struct array"); + } + PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr array, + arrow::ImportArray(c_array.get(), root->type())); + auto struct_array = checked_pointer_cast(array); + const auto& type = *struct_array->struct_type(); + arrow::ArrayVector children; + arrow::FieldVector fields; + auto append = [&](const std::string& name) -> Status { + int32_t index = type.GetFieldIndex(name); + if (index < 0) { + return Status::Invalid("Output field is missing or ambiguous in batch: ", name); + } + fields.push_back(type.field(index)); + children.push_back(struct_array->field(index)); + return Status::OK(); + }; + const std::string& row_kind = SpecialFields::ValueKind().Name(); + if (type.GetFieldIndex(row_kind) >= 0) { + PAIMON_RETURN_NOT_OK(append(row_kind)); + } + for (const std::string& name : output_fields_) { + if (name != row_kind || type.GetFieldIndex(row_kind) < 0) { + PAIMON_RETURN_NOT_OK(append(name)); + } + } + // Root TopK appends its score even when it is not projected. Keep it until the outer TopK + // reader has ranked the rows and removes the score according to the output schema. + for (const auto& field : type.fields()) { + const std::string& name = field->name(); + if (SpecialFields::ParseIndexScoreFieldName(name) && + std::find(output_fields_.begin(), output_fields_.end(), name) == output_fields_.end()) { + PAIMON_RETURN_NOT_OK(append(name)); + } + } + // Specify the length so that an empty projection still preserves the row count. + auto output = + std::make_shared(arrow::struct_(fields), array->length(), children, + array->null_bitmap(), array->null_count()); + PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportArray(*output, c_array.get())); + PAIMON_RETURN_NOT_OK_FROM_ARROW( + arrow::ExportField(*root->WithType(output->type()), c_schema.get())); + PAIMON_RETURN_NOT_OK(AddArrowArrayLifetime(c_array.get(), c_schema.get(), array)); + release.Release(); + return Status::OK(); +} +} // namespace paimon diff --git a/src/paimon/common/reader/projection_batch_reader.h b/src/paimon/common/reader/projection_batch_reader.h new file mode 100644 index 000000000..a88c3c0a0 --- /dev/null +++ b/src/paimon/common/reader/projection_batch_reader.h @@ -0,0 +1,64 @@ +/* + * 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 +#include + +#include "paimon/reader/batch_reader.h" + +namespace arrow { +class MemoryPool; +} // namespace arrow + +namespace paimon { + +/// Drops dependency columns after filtering/merging, preserving the actual batch fields and +/// the leading _VALUE_KIND. Retains implicit index scores until the outer TopK reader consumes +/// them and removes scores absent from the output schema. +class ProjectionBatchReader : public BatchReader { + public: + ProjectionBatchReader(std::unique_ptr reader, + std::vector output_fields, + const std::shared_ptr& arrow_pool) + : reader_(std::move(reader)), + output_fields_(std::move(output_fields)), + arrow_pool_(arrow_pool) {} + + Result NextBatch() override; + Result NextBatchWithBitmap() override; + + std::shared_ptr GetReaderMetrics() const override { + return reader_->GetReaderMetrics(); + } + void Close() override { + reader_->Close(); + } + + private: + Status Project(ReadBatch* batch) const; + + std::unique_ptr reader_; + std::vector output_fields_; + std::shared_ptr arrow_pool_; +}; +} // namespace paimon diff --git a/src/paimon/common/reader/projection_batch_reader_test.cpp b/src/paimon/common/reader/projection_batch_reader_test.cpp new file mode 100644 index 000000000..f5b0da82c --- /dev/null +++ b/src/paimon/common/reader/projection_batch_reader_test.cpp @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include "paimon/common/reader/projection_batch_reader.h" + +#include "arrow/api.h" +#include "arrow/c/bridge.h" +#include "arrow/ipc/json_simple.h" +#include "paimon/common/reader/reader_utils.h" +#include "paimon/common/utils/arrow/mem_utils.h" +#include "paimon/common/utils/checked_cast.h" +#include "paimon/testing/mock/mock_file_batch_reader.h" +#include "paimon/testing/utils/testharness.h" + +namespace paimon::test { + +TEST(ProjectionBatchReaderTest, PreservesSelectionEncodingAndMetadata) { + auto json = [](const std::shared_ptr& type, const std::string& value) { + return arrow::ipc::internal::json::ArrayFromJSON(type, value).ValueOrDie(); + }; + auto dictionary_type = arrow::dictionary(arrow::int32(), arrow::utf8()); + auto names = + arrow::DictionaryArray::FromArrays(dictionary_type, json(arrow::int32(), "[0, 1, 0]"), + json(arrow::utf8(), R"(["Alice", "Bob"])")) + .ValueOrDie(); + auto metadata = arrow::key_value_metadata({"field-id"}, {"42"}); + auto name_field = arrow::field("name", dictionary_type, true, metadata); + auto data = arrow::StructArray::Make( + {json(arrow::int8(), "[0, 0, 0]"), json(arrow::int32(), "[1, 2, 3]"), + json(arrow::int32(), "[10, 20, 30]"), names}, + {arrow::field("_VALUE_KIND", arrow::int8()), arrow::field("id", arrow::int32()), + arrow::field("dependency", arrow::int32()), name_field}) + .ValueOrDie(); + for (bool with_bitmap : {false, true}) { + auto mock = std::make_unique(data, data->type(), + RoaringBitmap32::From({0, 2}), 3); + mock->EnableRandomizeBatchSize(false); + auto reader = std::make_unique( + std::move(mock), std::vector{"name", "id"}, + GetArrowPool(GetDefaultPool())); + BatchReader::ReadBatch batch; + if (with_bitmap) { + ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatchWithBitmap selected, + reader->NextBatchWithBitmap()); + ASSERT_EQ(selected.second, RoaringBitmap32::From({0, 2})); + batch = std::move(selected.first); + } else { + ASSERT_OK_AND_ASSIGN(batch, reader->NextBatch()); + } + auto imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status().ToString(); + std::shared_ptr result = std::move(imported).ValueOrDie(); + auto rows = checked_pointer_cast(result); + ASSERT_TRUE(rows->ValidateFull().ok()); + ASSERT_EQ(rows->length(), with_bitmap ? 3 : 2); + ASSERT_EQ(rows->struct_type()->num_fields(), 3); + ASSERT_EQ(rows->struct_type()->field(0)->name(), "_VALUE_KIND"); + ASSERT_TRUE(rows->struct_type()->field(1)->Equals(name_field, true)); + ASSERT_EQ(rows->struct_type()->field(2)->name(), "id"); + ASSERT_TRUE( + rows->field(2)->Equals(json(arrow::int32(), with_bitmap ? "[1, 2, 3]" : "[1, 3]"))); + reader->Close(); + } +} + +TEST(ProjectionBatchReaderTest, RejectsMissingOutputAndPreservesEmptyProjectionRows) { + auto data = arrow::ipc::internal::json::ArrayFromJSON( + arrow::struct_({arrow::field("id", arrow::int32())}), "[[1], [2]]") + .ValueOrDie(); + ProjectionBatchReader invalid(std::make_unique(data, data->type(), 2), + {"missing"}, GetArrowPool(GetDefaultPool())); + ASSERT_NOK_WITH_MSG(invalid.NextBatch(), "Output field is missing"); + invalid.Close(); + auto mock = std::make_unique(data, data->type(), 2); + mock->EnableRandomizeBatchSize(false); + ProjectionBatchReader empty(std::move(mock), {}, GetArrowPool(GetDefaultPool())); + ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatch batch, empty.NextBatch()); + ASSERT_EQ(batch.first->length, 2); + ASSERT_EQ(batch.first->n_children, 0); + ReaderUtils::ReleaseReadBatch(std::move(batch)); + ASSERT_OK_AND_ASSIGN(batch, empty.NextBatch()); + ASSERT_TRUE(BatchReader::IsEofBatch(batch)); + empty.Close(); +} + +TEST(ProjectionBatchReaderTest, PreservesParentNullsAndRowCountWithEmptyProjection) { + auto data = arrow::ipc::internal::json::ArrayFromJSON( + arrow::struct_({arrow::field("id", arrow::int32()), + arrow::field("dependency", arrow::int32())}), + "[[10, 1], null, [30, 3], [40, 4]]") + .ValueOrDie(); + for (bool empty_projection : {false, true}) { + for (bool with_bitmap : {false, true}) { + auto source = std::make_unique( + data, data->type(), RoaringBitmap32::From({0, 1, 3}), 4); + source->EnableRandomizeBatchSize(false); + std::vector output_fields; + if (!empty_projection) { + output_fields.push_back("id"); + } + ProjectionBatchReader reader(std::move(source), std::move(output_fields), + GetArrowPool(GetDefaultPool())); + BatchReader::ReadBatch batch; + if (with_bitmap) { + ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatchWithBitmap selected, + reader.NextBatchWithBitmap()); + ASSERT_EQ(selected.second, RoaringBitmap32::From({0, 1, 3})); + batch = std::move(selected.first); + } else { + ASSERT_OK_AND_ASSIGN(batch, reader.NextBatch()); + } + auto imported = arrow::ImportArray(batch.first.get(), batch.second.get()); + ASSERT_TRUE(imported.ok()) << imported.status().ToString(); + auto rows = checked_pointer_cast(std::move(imported).ValueOrDie()); + ASSERT_TRUE(rows->ValidateFull().ok()); + ASSERT_EQ(rows->length(), with_bitmap ? 4 : 3); + ASSERT_EQ(rows->null_count(), 1); + ASSERT_TRUE(rows->IsNull(1)); + ASSERT_EQ(rows->num_fields(), empty_projection ? 0 : 1); + if (!empty_projection) { + auto ids = checked_pointer_cast(rows->field(0)); + ASSERT_EQ(ids->Value(0), 10); + ASSERT_EQ(ids->Value(2), with_bitmap ? 30 : 40); + ASSERT_EQ(ids->Value(ids->length() - 1), 40); + } + reader.Close(); + } + } +} +} // namespace paimon::test diff --git a/src/paimon/common/table/special_fields.h b/src/paimon/common/table/special_fields.h index 73562140b..373a78fab 100644 --- a/src/paimon/common/table/special_fields.h +++ b/src/paimon/common/table/special_fields.h @@ -21,12 +21,14 @@ #include #include #include +#include #include #include #include "arrow/type_fwd.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/string_utils.h" +#include "paimon/status.h" #include "paimon/utils/special_field_ids.h" namespace paimon { @@ -112,6 +114,27 @@ struct SpecialFields { ParseIndexScoreFieldName(field_name).has_value(); } + /// Check user predicate names against the system fields supported by the scan/read entry. + static Status ValidatePredicateFieldNames(const std::set& field_names, + const arrow::FieldVector& allowed_system_fields) { + for (const auto& name : field_names) { + if (!IsSystemField(name)) { + continue; + } + bool allowed = false; + for (const auto& field : allowed_system_fields) { + if (field->name() == name) { + allowed = true; + break; + } + } + if (!allowed) { + return Status::Invalid("Predicate on system field '", name, "' are not supported"); + } + } + return Status::OK(); + } + // TODO(xinyu.lxy): add a func to complete row-tracking fields static std::shared_ptr CompleteSequenceAndValueKindField( diff --git a/src/paimon/common/table/special_fields_test.cpp b/src/paimon/common/table/special_fields_test.cpp index 94df21676..e0e214d0f 100644 --- a/src/paimon/common/table/special_fields_test.cpp +++ b/src/paimon/common/table/special_fields_test.cpp @@ -21,7 +21,9 @@ #include #include "arrow/type.h" +#include "fmt/format.h" #include "gtest/gtest.h" +#include "paimon/testing/utils/testharness.h" namespace paimon::test { @@ -97,4 +99,32 @@ TEST(SpecialFieldsTest, TestIsSystemField) { ASSERT_TRUE(SpecialFields::IsSystemField("_KEY_0")); } +TEST(SpecialFieldsTest, PredicateFieldNamesAllowOnlyConfiguredSystemFields) { + ASSERT_OK(SpecialFields::ValidatePredicateFieldNames({"id", "name"}, {})); + arrow::FieldVector allowed_fields = {SpecialFields::RowId().ArrowField(), + SpecialFields::SequenceNumber().ArrowField()}; + ASSERT_OK(SpecialFields::ValidatePredicateFieldNames({"id", "_ROW_ID", "_SEQUENCE_NUMBER"}, + allowed_fields)); + for (const auto& field : allowed_fields) { + ASSERT_OK(SpecialFields::ValidatePredicateFieldNames({"id", field->name()}, {field})); + ASSERT_NOK_WITH_MSG( + SpecialFields::ValidatePredicateFieldNames({field->name()}, {}), + fmt::format("Predicate on system field '{}' are not supported", field->name())); + ASSERT_NOK_WITH_MSG( + SpecialFields::ValidatePredicateFieldNames({"_ROW_ID", "_SEQUENCE_NUMBER"}, {field}), + "Predicate on system field"); + } +} + +TEST(SpecialFieldsTest, PredicateFieldNamesRejectOtherSystemFields) { + arrow::FieldVector allowed_fields = {SpecialFields::RowId().ArrowField(), + SpecialFields::SequenceNumber().ArrowField()}; + for (const auto& field_name : + {"_VALUE_KIND", "rowkind", "_INDEX_SCORE", "_text_INDEX_SCORE", "_KEY_id"}) { + ASSERT_NOK_WITH_MSG( + SpecialFields::ValidatePredicateFieldNames({field_name}, allowed_fields), + fmt::format("Predicate on system field '{}' are not supported", field_name)); + } +} + } // namespace paimon::test diff --git a/src/paimon/core/global_index/global_index_scan_impl.cpp b/src/paimon/core/global_index/global_index_scan_impl.cpp index 1286386d0..85546058f 100644 --- a/src/paimon/core/global_index/global_index_scan_impl.cpp +++ b/src/paimon/core/global_index/global_index_scan_impl.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,8 @@ #include "arrow/c/helpers.h" #include "paimon/common/global_index/offset_global_index_reader.h" #include "paimon/common/global_index/union_global_index_reader.h" +#include "paimon/common/predicate/predicate_validator.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/utils/scope_guard.h" #include "paimon/core/global_index/global_index_evaluator_impl.h" #include "paimon/core/global_index/global_index_live_row_filter.h" @@ -37,6 +40,7 @@ #include "paimon/global_index/bitmap_global_index_result.h" #include "paimon/global_index/global_indexer.h" #include "paimon/global_index/global_indexer_factory.h" +#include "paimon/predicate/predicate_utils.h" namespace paimon { GlobalIndexScanImpl::GlobalIndexScanImpl(const std::shared_ptr& table_schema, @@ -324,6 +328,14 @@ GlobalIndexIOMeta GlobalIndexScanImpl::ToGlobalIndexIOMeta( Result> GlobalIndexScanImpl::Scan( const std::shared_ptr& predicate) { + std::set field_names; + if (predicate) { + PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(predicate, &field_names)); + } + PAIMON_RETURN_NOT_OK( + SpecialFields::ValidatePredicateFieldNames(field_names, /*allowed_system_fields=*/{})); + PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( + *DataField::ConvertDataFieldsToArrowSchema(table_schema_->Fields()), predicate)); PAIMON_ASSIGN_OR_RAISE(std::shared_ptr evaluator, GetOrCreateIndexEvaluator()); return evaluator->Evaluate(predicate); @@ -331,6 +343,8 @@ Result> GlobalIndexScanImpl::Scan( Result> GlobalIndexScanImpl::ScanWithCoverage( const std::shared_ptr& predicate) const { + PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( + *DataField::ConvertDataFieldsToArrowSchema(table_schema_->Fields()), predicate)); GlobalIndexEvaluatorImpl evaluator( table_schema_, [this](int32_t field_id) -> Result>> { diff --git a/src/paimon/core/io/complete_row_tracking_fields_reader.cpp b/src/paimon/core/io/complete_row_tracking_fields_reader.cpp index e9d703bc8..363725b3c 100644 --- a/src/paimon/core/io/complete_row_tracking_fields_reader.cpp +++ b/src/paimon/core/io/complete_row_tracking_fields_reader.cpp @@ -19,6 +19,7 @@ #include "paimon/core/io/complete_row_tracking_fields_reader.h" #include +#include #include #include @@ -30,6 +31,7 @@ #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/object_utils.h" +#include "paimon/predicate/predicate_utils.h" namespace paimon { CompleteRowTrackingFieldsBatchReader::CompleteRowTrackingFieldsBatchReader( @@ -61,19 +63,24 @@ Status CompleteRowTrackingFieldsBatchReader::SetReadSchema( PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr arrow_schema, arrow::ImportSchema(read_schema)); read_schema_ = arrow_schema; + std::set completed_fields; int32_t row_id_idx = arrow_schema->GetFieldIndex(SpecialFields::RowId().Name()); if (row_id_idx != -1 && !ObjectUtils::Contains(file_field_names, SpecialFields::RowId().Name())) { PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(arrow_schema, arrow_schema->RemoveField(row_id_idx)); + completed_fields.insert(SpecialFields::RowId().Name()); } int32_t sequence_id_idx = arrow_schema->GetFieldIndex(SpecialFields::SequenceNumber().Name()); if (sequence_id_idx != -1 && !ObjectUtils::Contains(file_field_names, SpecialFields::SequenceNumber().Name())) { PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(arrow_schema, arrow_schema->RemoveField(sequence_id_idx)); + completed_fields.insert(SpecialFields::SequenceNumber().Name()); } + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr physical_predicate, + PredicateUtils::ExcludePredicateWithFields(predicate, completed_fields)); ArrowSchema c_schema; PAIMON_RETURN_NOT_OK_FROM_ARROW(arrow::ExportSchema(*arrow_schema, &c_schema)); - return reader_->SetReadSchema(&c_schema, predicate, selection_bitmap); + return reader_->SetReadSchema(&c_schema, physical_predicate, selection_bitmap); } Result diff --git a/src/paimon/core/manifest/manifest_file.cpp b/src/paimon/core/manifest/manifest_file.cpp index f47a63a9c..1206c99bc 100644 --- a/src/paimon/core/manifest/manifest_file.cpp +++ b/src/paimon/core/manifest/manifest_file.cpp @@ -242,9 +242,7 @@ Status ManifestFile::PrepareBucketRead(int32_t bucket, kVersionFieldIndex, version_name, FieldType::INT, Literal( checked_cast(serializer_.get())->GetVersion()))})); - if (!PredicateValidator::ValidatePredicateWithSchema(*file_schema, selector, - /*validate_field_idx=*/true) - .ok()) { + if (!PredicateValidator::ValidatePredicateWithSchema(*file_schema, selector).ok()) { // An incompatible projection must fall back to ordinary schema evolution. return Status::OK(); } diff --git a/src/paimon/core/operation/abstract_split_read.cpp b/src/paimon/core/operation/abstract_split_read.cpp index f14e2cede..a45d37c82 100644 --- a/src/paimon/core/operation/abstract_split_read.cpp +++ b/src/paimon/core/operation/abstract_split_read.cpp @@ -72,6 +72,7 @@ #include "paimon/format/file_format.h" #include "paimon/format/file_format_factory.h" #include "paimon/fs/file_system.h" +#include "paimon/predicate/predicate_utils.h" #include "paimon/status.h" #include "paimon/utils/roaring_bitmap32.h" @@ -251,7 +252,12 @@ Result> AbstractSplitRead::ApplyIndexAndDvReade std::unique_ptr evaluator, FileIndexEvaluator::Create(data_schema, file_index_options, data_file_path_factory, file, options_.GetFileSystem(), /*cache=*/nullptr, pool_)); - PAIMON_ASSIGN_OR_RAISE(file_index_result, evaluator->Evaluate(predicate)); + // File indexes only cover the file fields, not virtual system fields. + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr index_predicate, + PredicateUtils::CreatePickedFieldFilter( + predicate, ObjectUtils::CreateIdentifierToIndexMap(data_schema->field_names()))); + PAIMON_ASSIGN_OR_RAISE(file_index_result, evaluator->Evaluate(index_predicate)); PAIMON_ASSIGN_OR_RAISE(bool is_remain, file_index_result->IsRemain()); if (!is_remain) { return std::unique_ptr(); diff --git a/src/paimon/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index d13cb9199..c65eaef07 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -43,6 +43,7 @@ #include "paimon/common/reader/complete_index_score_batch_reader.h" #include "paimon/common/reader/complete_row_kind_batch_reader.h" #include "paimon/common/reader/concat_batch_reader.h" +#include "paimon/common/reader/projection_batch_reader.h" #include "paimon/common/table/special_fields.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/arrow/status_utils.h" @@ -243,8 +244,15 @@ Result> DataEvolutionSplitRead::CreateReader( batch_reader = std::make_unique( std::move(batch_reader), std::move(scores_by_row_id), remove_row_id, arrow_pool_); } - return WrapWithBlobViewResolverIfNeeded(data_split, std::move(batch_reader), - indexed_split->RowRanges()); + PAIMON_ASSIGN_OR_RAISE(batch_reader, + WrapWithBlobViewResolverIfNeeded(data_split, std::move(batch_reader), + indexed_split->RowRanges())); + if (context_->GetReadSchemaPlan()->NeedsProjection()) { + batch_reader = std::make_unique( + std::move(batch_reader), + context_->GetReadSchemaPlan()->GetOutputSchema()->field_names(), arrow_pool_); + } + return batch_reader; } else if (auto data_split = std::dynamic_pointer_cast(split)) { if (HasIndexScoreField(raw_read_schema_)) { return Status::Invalid( @@ -253,8 +261,15 @@ Result> DataEvolutionSplitRead::CreateReader( PAIMON_ASSIGN_OR_RAISE( std::unique_ptr inner_reader, InnerCreateReader(data_split, /*row_ranges=*/std::nullopt, raw_read_schema_)); - return WrapWithBlobViewResolverIfNeeded(data_split, std::move(inner_reader), - /*row_ranges=*/std::nullopt); + PAIMON_ASSIGN_OR_RAISE(inner_reader, + WrapWithBlobViewResolverIfNeeded(data_split, std::move(inner_reader), + /*row_ranges=*/std::nullopt)); + if (context_->GetReadSchemaPlan()->NeedsProjection()) { + inner_reader = std::make_unique( + std::move(inner_reader), + context_->GetReadSchemaPlan()->GetOutputSchema()->field_names(), arrow_pool_); + } + return inner_reader; } return Status::Invalid("Invalid Split, cannot cast to IndexedSplit or DataSplit"); } diff --git a/src/paimon/core/operation/data_evolution_split_read.h b/src/paimon/core/operation/data_evolution_split_read.h index 70075fb7e..b8cf9d96a 100644 --- a/src/paimon/core/operation/data_evolution_split_read.h +++ b/src/paimon/core/operation/data_evolution_split_read.h @@ -58,8 +58,8 @@ struct DeletionFile; /// If the class name below is enclosed in parentheses, it might be present in the read path; /// otherwise, it must be present in the read path. /// -/// Readers Overview: (ConcatBatchReader across -/// splits)->(BlobViewResolvingBatchReader)->(CompleteIndexScoreBatchReader)-> +/// Readers Overview: (ConcatBatchReader across splits)->(ProjectionBatchReader) +/// ->(BlobViewResolvingBatchReader)->(CompleteIndexScoreBatchReader)-> /// CompleteRowKindBatchReader->(PredicateBatchReader) /// ->ConcatBatchReader across files->DataEvolutionFileReader /// ->(ConcatBatchReader across vector files | BlobFallbackBatchReader across blob sequence layers) diff --git a/src/paimon/core/operation/file_store_scan.cpp b/src/paimon/core/operation/file_store_scan.cpp index a40be6742..38d9349d2 100644 --- a/src/paimon/core/operation/file_store_scan.cpp +++ b/src/paimon/core/operation/file_store_scan.cpp @@ -35,6 +35,7 @@ #include "paimon/common/executor/future.h" #include "paimon/common/io/cache/cache_key.h" #include "paimon/common/predicate/literal_converter.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/field_type_utils.h" #include "paimon/common/utils/scope_guard.h" @@ -736,9 +737,21 @@ Status FileStoreScan::SplitAndSetFilter(const std::vector& partitio return Status::NotImplemented("FullTextMatch predicate execution is not implemented yet"); } if (scan_filters->GetPredicate()) { - PAIMON_ASSIGN_OR_RAISE(std::unique_ptr mapping_builder, - FieldMappingBuilder::Create(arrow_schema, partition_keys, - scan_filters->GetPredicate())); + // Virtual row-tracking values are completed during reading, not stored in manifest stats. + // Drop entire conjuncts that depend on them, including OR branches, to avoid false + // negatives. + std::set virtual_fields; + for (const auto& field : {SpecialFields::RowId(), SpecialFields::SequenceNumber()}) { + if (arrow_schema->GetFieldIndex(field.Name()) < 0) { + virtual_fields.insert(field.Name()); + } + } + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr stats_predicate, + PredicateUtils::ExcludePredicateWithFields( + scan_filters->GetPredicate(), virtual_fields)); + PAIMON_ASSIGN_OR_RAISE( + std::unique_ptr mapping_builder, + FieldMappingBuilder::Create(arrow_schema, partition_keys, stats_predicate)); PAIMON_ASSIGN_OR_RAISE(std::vector data_fields, DataField::ConvertArrowSchemaToDataFields(arrow_schema)); auto converted_fields = BlobUtils::ConvertBlobInlineDataFields( diff --git a/src/paimon/core/operation/internal_read_context.cpp b/src/paimon/core/operation/internal_read_context.cpp index 75f33565f..8ccde981f 100644 --- a/src/paimon/core/operation/internal_read_context.cpp +++ b/src/paimon/core/operation/internal_read_context.cpp @@ -276,6 +276,17 @@ std::optional InternalReadContext::TryResolveSpecialFieldByName( return std::nullopt; } +Result> InternalReadContext::CreateReadSchemaPlan( + const std::shared_ptr& source_schema, + const std::shared_ptr& output_schema, + const std::shared_ptr& predicate) { + std::set required_names; + if (predicate) { + PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(predicate, &required_names)); + } + return ReadSchemaPlan::Create(source_schema, output_schema, required_names); +} + Result> InternalReadContext::Create( const std::shared_ptr& context, const std::shared_ptr& table_schema, const std::map& options) { @@ -391,35 +402,46 @@ Result> InternalReadContext::CreateFromCore "Precise file-index evaluation does not support _INDEX_SCORE; " "project __INDEX_SCORE instead"); } - // validate predicate + auto source_schema = DataField::ConvertDataFieldsToArrowSchema(table_schema->Fields()); if (context->GetPredicate()) { std::set field_names; PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(context->GetPredicate(), &field_names)); - for (const auto& field_name : field_names) { - if (field_name == SpecialFields::IndexScore().Name() || - SpecialFields::ParseIndexScoreFieldName(field_name)) { - return Status::Invalid(fmt::format( - "Predicates on virtual index score column '{}' are not supported", field_name)); - } + arrow::FieldVector allowed_system_fields; + if (core_options.RowTrackingEnabled()) { + allowed_system_fields.push_back( + DataField::ConvertDataFieldToArrowField(SpecialFields::RowId())); } + if (core_options.RowTrackingEnabled() || core_options.KeyValueSequenceNumberEnabled()) { + allowed_system_fields.push_back( + DataField::ConvertDataFieldToArrowField(SpecialFields::SequenceNumber())); + } + PAIMON_RETURN_NOT_OK( + SpecialFields::ValidatePredicateFieldNames(field_names, allowed_system_fields)); + arrow::FieldVector validation_fields = source_schema->fields(); + validation_fields.insert(validation_fields.end(), allowed_system_fields.begin(), + allowed_system_fields.end()); + source_schema = arrow::schema(validation_fields); PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( - *read_schema, context->GetPredicate(), /*validate_field_idx=*/true)); + *source_schema, context->GetPredicate())); } + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr schema_plan, + CreateReadSchemaPlan(source_schema, read_schema, context->GetPredicate())); if (!context->GetMemoryPool()) { return Status::Invalid("memory pool is null"); } std::shared_ptr arrow_pool = GetArrowPool(context->GetMemoryPool()); - auto internal_context = std::unique_ptr( - new InternalReadContext(context, table_schema, read_schema, core_options, arrow_pool)); + auto internal_context = std::unique_ptr(new InternalReadContext( + context, table_schema, std::move(schema_plan), core_options, arrow_pool)); PAIMON_RETURN_NOT_OK(internal_context->BindIndexScores()); return internal_context; } Status InternalReadContext::BindIndexScores() { std::map projected_scores; - for (int32_t idx = 0; idx < read_schema_->num_fields(); ++idx) { + for (int32_t idx = 0; idx < GetReadSchema()->num_fields(); ++idx) { if (auto field_name = - SpecialFields::ParseIndexScoreFieldName(read_schema_->field(idx)->name())) { + SpecialFields::ParseIndexScoreFieldName(GetReadSchema()->field(idx)->name())) { projected_scores.emplace(*field_name, idx); } } @@ -467,7 +489,7 @@ Status InternalReadContext::BindIndexScores() { for (const auto& [field_name, output_idx] : projected_scores) { if (index_score_bindings_.find(output_idx) == index_score_bindings_.end()) { return Status::Invalid(fmt::format("Index score field '{}' has no search source", - read_schema_->field(output_idx)->name())); + GetReadSchema()->field(output_idx)->name())); } } return Status::OK(); @@ -488,12 +510,12 @@ bool InternalReadContext::NeedsScores(const IndexScoreSource& source) const { InternalReadContext::InternalReadContext(const std::shared_ptr& read_context, const std::shared_ptr& table_schema, - const std::shared_ptr& read_schema, + std::shared_ptr schema_plan, const CoreOptions& options, const std::shared_ptr& arrow_pool) : read_context_(read_context), table_schema_(table_schema), - read_schema_(read_schema), + schema_plan_(std::move(schema_plan)), arrow_pool_(arrow_pool), options_(options), fs_scheme_map_(read_context->GetFileSystemSchemeToIdentifierMap()) {} @@ -507,9 +529,12 @@ Result> InternalReadContext::CreateWithSche } // Create a new InternalReadContext sharing all properties except read_schema. // The new read_schema is the minimal column set for COUNT(*). + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr schema_plan, + CreateReadSchemaPlan(original->GetReadSchema(), new_read_schema, original->GetPredicate())); auto result = std::shared_ptr( - new InternalReadContext(original->read_context_, original->table_schema_, new_read_schema, - original->options_, original->arrow_pool_)); + new InternalReadContext(original->read_context_, original->table_schema_, + std::move(schema_plan), original->options_, original->arrow_pool_)); result->path_ = original->path_; result->fs_scheme_map_ = original->fs_scheme_map_; return result; diff --git a/src/paimon/core/operation/internal_read_context.h b/src/paimon/core/operation/internal_read_context.h index 5e6925f6f..359459c5e 100644 --- a/src/paimon/core/operation/internal_read_context.h +++ b/src/paimon/core/operation/internal_read_context.h @@ -26,6 +26,7 @@ #include "paimon/core/core_options.h" #include "paimon/core/schema/table_schema.h" +#include "paimon/core/utils/read_schema_plan.h" #include "paimon/read_context.h" #include "paimon/result.h" @@ -82,7 +83,10 @@ class InternalReadContext { return options_; } std::shared_ptr GetReadSchema() const { - return read_schema_; + return schema_plan_->GetReadSchema(); + } + std::shared_ptr GetReadSchemaPlan() const { + return schema_plan_; } const std::shared_ptr& GetTableSchema() const { return table_schema_; @@ -177,10 +181,14 @@ class InternalReadContext { CoreOptions options); InternalReadContext(const std::shared_ptr& read_context, const std::shared_ptr& table_schema, - const std::shared_ptr& read_schema, - const CoreOptions& options, + std::shared_ptr schema_plan, const CoreOptions& options, const std::shared_ptr& arrow_pool); + static Result> CreateReadSchemaPlan( + const std::shared_ptr& source_schema, + const std::shared_ptr& output_schema, + const std::shared_ptr& predicate); + static std::optional TryResolveSpecialFieldById(int32_t field_id, const CoreOptions& core_options); static std::optional TryResolveSpecialFieldByName(const std::string& name, @@ -194,7 +202,7 @@ class InternalReadContext { std::shared_ptr read_context_; std::shared_ptr table_schema_; - std::shared_ptr read_schema_; + std::shared_ptr schema_plan_; std::shared_ptr arrow_pool_; CoreOptions options_; std::optional path_; diff --git a/src/paimon/core/operation/internal_read_context_test.cpp b/src/paimon/core/operation/internal_read_context_test.cpp index 471a4c35e..41068321b 100644 --- a/src/paimon/core/operation/internal_read_context_test.cpp +++ b/src/paimon/core/operation/internal_read_context_test.cpp @@ -49,6 +49,66 @@ namespace paimon::test { +TEST(InternalReadContext, SystemPredicatesResolveOnlyRequestedFields) { + ASSERT_OK_AND_ASSIGN( + std::shared_ptr table_schema, + TableSchema::Create(0, arrow::schema({arrow::field("id", arrow::int32())}), {}, {}, {})); + for (const auto& field : {SpecialFields::RowId(), SpecialFields::SequenceNumber()}) { + for (const auto& option : + {Options::ROW_TRACKING_ENABLED, Options::KEY_VALUE_SEQUENCE_NUMBER_ENABLED}) { + ReadContextBuilder builder("unused"); + auto predicate = PredicateBuilder::GreaterThan(77, field.Name(), FieldType::BIGINT, + Literal(int64_t{10})); + builder.SetReadFieldNames({"id"}).SetPredicate(predicate); + ASSERT_OK_AND_ASSIGN(std::shared_ptr context, builder.Finish()); + ASSERT_NOK_WITH_MSG(InternalReadContext::Create(context, table_schema, {}), + "Predicate on system field"); + const std::map options = {{option, "true"}}; + if (field.Name() == SpecialFields::RowId().Name() && + option == Options::KEY_VALUE_SEQUENCE_NUMBER_ENABLED) { + ASSERT_NOK_WITH_MSG(InternalReadContext::Create(context, table_schema, options), + "Predicate on system field"); + continue; + } + ASSERT_OK_AND_ASSIGN(std::shared_ptr internal, + InternalReadContext::Create(context, table_schema, options)); + ASSERT_EQ(internal->GetTableSchema()->Fields().size(), 1); + ASSERT_EQ(internal->GetReadSchemaPlan()->GetOutputSchema()->field_names(), + std::vector{"id"}); + ASSERT_EQ(internal->GetReadSchema()->field_names(), + (std::vector{"id", field.Name()})); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr count_context, + InternalReadContext::CreateWithSchema( + internal, arrow::schema({arrow::field("id", arrow::int32())}))); + ASSERT_EQ(count_context->GetReadSchema()->field_names(), + (std::vector{"id", field.Name()})); + } + } +} + +TEST(InternalReadContext, ValidatesPredicateFieldsWithoutChangingProjection) { + auto schema = arrow::schema({arrow::field("id", arrow::int32())}); + ASSERT_OK_AND_ASSIGN(std::shared_ptr table_schema, + TableSchema::Create(0, schema, {}, {}, {})); + const auto& field = SpecialFields::ValueKind(); + for (bool projected : {false, true}) { + ReadContextBuilder builder("unused"); + builder.SetReadFieldNames(projected ? std::vector{"id", field.Name()} + : std::vector{"id"}); + ASSERT_OK_AND_ASSIGN(std::shared_ptr projection, builder.Finish()); + ASSERT_OK(InternalReadContext::Create(projection, table_schema, {})); + auto leaf = PredicateBuilder::IsNotNull(77, field.Name(), FieldType::TINYINT); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr predicate, + PredicateBuilder::Or({PredicateBuilder::IsNotNull(0, "id", FieldType::INT), leaf})); + builder.SetPredicate(predicate); + ASSERT_OK_AND_ASSIGN(std::shared_ptr context, builder.Finish()); + ASSERT_NOK_WITH_MSG(InternalReadContext::Create(context, table_schema, {}), + "Predicate on system field"); + } +} + TEST(InternalReadContext, TestReadWithUnspecifiedSchema) { // no read schema is specified, read all fields std::string path = paimon::test::GetDataDir() + "/orc/append_09.db/append_09"; @@ -488,7 +548,7 @@ TEST(InternalReadContext, TestPrimaryKeyVectorSearchRequiresDeletionVectors) { "primary-key tables requires deletion vectors"); } -TEST(InternalReadContext, TestFullTextMatchValidatesProjection) { +TEST(InternalReadContext, TestFullTextMatchValidatesTableSchema) { std::string path = paimon::test::GetDataDir() + "/orc/append_09.db/append_09"; SchemaManager schema_manager(std::make_shared(), path); ASSERT_OK_AND_ASSIGN(std::shared_ptr table_schema, schema_manager.ReadSchema(0)); @@ -500,11 +560,7 @@ TEST(InternalReadContext, TestFullTextMatchValidatesProjection) { }; const std::vector cases = { {0, "f0", {"f0"}, ""}, - {0, "f0", {"f1"}, "field f0 does not exist in schema"}, - {1, - "f0", - {"f0"}, - "field f0 has field idx 0 in input schema, mismatch field idx 1 in predicate"}, + {0, "f0", {"f1"}, ""}, {0, "f1", {"f1"}, "schema type int32 mismatches predicate field type STRING"}}; for (const auto& test_case : cases) { auto match = @@ -794,9 +850,8 @@ TEST_F(InternalReadContextScoreTest, RejectsPredicatesOnFullTextMatchScores) { builder.EnablePreciseFileIndexEvaluate(true) .SetReadFieldNames({"F1", "_F1_INDEX_SCORE"}) .SetPredicate(predicate); - ASSERT_NOK_WITH_MSG( - Create(&builder), - "Predicates on virtual index score column '_F1_INDEX_SCORE' are not supported"); + ASSERT_NOK_WITH_MSG(Create(&builder), + "Predicate on system field '_F1_INDEX_SCORE' are not supported"); } } @@ -813,17 +868,15 @@ TEST_F(InternalReadContextScoreTest, RejectsNestedPredicatesOnRootSearchScores) .SetFullTextSearch(search) .SetReadFieldNames({"F1", "_F1_INDEX_SCORE"}) .SetPredicate(predicate); - ASSERT_NOK_WITH_MSG( - Create(&builder), - "Predicates on virtual index score column '_F1_INDEX_SCORE' are not supported"); + ASSERT_NOK_WITH_MSG(Create(&builder), + "Predicate on system field '_F1_INDEX_SCORE' are not supported"); } TEST_F(InternalReadContextScoreTest, RejectsPredicatesOnUnnamedIndexScores) { ReadContextBuilder builder("/tmp/unused-table-path"); builder.SetPredicate(PredicateBuilder::IsNull(0, "_INDEX_SCORE", FieldType::FLOAT)); - ASSERT_NOK_WITH_MSG( - Create(&builder), - "Predicates on virtual index score column '_INDEX_SCORE' are not supported"); + ASSERT_NOK_WITH_MSG(Create(&builder), + "Predicate on system field '_INDEX_SCORE' are not supported"); } TEST_F(InternalReadContextScoreTest, RejectsMissingScoreSource) { diff --git a/src/paimon/core/operation/merge_file_split_read.cpp b/src/paimon/core/operation/merge_file_split_read.cpp index 312760db2..3a0f0156b 100644 --- a/src/paimon/core/operation/merge_file_split_read.cpp +++ b/src/paimon/core/operation/merge_file_split_read.cpp @@ -30,6 +30,7 @@ #include "fmt/format.h" #include "paimon/common/reader/complete_row_kind_batch_reader.h" #include "paimon/common/reader/concat_batch_reader.h" +#include "paimon/common/reader/projection_batch_reader.h" #include "paimon/common/table/special_fields.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/arrow/status_utils.h" @@ -438,13 +439,28 @@ Result> MergeFileSplitRead::CreateReader( } else { PAIMON_ASSIGN_OR_RAISE(batch_reader, CreateMergeReader(data_split, data_file_path_factory)); } - return std::make_unique(std::move(batch_reader), arrow_pool_); + batch_reader = + std::make_unique(std::move(batch_reader), arrow_pool_); + if (context_->GetReadSchemaPlan()->NeedsProjection()) { + batch_reader = std::make_unique( + std::move(batch_reader), + context_->GetReadSchemaPlan()->GetOutputSchema()->field_names(), arrow_pool_); + } + return batch_reader; } Result> MergeFileSplitRead::CreateRealtimeReader( const std::vector>& disk_splits, std::vector>&& additional_readers) { - return RealtimeReaderBuilder::Create(disk_splits, std::move(additional_readers), this); + PAIMON_ASSIGN_OR_RAISE( + std::unique_ptr reader, + RealtimeReaderBuilder::Create(disk_splits, std::move(additional_readers), this)); + if (context_->GetReadSchemaPlan()->NeedsProjection()) { + reader = std::make_unique( + std::move(reader), context_->GetReadSchemaPlan()->GetOutputSchema()->field_names(), + arrow_pool_); + } + return reader; } void MergeFileSplitRead::SetMergeFunctionWrapper( diff --git a/src/paimon/core/operation/merge_file_split_read.h b/src/paimon/core/operation/merge_file_split_read.h index 45f19a463..aa1b8be53 100644 --- a/src/paimon/core/operation/merge_file_split_read.h +++ b/src/paimon/core/operation/merge_file_split_read.h @@ -68,8 +68,8 @@ class MergeFunctionWrapper; /// If the class name below is enclosed in parentheses, it might be present in the read path; /// otherwise, it must be present in the read path. /// -/// Readers Overview: (ConcatBatchReader across -/// splits)->CompleteRowKindBatchReader->(PredicateBatchReader) +/// Readers Overview: (ConcatBatchReader across splits)->(ProjectionBatchReader) +/// ->CompleteRowKindBatchReader->(PredicateBatchReader) /// ->ConcatBatchReader across no overlapped /// files->KeyValueProjectionReader/AsyncKeyValueProjectionReader /// ->DropDeleteReader->SortMergeReader->ConcatKeyValueRecordReader->KeyValueDataFileRecordReader diff --git a/src/paimon/core/operation/raw_file_split_read.cpp b/src/paimon/core/operation/raw_file_split_read.cpp index cf3b6b35e..6cb90cdd6 100644 --- a/src/paimon/core/operation/raw_file_split_read.cpp +++ b/src/paimon/core/operation/raw_file_split_read.cpp @@ -27,6 +27,7 @@ #include "paimon/common/executor/reader_build_executor.h" #include "paimon/common/reader/complete_row_kind_batch_reader.h" #include "paimon/common/reader/concat_batch_reader.h" +#include "paimon/common/reader/projection_batch_reader.h" #include "paimon/common/types/data_field.h" #include "paimon/core/core_options.h" #include "paimon/core/deletionvectors/deletion_vector.h" @@ -200,7 +201,15 @@ Result> RawFileSplitRead::CreateReader( auto dv_factory = DeletionVector::CreateFactory( options_.GetFileSystem(), DeletionVector::CreateDeletionFileMap(data_files, deletion_files), pool_); - return CreateReader(partition, bucket, data_files, dv_factory, local_row_ranges); + PAIMON_ASSIGN_OR_RAISE( + std::unique_ptr reader, + CreateReader(partition, bucket, data_files, dv_factory, local_row_ranges)); + if (context_->GetReadSchemaPlan()->NeedsProjection()) { + reader = std::make_unique( + std::move(reader), context_->GetReadSchemaPlan()->GetOutputSchema()->field_names(), + arrow_pool_); + } + return reader; } Result RawFileSplitRead::Match(const std::shared_ptr& split, diff --git a/src/paimon/core/operation/raw_file_split_read.h b/src/paimon/core/operation/raw_file_split_read.h index 82d87beb1..81c29f049 100644 --- a/src/paimon/core/operation/raw_file_split_read.h +++ b/src/paimon/core/operation/raw_file_split_read.h @@ -53,7 +53,8 @@ struct DeletionFile; /// otherwise, it must be present in the read path. /// /// Readers Overview: (TopKBatchReader) -> (ConcatBatchReader across splits) -/// -> CompleteRowKindBatchReader -> (PredicateBatchReader) -> ConcatBatchReader across files +/// -> (ProjectionBatchReader) -> CompleteRowKindBatchReader -> (PredicateBatchReader) +/// -> ConcatBatchReader across files /// -> (CompleteIndexScoreFileBatchReader) -> FieldMappingReader /// -> (ApplyDeletionVectorBatchReader) -> (ApplyBitmapIndexBatchReader) /// -> (CompleteRowTrackingFieldsBatchReader) -> (ShreddingFileReader) diff --git a/src/paimon/core/table/file_store_table.cpp b/src/paimon/core/table/file_store_table.cpp index 496d207f8..3b2b947e5 100644 --- a/src/paimon/core/table/file_store_table.cpp +++ b/src/paimon/core/table/file_store_table.cpp @@ -33,6 +33,7 @@ #include "paimon/commit_context.h" #include "paimon/common/fs/resolving_file_system.h" #include "paimon/common/predicate/predicate_validator.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/binary_row_partition_computer.h" @@ -90,6 +91,7 @@ #include "paimon/file_store_write.h" #include "paimon/format/file_format.h" #include "paimon/fs/file_system.h" +#include "paimon/predicate/predicate_utils.h" #include "paimon/read_context.h" #include "paimon/realtime/realtime_context.h" #include "paimon/result.h" @@ -505,9 +507,25 @@ Result> FileStoreTable::NewScan( auto arrow_schema = DataField::ConvertDataFieldsToArrowSchema(table_schema->Fields()); if (context->GetScanFilters() && context->GetScanFilters()->GetPredicate()) { + const auto& predicate = context->GetScanFilters()->GetPredicate(); + std::set field_names; + PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(predicate, &field_names)); + arrow::FieldVector allowed_system_fields; + if (core_options.RowTrackingEnabled()) { + allowed_system_fields.push_back( + DataField::ConvertDataFieldToArrowField(SpecialFields::RowId())); + } + if (core_options.RowTrackingEnabled() || core_options.KeyValueSequenceNumberEnabled()) { + allowed_system_fields.push_back( + DataField::ConvertDataFieldToArrowField(SpecialFields::SequenceNumber())); + } + PAIMON_RETURN_NOT_OK( + SpecialFields::ValidatePredicateFieldNames(field_names, allowed_system_fields)); + arrow::FieldVector validation_fields = arrow_schema->fields(); + validation_fields.insert(validation_fields.end(), allowed_system_fields.begin(), + allowed_system_fields.end()); PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( - *arrow_schema, context->GetScanFilters()->GetPredicate(), - /*validate_field_idx=*/false)); + *arrow::schema(validation_fields), predicate)); } PAIMON_ASSIGN_OR_RAISE(std::shared_ptr path_factory, file_store.NewPathFactory(arrow_schema, table_schema->PartitionKeys(), diff --git a/src/paimon/core/table/format/format_table_read.cpp b/src/paimon/core/table/format/format_table_read.cpp index 7be0e2f81..dfe2f3c65 100644 --- a/src/paimon/core/table/format/format_table_read.cpp +++ b/src/paimon/core/table/format/format_table_read.cpp @@ -35,6 +35,8 @@ #include "paimon/common/reader/concat_batch_reader.h" #include "paimon/common/reader/data_file_reader_factory.h" #include "paimon/common/reader/predicate_batch_reader.h" +#include "paimon/common/reader/projection_batch_reader.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/arrow/status_utils.h" @@ -47,10 +49,12 @@ #include "paimon/core/table/format/format_path_validation.h" #include "paimon/core/table/format/lazy_concat_batch_reader.h" #include "paimon/core/utils/field_mapping.h" +#include "paimon/core/utils/read_schema_plan.h" #include "paimon/format/file_format.h" #include "paimon/format/file_format_factory.h" #include "paimon/fs/file_system.h" #include "paimon/predicate/predicate.h" +#include "paimon/predicate/predicate_utils.h" namespace paimon { @@ -236,8 +240,8 @@ Result> DescribeFileColumns( class FormatTableRead::Impl { public: std::shared_ptr table; - /// Columns the reader returns, in the order it returns them. - std::shared_ptr read_schema; + /// Output columns and the internal read schema, including predicate dependencies. + std::shared_ptr schema_plan; /// The whole table schema, as the mapping describes a column: what a file's own columns are /// matched against, one file at a time. See `DescribeFileColumns()`. /// @@ -393,7 +397,20 @@ Result> FormatTableRead::CreateInternal( auto impl = std::make_unique(); impl->table = table; - impl->read_schema = arrow::schema(read_fields); + std::set required_fields; + if (predicate) { + PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(predicate, &required_fields)); + PAIMON_RETURN_NOT_OK(SpecialFields::ValidatePredicateFieldNames( + required_fields, /*allowed_system_fields=*/{})); + PAIMON_RETURN_NOT_OK( + PredicateValidator::ValidatePredicateWithSchema(*table_schema, predicate)); + } + if (enable_predicate_filter) { + impl->filter_predicate = predicate; + } + PAIMON_ASSIGN_OR_RAISE( + impl->schema_plan, + ReadSchemaPlan::Create(table_schema, arrow::schema(read_fields), required_fields)); impl->pool = memory_pool; impl->arrow_pool = GetArrowPool(memory_pool); impl->format_identifier = FormatTable::FormatToString(table->GetFormat()); @@ -401,7 +418,8 @@ Result> FormatTableRead::CreateInternal( DataField::ConvertArrowSchemaToDataFields(table_schema)); impl->table_fields = std::make_shared>(std::move(table_fields)); std::set read_file_columns; - for (const std::shared_ptr& read_field : read_fields) { + for (const std::shared_ptr& read_field : + impl->schema_plan->GetReadSchema()->fields()) { if (!is_partition_key(read_field->name())) { read_file_columns.insert(read_field->name()); } @@ -421,20 +439,10 @@ Result> FormatTableRead::CreateInternal( table->FullName())); } - if (predicate != nullptr) { - // The same rules `InternalReadContext` applies to a managed table's predicate. The field - // index is not among them: everything downstream resolves a field by name. - PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( - *impl->read_schema, predicate, /*validate_field_idx=*/false)); - if (enable_predicate_filter) { - impl->filter_predicate = predicate; - } - } - // The builder also hands the file reader only the conjuncts naming columns the file holds. PAIMON_ASSIGN_OR_RAISE( std::unique_ptr field_mapping_builder, - FieldMappingBuilder::Create(impl->read_schema, partition_keys, predicate)); + FieldMappingBuilder::Create(impl->schema_plan->GetReadSchema(), partition_keys, predicate)); impl->field_mapping_builder = std::move(field_mapping_builder); PAIMON_ASSIGN_OR_RAISE(CoreOptions core_options, @@ -592,7 +600,13 @@ Result> FormatTableRead::ApplyFilterAndRowKind( } // Every row is an insert, but `BatchReader::NextBatch()` still promises the leading // `_VALUE_KIND` field: an engine reading by field index would find its columns shifted. - return std::make_unique(std::move(result), impl_->arrow_pool); + result = std::make_unique(std::move(result), impl_->arrow_pool); + if (impl_->schema_plan->NeedsProjection()) { + result = std::make_unique( + std::move(result), impl_->schema_plan->GetOutputSchema()->field_names(), + impl_->arrow_pool); + } + return result; } Result> FormatTableRead::CreateReader( diff --git a/src/paimon/core/table/format/format_table_test.cpp b/src/paimon/core/table/format/format_table_test.cpp index 44b23fb9c..9b0aaa8ed 100644 --- a/src/paimon/core/table/format/format_table_test.cpp +++ b/src/paimon/core/table/format/format_table_test.cpp @@ -4962,21 +4962,9 @@ TEST(FormatTableTest, TestPredicateIsCheckedTheWayEveryOtherReadPathChecksIt) { /*enable_predicate_filter=*/false); ASSERT_FALSE(wrong_type.ok()); ASSERT_TRUE(wrong_type.status().IsInvalid()) << wrong_type.status().ToString(); - - // The field index a predicate carries is not one of the checks: everything downstream - // resolves a field by name, and a caller that built the predicate against the table cannot - // know where a projection will put the column. - std::shared_ptr wrong_index = PredicateBuilder::Equal( - /*field_index=*/7, /*field_name=*/"id", FieldType::INT, Literal(1)); - ASSERT_OK(FormatTableRead::TEST_Create(table, /*projection=*/std::nullopt, - /*pool=*/nullptr, wrong_index, - /*enable_predicate_filter=*/false)); } -TEST(FormatTableTest, TestPredicateMayOnlyNameColumnsTheReadProduces) { - // One rule, the one `InternalReadContext` applies to a managed table: validated against the - // read schema. An unknown field and a dropped one are refused alike, since nothing - // downstream could evaluate either. +TEST(FormatTableTest, TestPredicateMayNameUnprojectedTableColumns) { std::unique_ptr dir = UniqueTestDirectory::Create(); ASSERT_TRUE(dir); ASSERT_OK_AND_ASSIGN(std::shared_ptr table, @@ -4990,20 +4978,39 @@ TEST(FormatTableTest, TestPredicateMayOnlyNameColumnsTheReadProduces) { /*enable_predicate_filter=*/false), "does not exist in schema"); - // A column of the table that this read does not produce. + // A table column can be used by the predicate without appearing in the output. std::shared_ptr id_gt_1 = PredicateBuilder::GreaterThan( /*field_index=*/0, /*field_name=*/"id", FieldType::INT, Literal(1)); std::vector projection = {"name", "dt"}; - ASSERT_NOK_WITH_MSG(FormatTableRead::TEST_Create(table, projection, /*pool=*/nullptr, id_gt_1, - /*enable_predicate_filter=*/true), - "does not exist in schema"); - ASSERT_NOK(FormatTableRead::TEST_Create(table, projection, /*pool=*/nullptr, id_gt_1, - /*enable_predicate_filter=*/false)); + ASSERT_OK(FormatTableRead::TEST_Create(table, projection, /*pool=*/nullptr, id_gt_1, + /*enable_predicate_filter=*/true)); + ASSERT_OK(FormatTableRead::TEST_Create(table, projection, /*pool=*/nullptr, id_gt_1, + /*enable_predicate_filter=*/false)); // Projected back in, and the same predicate is accepted. ASSERT_OK(FormatTableRead::TEST_Create(table, std::vector{"id", "name", "dt"}, /*pool=*/nullptr, id_gt_1, /*enable_predicate_filter=*/true)); + + ASSERT_OK_AND_ASSIGN( + std::unique_ptr batch, + MakeBatch({1, 2, 3}, {"alice", "bob", "carol"}, "20240101", {{"dt", "20240101"}})); + ASSERT_OK(WriteAndCommit(table, std::move(batch))); + ASSERT_OK_AND_ASSIGN(std::unique_ptr scan, + FormatTableScan::Create(table, {}, std::nullopt)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, scan->CreatePlan()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr read, + FormatTableRead::TEST_Create(table, projection, nullptr, id_gt_1, true)); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, read->CreateReader(plan->Splits())); + ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatch result, reader->NextBatch()); + ASSERT_OK_AND_ASSIGN(std::shared_ptr rows, ImportBatch(result)); + ASSERT_EQ(rows->num_rows(), 2); + ASSERT_EQ(rows->schema()->field_names(), + (std::vector{"_VALUE_KIND", "name", "dt"})); + auto names = checked_pointer_cast(rows->column(1)); + ASSERT_EQ(names->GetString(0), "bob"); + ASSERT_EQ(names->GetString(1), "carol"); + reader->Close(); } TEST(FormatTableTest, TestAPartitionValueIsReadIntoItsColumnTypeBeforeItNamesADirectory) { diff --git a/src/paimon/core/table/source/append_only_table_read.cpp b/src/paimon/core/table/source/append_only_table_read.cpp index e555ff720..348222942 100644 --- a/src/paimon/core/table/source/append_only_table_read.cpp +++ b/src/paimon/core/table/source/append_only_table_read.cpp @@ -30,6 +30,7 @@ #include "paimon/common/reader/complete_row_kind_batch_reader.h" #include "paimon/common/reader/concat_batch_reader.h" #include "paimon/common/reader/predicate_batch_reader.h" +#include "paimon/common/reader/projection_batch_reader.h" #include "paimon/common/table/special_fields.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/arrow/arrow_utils.h" @@ -171,6 +172,7 @@ Result> AppendOnlyTableRead::CreateReader( Result> AppendOnlyTableRead::CreateRealtimeReader( const std::shared_ptr& realtime_split, const RealtimePartitionBucketView& memory) { + const auto& schema_plan = context_->GetReadSchemaPlan(); std::vector> readers; readers.reserve(realtime_split->DiskSplits().size() + 1); ScopeGuard readers_guard([&readers]() { @@ -197,6 +199,11 @@ Result> AppendOnlyTableRead::CreateRealtimeReader( context_, memory.mode, memory.store, memory.read_view, OffsetRange(realtime_split->CommittedEndOffset(), realtime_split->MemoryEndOffset()))); + if (schema_plan->NeedsProjection()) { + memory_reader = std::make_unique( + std::move(memory_reader), schema_plan->GetOutputSchema()->field_names(), + context_->GetArrowMemoryPool()); + } readers.push_back(std::move(memory_reader)); std::unique_ptr result = std::make_unique(std::move(readers), context_->GetArrowMemoryPool()); @@ -256,6 +263,11 @@ Result> AppendOnlyTableRead::CreateRealtimeReader( PredicateBatchReader::Create(std::move(memory_reader), context_->GetPredicate(), context_->GetArrowMemoryPool())); } + if (schema_plan->NeedsProjection()) { + memory_reader = std::make_unique( + std::move(memory_reader), schema_plan->GetOutputSchema()->field_names(), + context_->GetArrowMemoryPool()); + } PAIMON_ASSIGN_OR_RAISE(std::unique_ptr realtime_reader, RealtimeReader::Create(memory.read_view, std::move(memory_reader))); memory_reader = std::move(realtime_reader); @@ -306,6 +318,7 @@ Result> AppendOnlyTableRead::CreateDeduplicateDiskR return Status::Invalid("deduplicate real-time disk split is not a data split"); } + const auto& schema_plan = context_->GetReadSchemaPlan(); if (offset_deletions->IsEmpty()) { return raw_read->CreateReader(data_split->Partition(), data_split->Bucket(), data_split->DataFiles(), data_split->DeletionFiles(), @@ -354,6 +367,11 @@ Result> AppendOnlyTableRead::CreateDeduplicateDiskR if (!expose_offset) { reader = std::make_unique(std::move(reader)); } + if (schema_plan->NeedsProjection()) { + reader = std::make_unique( + std::move(reader), schema_plan->GetOutputSchema()->field_names(), + context_->GetArrowMemoryPool()); + } return reader; } diff --git a/src/paimon/core/table/source/data_evolution_full_text_read.cpp b/src/paimon/core/table/source/data_evolution_full_text_read.cpp index 57c6e7ff1..ad170dbcf 100644 --- a/src/paimon/core/table/source/data_evolution_full_text_read.cpp +++ b/src/paimon/core/table/source/data_evolution_full_text_read.cpp @@ -585,8 +585,7 @@ Result> DataEvolutionFullTextRead::Sear int64_t snapshot_id, const RowRangeIndex& raw_rows, const std::string& raw_index_type) const { if (filter_) { PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( - *DataField::ConvertDataFieldsToArrowSchema(table_schema_->Fields()), filter_, - /*validate_field_idx=*/false)); + *DataField::ConvertDataFieldsToArrowSchema(table_schema_->Fields()), filter_)); } // Keep data reads on the caller: they can submit work to the same executor as the shards. PAIMON_ASSIGN_OR_RAISE(std::optional live_rows, diff --git a/src/paimon/core/table/source/data_evolution_full_text_read_test.cpp b/src/paimon/core/table/source/data_evolution_full_text_read_test.cpp index aafc9a3a6..67fc3fa45 100644 --- a/src/paimon/core/table/source/data_evolution_full_text_read_test.cpp +++ b/src/paimon/core/table/source/data_evolution_full_text_read_test.cpp @@ -932,7 +932,8 @@ TEST_F(DataEvolutionFullTextReadTest, TestBuilderValidatesSettings) { std::unique_ptr row_id_field = NewBuilder(3); row_id_field->WithFilter(PredicateBuilder::Equal( /*field_index=*/0, "_ROW_ID", FieldType::BIGINT, Literal(static_cast(1)))); - ASSERT_NOK_WITH_MSG(row_id_field->NewFullTextScan(), "field _ROW_ID does not exist in schema"); + ASSERT_NOK_WITH_MSG(row_id_field->NewFullTextScan(), + "Predicate on system field '_ROW_ID' are not supported"); std::unique_ptr wrong_type = NewBuilder(3); wrong_type->WithFilter(PredicateBuilder::Equal(/*field_index=*/0, "id", FieldType::STRING, diff --git a/src/paimon/core/table/source/filtered_row_id_reader.cpp b/src/paimon/core/table/source/filtered_row_id_reader.cpp index 78a674439..34833e462 100644 --- a/src/paimon/core/table/source/filtered_row_id_reader.cpp +++ b/src/paimon/core/table/source/filtered_row_id_reader.cpp @@ -30,10 +30,8 @@ #include "arrow/c/bridge.h" #include "fmt/format.h" #include "paimon/common/table/special_fields.h" -#include "paimon/common/types/data_field.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" -#include "paimon/common/utils/object_utils.h" #include "paimon/common/utils/scope_guard.h" #include "paimon/core/catalog/catalog_utils.h" #include "paimon/core/global_index/global_index_evaluator_impl.h" @@ -46,7 +44,6 @@ #include "paimon/global_index/bitmap_global_index_result.h" #include "paimon/predicate/compound_predicate.h" #include "paimon/predicate/leaf_predicate.h" -#include "paimon/predicate/predicate_utils.h" #include "paimon/read_context.h" #include "paimon/reader/batch_reader.h" #include "paimon/scan_context.h" @@ -154,18 +151,10 @@ Result FilteredRowIdReader::MatchingRowIds(const RowRangeIndex& if (row_ranges.Ranges().empty()) { return matching; } - std::set filter_fields; - PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(filter_, &filter_fields)); - std::vector read_fields; - for (const DataField& field : table_schema_->Fields()) { - if (filter_fields.count(field.Name()) > 0) { - read_fields.push_back(field.Name()); - } - } PAIMON_ASSIGN_OR_RAISE(Snapshot snapshot, LoadSnapshot(options_, root_path_, snapshot_id_)); PAIMON_RETURN_NOT_OK( ReadRows(root_path_, table_schema_, options_, partition_filter_, snapshot, row_ranges, - read_fields, filter_, executor_, pool_, + /*read_fields=*/{}, filter_, executor_, pool_, [&row_ranges, &matching](const arrow::StructArray& /*batch*/, const arrow::Int64Array& row_ids) -> Status { for (int64_t i = 0; i < row_ids.length(); ++i) { @@ -230,10 +219,7 @@ Status FilteredRowIdReader::ReadRows( .WithMemoryPool(pool) .WithExecutor(executor); if (predicate) { - PAIMON_ASSIGN_OR_RAISE(std::shared_ptr read_predicate, - PredicateUtils::CreatePickedFieldFilter( - predicate, ObjectUtils::CreateIdentifierToIndexMap(fields))); - read_builder.SetPredicate(read_predicate).EnablePredicateFilter(true); + read_builder.SetPredicate(predicate).EnablePredicateFilter(true); } PAIMON_ASSIGN_OR_RAISE(std::unique_ptr read_context, read_builder.Finish()); PAIMON_ASSIGN_OR_RAISE(std::unique_ptr table_read, diff --git a/src/paimon/core/table/source/full_text_search_builder.cpp b/src/paimon/core/table/source/full_text_search_builder.cpp index 98b51c3e9..c8f7417e2 100644 --- a/src/paimon/core/table/source/full_text_search_builder.cpp +++ b/src/paimon/core/table/source/full_text_search_builder.cpp @@ -20,11 +20,13 @@ #include "paimon/table/source/full_text_search_builder.h" #include +#include #include #include "fmt/format.h" #include "paimon/common/predicate/predicate_filter.h" #include "paimon/common/predicate/predicate_validator.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/types/data_field.h" #include "paimon/common/utils/object_utils.h" #include "paimon/common/utils/path_util.h" @@ -224,6 +226,13 @@ Result ResolveFilters(const std::vector field_names; + if (filter) { + PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(filter, &field_names)); + } + PAIMON_RETURN_NOT_OK( + SpecialFields::ValidatePredicateFieldNames(field_names, /*allowed_system_fields=*/{})); + std::map partition_key_to_idx = ObjectUtils::CreateIdentifierToIndexMap(partition_keys); std::vector> partition_conjuncts; @@ -253,8 +262,7 @@ Result ResolveFilters(const std::vector reader, std::map> masks, - std::set dropped_fields, std::set decoded_fields, - std::shared_ptr arrow_pool, std::shared_ptr logical_type) + std::set decoded_fields, std::shared_ptr arrow_pool, + std::shared_ptr logical_type) : reader_(std::move(reader)), masks_(std::move(masks)), - dropped_fields_(std::move(dropped_fields)), decoded_fields_(std::move(decoded_fields)), arrow_pool_(std::move(arrow_pool)), logical_type_(std::move(logical_type)) { @@ -188,9 +191,6 @@ Result QueryAuthBatchReader::NextBatch() { arrow::ArrayVector children; for (int32_t i = 0; i < struct_type.num_fields(); ++i) { const std::shared_ptr& field = struct_type.field(i); - if (dropped_fields_.count(field->name()) > 0) { - continue; - } auto mask = masks_.find(field->name()); if (mask == masks_.end()) { const arrow::StructArray& source = @@ -278,6 +278,11 @@ Result> QueryAuthTableRead::Create( name)); } } + PAIMON_RETURN_NOT_OK( + SpecialFields::ValidatePredicateFieldNames(predicate_fields, /*allowed_system_fields=*/{})); + PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( + *DataField::ConvertDataFieldsToArrowSchema(table_schema->Fields()), + context->GetPredicate())); std::unique_ptr read(new QueryAuthTableRead( context, table_schema, arrow_pool, std::move(create_inner), std::move(output_fields))); // Built now, so a read the table cannot serve fails here rather than at the first split. @@ -435,24 +440,32 @@ Result> QueryAuthTableRead::CreateReader( std::vector>(), arrow_pool_)); } - // The columns read only for the rules or for the predicate, dropped from the output. - std::vector extra_fields; + std::shared_ptr source_schema = + DataField::ConvertDataFieldsToArrowSchema(table_schema_->Fields()); + std::shared_ptr output_schema = source_schema; if (output_fields_) { - std::set output(output_fields_->begin(), output_fields_->end()); - std::vector visible = output_fields_.value(); - for (const std::string& field : filter_fields) { - if (output.count(field) == 0) { - visible.push_back(field); - } + arrow::FieldVector fields; + for (const std::string& name : *output_fields_) { + fields.push_back(source_schema->GetFieldByName(name)); } - std::set required = rules.RequiredFields(visible); - required.insert(filter_fields.begin(), filter_fields.end()); - for (const DataField& field : table_schema_->Fields()) { - if (required.count(field.Name()) > 0 && output.count(field.Name()) == 0) { - extra_fields.push_back(field.Name()); - } + output_schema = arrow::schema(fields); + } + std::vector visible = output_schema->field_names(); + std::set visible_names(visible.begin(), visible.end()); + for (const std::string& field : filter_fields) { + if (visible_names.insert(field).second) { + visible.push_back(field); } } + std::set required = rules.RequiredFields(visible); + required.insert(filter_fields.begin(), filter_fields.end()); + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr schema_plan, + ReadSchemaPlan::Create(source_schema, output_schema, required)); + std::vector extra_fields; + for (int32_t i = output_schema->num_fields(); i < schema_plan->GetReadSchema()->num_fields(); + ++i) { + extra_fields.push_back(schema_plan->GetReadSchema()->field(i)->name()); + } PAIMON_ASSIGN_OR_RAISE(TableRead * inner, GetOrCreateInnerRead(extra_fields)); PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, inner->CreateReader(auth_split->GetSplit())); @@ -470,32 +483,26 @@ Result> QueryAuthTableRead::CreateReader( const std::map> no_masks; if (rules.RowFilter() != nullptr) { reader = std::make_unique( - std::move(reader), no_masks, - /*dropped_fields=*/std::set(), rules.RowFilterFields(), arrow_pool_, + std::move(reader), no_masks, rules.RowFilterFields(), arrow_pool_, DataField::ConvertDataFieldsToArrowStructType(table_schema_->Fields())); PAIMON_ASSIGN_OR_RAISE( std::unique_ptr filtered, PredicateBatchReader::Create(std::move(reader), rules.RowFilter(), arrow_pool_)); reader = std::make_unique(std::move(filtered)); } - std::set dropped_fields(extra_fields.begin(), extra_fields.end()); - if (!rules.Masks().empty() || !filter_fields.empty() || - (filter == nullptr && !dropped_fields.empty())) { - reader = std::make_unique( - std::move(reader), rules.Masks(), - filter == nullptr ? dropped_fields : std::set(), filter_fields, - arrow_pool_); + if (!rules.Masks().empty() || !filter_fields.empty()) { + reader = std::make_unique(std::move(reader), rules.Masks(), + filter_fields, arrow_pool_); } if (filter != nullptr) { PAIMON_ASSIGN_OR_RAISE( std::unique_ptr filtered, PredicateBatchReader::Create(std::move(reader), filter, arrow_pool_)); reader = std::move(filtered); - if (!dropped_fields.empty()) { - reader = std::make_unique( - std::move(reader), no_masks, dropped_fields, - /*decoded_fields=*/std::set(), arrow_pool_); - } + } + if (schema_plan->NeedsProjection()) { + reader = std::make_unique( + std::move(reader), schema_plan->GetOutputSchema()->field_names(), arrow_pool_); } close_guard.Release(); return reader; diff --git a/src/paimon/core/table/source/query_auth_table_read.h b/src/paimon/core/table/source/query_auth_table_read.h index 47c396285..9821e9fc1 100644 --- a/src/paimon/core/table/source/query_auth_table_read.h +++ b/src/paimon/core/table/source/query_auth_table_read.h @@ -42,14 +42,13 @@ class Metrics; class Predicate; class QueryAuthSplit; -/// Applies the column masks to each batch, each computed from the raw batch, and drops the columns -/// only the rules needed, mirroring Java `TableQueryAuthResult.doAuth`. The masked columns, and -/// the columns a predicate evaluated next reads, are output decoded. +/// Applies the column masks to each batch, each computed from the raw batch, mirroring Java +/// `TableQueryAuthResult.doAuth`. The masked columns, and the columns a predicate evaluated +/// next reads, are output decoded. class QueryAuthBatchReader : public BatchReader { public: /// @param masks The masks to apply, keyed by the column they replace; a mask whose column is /// not in a batch is not applied. - /// @param dropped_fields The columns removed from each batch after masking. /// @param decoded_fields The unmasked columns output no longer dictionary-encoded or large /// strings; other unmasked columns are output as read unless `logical_type` decodes /// them. @@ -57,7 +56,7 @@ class QueryAuthBatchReader : public BatchReader { /// logical schema so a row filter cannot leave unauthorized values in a dictionary. QueryAuthBatchReader(std::unique_ptr reader, std::map> masks, - std::set dropped_fields, std::set decoded_fields, + std::set decoded_fields, std::shared_ptr arrow_pool, std::shared_ptr logical_type = nullptr); @@ -79,7 +78,6 @@ class QueryAuthBatchReader : public BatchReader { std::unique_ptr reader_; std::map> masks_; - std::set dropped_fields_; std::set decoded_fields_; /// `decoded_fields_` and the columns `masks_` read. std::set decode_inputs_; diff --git a/src/paimon/core/table/source/query_auth_table_read_test.cpp b/src/paimon/core/table/source/query_auth_table_read_test.cpp index 32e39d7f4..9a596540a 100644 --- a/src/paimon/core/table/source/query_auth_table_read_test.cpp +++ b/src/paimon/core/table/source/query_auth_table_read_test.cpp @@ -33,6 +33,7 @@ #include "fmt/format.h" #include "gtest/gtest.h" #include "paimon/common/reader/predicate_batch_reader.h" +#include "paimon/common/reader/reader_utils.h" #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" @@ -173,8 +174,7 @@ TEST(QueryAuthTableReadTest, TestBatchReaderDecodesDictionaryAndLargeStringColum {"alias", fmt::format(R"({{"name": "FIELD_REF", "fieldRef": {}}})", nick_ref)}})); QueryAuthBatchReader reader(std::make_unique(batch), rules->Masks(), - /*dropped_fields=*/{}, /*decoded_fields=*/{}, - GetArrowPool(GetDefaultPool())); + /*decoded_fields=*/{}, GetArrowPool(GetDefaultPool())); ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatch masked_batch, reader.NextBatch()); ASSERT_FALSE(BatchReader::IsEofBatch(masked_batch)); std::shared_ptr masked = @@ -207,7 +207,6 @@ TEST(QueryAuthTableReadTest, TestBatchReaderDecodesDictionaryAndLargeStringColum PredicateBatchReader::Create(std::make_unique( std::make_unique(batch), std::map>(), - /*dropped_fields=*/std::set(), /*decoded_fields=*/std::set{"name", "phone"}, GetArrowPool(GetDefaultPool())), name_or_phone, GetArrowPool(GetDefaultPool()))); @@ -227,7 +226,6 @@ TEST(QueryAuthTableReadTest, TestBatchReaderDecodesDictionaryAndLargeStringColum std::make_unique( std::make_unique(batch), std::map>(), - /*dropped_fields=*/std::set(), /*decoded_fields=*/std::set{"name"}, GetArrowPool(GetDefaultPool()), /*logical_type=*/ arrow::struct_( @@ -396,4 +394,72 @@ TEST(QueryAuthTableReadTest, TestRowFilterRemovesRowsFromTheBatchWithBitmap) { assert_only_tenant_a(std::move(reader)); } +TEST(QueryAuthTableReadTest, FiltersAnUnprojectedMaskUsingItsUnprojectedInput) { + auto fields = arrow::schema( + {arrow::field("id", arrow::int32()), arrow::field("name", arrow::utf8()), + arrow::field("tenant", arrow::int32()), arrow::field("public_name", arrow::utf8())}); + ASSERT_OK_AND_ASSIGN(std::shared_ptr schema, + TableSchema::Create(0, fields, {}, {}, {})); + auto batch = + arrow::ipc::internal::json::ArrayFromJSON( + arrow::struct_(fields->fields()), + R"([[101,"private",7,"Alice"], [102,"Alice",8,"Alice"], [103,"Alice",7,"Bob"]])") + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN( + std::shared_ptr rules, + TableQueryAuthResult::Create( + {R"({"kind":"LEAF","transform":{"name":"FIELD_REF","fieldRef":{"index":2, "name":"tenant","type":"INT"}},"function":"EQUAL","literals":[7]})"}, + {{"name", + R"({"name":"FIELD_REF","fieldRef":{"index":3,"name":"public_name","type":"STRING"}})"}})); + QueryAuthScope scope; + scope.table_path = "table_root_path"; + scope.branch = "main"; + scope.authorized_field_ids = {{"id", schema->Fields()[0].Id()}, + {"name", schema->Fields()[1].Id()}}; + scope.rule_field_ids = rules->BindFieldIds(schema->Fields()); + auto split = std::make_shared(std::make_shared(), rules, scope); + for (bool filter_enabled : {false, true}) { + ReadContextBuilder builder(scope.table_path); + builder.SetReadFieldNames({"id"}) + .EnablePredicateFilter(filter_enabled) + .SetPredicate(PredicateBuilder::Equal(1, "name", FieldType::STRING, + Literal(FieldType::STRING, "Alice", 5))); + ASSERT_OK_AND_ASSIGN(std::shared_ptr context, builder.Finish()); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr read, + QueryAuthTableRead::Create( + context, schema, GetArrowPool(GetDefaultPool()), + [batch](std::unique_ptr inner) -> Result> { + // Create() first probes the reader without rule dependencies. + if (inner->GetReadFieldNames().size() > 1 && + inner->GetReadFieldNames() != + (std::vector{"id", "name", "tenant", "public_name"})) { + return Status::Invalid("incorrect auth dependency projection"); + } + if (inner->GetPredicate()) { + return Status::Invalid("masked predicate must not reach the raw reader"); + } + return std::unique_ptr(std::make_unique( + [batch]( + const std::shared_ptr&) -> Result> { + return std::unique_ptr( + std::make_unique(batch)); + })); + })); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, read->CreateReader(split)); + ASSERT_OK_AND_ASSIGN(BatchReader::ReadBatchWithBitmap result, + reader->NextBatchWithBitmap()); + ASSERT_EQ(result.second, RoaringBitmap32::From({0})); + ASSERT_OK_AND_ASSIGN( + BatchReader::ReadBatch filtered, + ReaderUtils::ApplyBitmapToReadBatch(std::move(result), GetArrowPool(GetDefaultPool()))); + auto array = arrow::ImportArray(filtered.first.get(), filtered.second.get()).ValueOrDie(); + ASSERT_TRUE( + array->Equals(*arrow::ipc::internal::json::ArrayFromJSON( + arrow::struct_({arrow::field("id", arrow::int32())}), "[[101]]") + .ValueOrDie())); + reader->Close(); + } +} + } // namespace paimon::test diff --git a/src/paimon/core/table/source/query_auth_table_scan.cpp b/src/paimon/core/table/source/query_auth_table_scan.cpp index e1c72b29d..f86313ca4 100644 --- a/src/paimon/core/table/source/query_auth_table_scan.cpp +++ b/src/paimon/core/table/source/query_auth_table_scan.cpp @@ -28,6 +28,8 @@ #include "arrow/c/abi.h" #include "arrow/c/bridge.h" #include "fmt/format.h" +#include "paimon/common/predicate/predicate_validator.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/object_utils.h" #include "paimon/core/catalog/catalog_utils.h" @@ -149,6 +151,13 @@ Result> QueryAuthTableScan::Create( columns.push_back(name); } } + if (scan_filter && scan_filter->GetPredicate()) { + PAIMON_RETURN_NOT_OK(SpecialFields::ValidatePredicateFieldNames( + user_filter_fields, /*allowed_system_fields=*/{})); + PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( + *DataField::ConvertDataFieldsToArrowSchema(table_schema->Fields()), + scan_filter->GetPredicate())); + } std::optional> authorization_columns; if (read_field_names) { authorization_columns = std::move(columns); diff --git a/src/paimon/core/table/source/table_read_test.cpp b/src/paimon/core/table/source/table_read_test.cpp index 46c5b844a..6d53cbbc5 100644 --- a/src/paimon/core/table/source/table_read_test.cpp +++ b/src/paimon/core/table/source/table_read_test.cpp @@ -100,18 +100,6 @@ TEST(TableReadTest, TestReadWithInvalidContext) { ASSERT_NOK_WITH_MSG(TableRead::Create(std::move(read_context)), "schema type double mismatches predicate field type BIGINT"); } - { - // field idx in predicate mismatch in schema - auto predicate = PredicateBuilder::Equal(/*field_index=*/2, /*field_name=*/"f3", - FieldType::DOUBLE, Literal(15.0)); - ReadContextBuilder context_builder(path); - context_builder.SetReadFieldNames({"f3", "f0", "f1"}); - context_builder.SetPredicate(predicate); - ASSERT_OK_AND_ASSIGN(auto read_context, context_builder.Finish()); - ASSERT_NOK_WITH_MSG( - TableRead::Create(std::move(read_context)), - "field f3 has field idx 0 in input schema, mismatch field idx 2 in predicate"); - } { // literal cannot be null auto predicate = PredicateBuilder::Equal(/*field_index=*/3, /*field_name=*/"f3", @@ -132,6 +120,47 @@ TEST(TableReadTest, TestReadWithInvalidContext) { } } +TEST(TableReadTest, ScanRowTrackingPredicatesKeepCandidatesForReadFiltering) { + const std::string path = + GetDataDir() + "/orc/multi_partition_append_table.db/multi_partition_append_table"; + ASSERT_OK_AND_ASSIGN(std::unique_ptr baseline_context, + ScanContextBuilder(path).Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr baseline_scan, + TableScan::Create(std::move(baseline_context))); + ASSERT_OK_AND_ASSIGN(std::shared_ptr baseline, baseline_scan->CreatePlan()); + ASSERT_FALSE(baseline->Splits().empty()); + for (const std::string& name : {"_ROW_ID", "_SEQUENCE_NUMBER"}) { + auto system = + PredicateBuilder::GreaterThan(77, name, FieldType::BIGINT, Literal(int64_t{100})); + auto impossible = PredicateBuilder::Equal(1, "f1", FieldType::INT, Literal(-999)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr conjunction, + PredicateBuilder::And({system, impossible})); + ASSERT_OK_AND_ASSIGN(std::shared_ptr disjunction, + PredicateBuilder::Or({system, impossible})); + for (const auto& predicate : {system, conjunction, disjunction}) { + ASSERT_OK_AND_ASSIGN(std::unique_ptr context, + ScanContextBuilder(path) + .AddOption(Options::ROW_TRACKING_ENABLED, "true") + .SetPredicate(predicate) + .Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr scan, + TableScan::Create(std::move(context))); + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, scan->CreatePlan()); + ASSERT_EQ(plan->Splits().size(), + predicate == conjunction ? 0 : baseline->Splits().size()); + } + ASSERT_OK_AND_ASSIGN(std::unique_ptr disabled, + ScanContextBuilder(path).SetPredicate(system).Finish()); + ASSERT_NOK_WITH_MSG(TableScan::Create(std::move(disabled)), "Predicate on system field"); + } + ASSERT_OK_AND_ASSIGN( + std::unique_ptr forbidden, + ScanContextBuilder(path) + .SetPredicate(PredicateBuilder::IsNotNull(77, "_VALUE_KIND", FieldType::TINYINT)) + .Finish()); + ASSERT_NOK_WITH_MSG(TableScan::Create(std::move(forbidden)), "Predicate on system field"); +} + TEST(TableReadTest, TestReadWithSpecifiedInvalidSchema) { std::string path = paimon::test::GetDataDir() + "/orc/append_09.db/append_09"; ReadContextBuilder context_builder(path); @@ -230,26 +259,48 @@ TEST(TableReadTest, TestMixedFilePredicateProducesScoresThroughPublicReadEntry) auto scalar = PredicateBuilder::GreaterThan(1, "f3", FieldType::DOUBLE, Literal(13.0)); ASSERT_OK_AND_ASSIGN(std::shared_ptr predicate, PredicateBuilder::And({text, scalar})); - ReadContextBuilder builder(path); - builder.EnablePreciseFileIndexEvaluate(true) - .SetReadFieldNames({"_f0_INDEX_SCORE", "f3", "f0"}) - .SetPredicate(predicate) - .AddOption(Options::READ_BATCH_SIZE, "1"); - ASSERT_OK_AND_ASSIGN(std::unique_ptr context, builder.Finish()); - ASSERT_OK_AND_ASSIGN(std::unique_ptr read, TableRead::Create(std::move(context))); - ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, read->CreateReader(selected_split)); - ASSERT_OK_AND_ASSIGN(std::shared_ptr actual, - ReadResultCollector::CollectResult(std::move(reader))); - ASSERT_TRUE(actual); - ASSERT_EQ(actual->length(), 1); - auto values = std::dynamic_pointer_cast(actual->chunk(0)); - ASSERT_TRUE(values); - auto scores = std::dynamic_pointer_cast(values->field(1)); - auto names = std::dynamic_pointer_cast(values->field(3)); - ASSERT_TRUE(scores); - ASSERT_TRUE(names); - ASSERT_FLOAT_EQ(scores->Value(0), 0.75f); - ASSERT_EQ(names->GetString(0), "Tony"); + for (bool root_topk : {false, true}) { + for (bool project_score : {false, true}) { + SCOPED_TRACE(root_topk); + SCOPED_TRACE(project_score); + std::vector output_fields = {"f0"}; + if (project_score) { + output_fields.insert(output_fields.begin(), "_f0_INDEX_SCORE"); + } + ReadContextBuilder builder(path); + builder.EnablePreciseFileIndexEvaluate(true) + .SetReadFieldNames(output_fields) + .SetPredicate(root_topk ? scalar : predicate) + .AddOption(Options::READ_BATCH_SIZE, "1"); + if (root_topk) { + builder.SetFullTextSearch(std::make_shared( + "f0", R"({"match":{"query":"names"}})", /*limit=*/1)); + } + ASSERT_OK_AND_ASSIGN(std::unique_ptr context, builder.Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr read, + TableRead::Create(std::move(context))); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + read->CreateReader(selected_split)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr actual, + ReadResultCollector::CollectResult(std::move(reader))); + ASSERT_TRUE(actual); + ASSERT_EQ(actual->length(), 1); + auto values = std::dynamic_pointer_cast(actual->chunk(0)); + ASSERT_TRUE(values); + output_fields.insert(output_fields.begin(), "_VALUE_KIND"); + ASSERT_EQ(arrow::schema(values->struct_type()->fields())->field_names(), output_fields); + auto names = + std::dynamic_pointer_cast(values->GetFieldByName("f0")); + ASSERT_TRUE(names); + ASSERT_EQ(names->GetString(0), "Tony"); + if (project_score) { + auto scores = std::dynamic_pointer_cast( + values->GetFieldByName("_f0_INDEX_SCORE")); + ASSERT_TRUE(scores); + ASSERT_FLOAT_EQ(scores->Value(0), 0.75f); + } + } + } } TEST(TableReadTest, TestRootTopKEmptyInput) { diff --git a/src/paimon/core/table/source/topk_batch_reader.cpp b/src/paimon/core/table/source/topk_batch_reader.cpp index 8bfe9fb72..0d4901b70 100644 --- a/src/paimon/core/table/source/topk_batch_reader.cpp +++ b/src/paimon/core/table/source/topk_batch_reader.cpp @@ -57,7 +57,8 @@ std::unique_ptr TopKBatchReader::ApplyTopkReaderIfNeeded( : ScoreOrder::DESCENDING; return std::make_unique(std::move(reader), score_name, score_order, limit, context.GetCoreOptions().GetReadBatchSize(), - context.GetReadSchema(), context.GetArrowMemoryPool()); + context.GetReadSchemaPlan()->GetOutputSchema(), + context.GetArrowMemoryPool()); } TopKBatchReader::TopKBatchReader(std::unique_ptr reader, diff --git a/src/paimon/core/utils/read_schema_plan.h b/src/paimon/core/utils/read_schema_plan.h new file mode 100644 index 000000000..25784f1f5 --- /dev/null +++ b/src/paimon/core/utils/read_schema_plan.h @@ -0,0 +1,83 @@ +/* + * 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 +#include + +#include "arrow/type.h" +#include "paimon/core/schema/arrow_schema_validator.h" +#include "paimon/result.h" + +namespace paimon { + +/// Separates the requested output from the columns needed to produce it. +class ReadSchemaPlan { + public: + static Result> Create( + const std::shared_ptr& source_schema, + const std::shared_ptr& output_schema, + const std::set& required_fields) { + if (!source_schema || !output_schema) { + return Status::Invalid("ReadSchemaPlan requires non-null schemas"); + } + for (const std::string& name : required_fields) { + if (source_schema->GetFieldIndex(name) < 0) { + return Status::Invalid("Cannot resolve required field: ", name); + } + } + PAIMON_RETURN_NOT_OK(ArrowSchemaValidator::ValidateSchema(*output_schema)); + arrow::FieldVector fields = output_schema->fields(); + std::set included; + for (const auto& field : fields) { + included.insert(field->name()); + } + // Retain output order and nested projections; append dependencies in source order. + for (const auto& field : source_schema->fields()) { + if (required_fields.count(field->name()) != 0 && + included.insert(field->name()).second) { + fields.push_back(field); + } + } + return std::shared_ptr( + new ReadSchemaPlan(output_schema, arrow::schema(fields, output_schema->metadata()))); + } + + const std::shared_ptr& GetReadSchema() const { + return read_schema_; + } + const std::shared_ptr& GetOutputSchema() const { + return output_schema_; + } + bool NeedsProjection() const { + return read_schema_->num_fields() != output_schema_->num_fields(); + } + + private: + ReadSchemaPlan(std::shared_ptr output_schema, + std::shared_ptr read_schema) + : output_schema_(std::move(output_schema)), read_schema_(std::move(read_schema)) {} + + std::shared_ptr output_schema_; + std::shared_ptr read_schema_; +}; +} // namespace paimon diff --git a/test/inte/data_evolution_table_test.cpp b/test/inte/data_evolution_table_test.cpp index 79e16a6f2..04b7500b5 100644 --- a/test/inte/data_evolution_table_test.cpp +++ b/test/inte/data_evolution_table_test.cpp @@ -3078,6 +3078,15 @@ TEST_P(DataEvolutionTableTest, TestDataEvolutionPredicatePushDownBoundaries) { /*row_ranges=*/{Range(0l, 4l)}, /*check_scan_plan_when_empty_result=*/true, /*apply_predicate_to_scan=*/false)); + // The indexed predicate column is an internal dependency when only row ids are requested. + expected_array = std::dynamic_pointer_cast( + arrow::ipc::internal::json::ArrayFromJSON( + arrow::struct_({SpecialFields::RowId().ArrowField()}), "[[4]]") + .ValueOrDie()); + ASSERT_OK(ScanAndRead(table_path, {"_ROW_ID"}, expected_array, predicate, + /*row_ranges=*/{Range(0l, 4l)}, + /*check_scan_plan_when_empty_result=*/true, + /*apply_predicate_to_scan=*/false)); } } diff --git a/test/inte/read_inte_test.cpp b/test/inte/read_inte_test.cpp index cdb354ccf..93e6daf56 100644 --- a/test/inte/read_inte_test.cpp +++ b/test/inte/read_inte_test.cpp @@ -2309,6 +2309,28 @@ TEST_P(ReadInteTest, TestAppendReadWithPredicate) { &expected_array); ASSERT_TRUE(array_status.ok()); ASSERT_TRUE(result_array->Equals(*expected_array)); + // Neither the data predicate nor the partition predicate is in the output. + ReadContextBuilder projected_builder(path); + projected_builder.SetReadFieldNames({"f0"}) + .SetPredicate(predicate) + .EnablePredicateFilter(true) + .SetReadAheadCacheEnabled(param.read_ahead_cache_enabled) + .EnablePrefetch(param.enable_prefetch) + .AddOption(Options::FILE_FORMAT, param.file_format) + .AddOption(Options::READ_BATCH_SIZE, "2") + .AddOption("test.enable-adaptive-prefetch-strategy", + param.enable_adaptive_prefetch_strategy); + ASSERT_OK_AND_ASSIGN(read_context, projected_builder.Finish()); + ASSERT_OK_AND_ASSIGN(table_read, TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(batch_reader, table_read->CreateReader(data_splits)); + ASSERT_OK_AND_ASSIGN(result_array, ReadResultCollector::CollectResult(batch_reader.get())); + ASSERT_TRUE(arrow::ipc::internal::json::ChunkedArrayFromJSON( + arrow::struct_({arrow::field("_VALUE_KIND", arrow::int8()), + arrow::field("f0", arrow::utf8())}), + {R"([[0,"Emily"],[0,"Alex"],[0,"David"],[0,"Lily"],[0,"Lucy"],[0,"Paul"]])"}, + &expected_array) + .ok()); + ASSERT_TRUE(result_array->Equals(*expected_array)); if (param.file_format == "orc") { // test metrics ASSERT_TRUE(read_metrics); @@ -3724,6 +3746,28 @@ TEST_P(ReadInteTest, TestPkReadSnapshot6WithSchemaEvolutionWithPredicateFilter) &expected_array); ASSERT_TRUE(array_status.ok()); ASSERT_TRUE(result_array->Equals(*expected_array)) << result_array->ToString(); + + // Merge and schema evolution must still evaluate unprojected partition/value fields. + ReadContextBuilder projected_builder(path); + projected_builder.SetReadFieldNames({"k"}) + .SetPredicate(predicate) + .EnablePredicateFilter(true) + .SetReadAheadCacheEnabled(param.read_ahead_cache_enabled) + .EnablePrefetch(param.enable_prefetch) + .AddOption(Options::FILE_FORMAT, param.file_format) + .AddOption(Options::READ_BATCH_SIZE, "2") + .AddOption("test.enable-adaptive-prefetch-strategy", + param.enable_adaptive_prefetch_strategy); + ASSERT_OK_AND_ASSIGN(read_context, projected_builder.Finish()); + ASSERT_OK_AND_ASSIGN(table_read, TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(batch_reader, table_read->CreateReader(data_splits)); + ASSERT_OK_AND_ASSIGN(result_array, ReadResultCollector::CollectResult(std::move(batch_reader))); + auto projected_type = + DataField::ConvertDataFieldsToArrowStructType({SpecialFields::ValueKind(), read_fields[1]}); + ASSERT_TRUE(arrow::ipc::internal::json::ChunkedArrayFromJSON( + projected_type, {R"([[0, "Paul"]])"}, &expected_array) + .ok()); + ASSERT_TRUE(result_array->Equals(*expected_array)) << result_array->ToString(); } TEST_P(ReadInteTest, TestAppendReadWithSchemaEvolutionWithBuildInFieldId) { diff --git a/test/inte/realtime_write_inte_test.cpp b/test/inte/realtime_write_inte_test.cpp index aae45e2c9..067eaa115 100644 --- a/test/inte/realtime_write_inte_test.cpp +++ b/test/inte/realtime_write_inte_test.cpp @@ -3665,7 +3665,38 @@ TEST_F(RealtimeWriteInteTest, Commit(data_file_progress, /*commit_identifier=*/0)); ASSERT_OK(writer->RefreshCommittedSnapshot(data_file_snapshot_id)); + const std::string matching_payload = "match"; + std::shared_ptr scan_predicate = PredicateBuilder::Equal( + /*field_index=*/2, /*field_name=*/"payload", FieldType::STRING, + Literal(FieldType::STRING, matching_payload.data(), matching_payload.size())); + auto check_projection = [&](bool empty_deletions, const std::string& expected_json) { + ASSERT_OK_AND_ASSIGN(std::shared_ptr projected_plan, + CreatePlan(realtime_context, scan_predicate)); + ASSERT_EQ(1, projected_plan->Splits().size()); + auto realtime_split = + std::dynamic_pointer_cast(projected_plan->Splits().front()); + ASSERT_NE(nullptr, realtime_split); + ASSERT_FALSE(realtime_split->DiskSplits().empty()); + ASSERT_OK_AND_ASSIGN(std::shared_ptr context_impl, + RealtimeContextImpl::Cast(realtime_context)); + ASSERT_OK_AND_ASSIGN(RealtimePartitionBucketView view, + context_impl->ResolveReadView(realtime_split->OpaqueTicket())); + ASSERT_NE(nullptr, view.offset_deletions); + ASSERT_EQ(empty_deletions, view.offset_deletions->IsEmpty()); + ASSERT_OK_AND_ASSIGN(std::shared_ptr projected_result, + ReadPlan(projected_plan, realtime_context, {"id"}, scan_predicate, + /*enable_predicate_filter=*/false)); + const std::shared_ptr projected_type = arrow::struct_( + {arrow::field("_VALUE_KIND", arrow::int8()), arrow::field("id", arrow::int64())}); + const std::shared_ptr expected = + arrow::ipc::internal::json::ArrayFromJSON(projected_type, expected_json).ValueOrDie(); + ASSERT_NE(nullptr, projected_result); + ASSERT_TRUE(std::make_shared(expected)->Equals(*projected_result)) + << projected_result->ToString(); + }; + ASSERT_OK(write_one({3, "match", "p0"})); + ASSERT_NO_FATAL_FAILURE(check_projection(/*empty_deletions=*/true, "[[0, 1], [0, 7], [0, 3]]")); ASSERT_OK(write_one({4, "sealed-other", "p0"})); ASSERT_OK(write_one({7, "replacement-other", "p0"})); ASSERT_OK(writer->Seal()); @@ -3673,10 +3704,6 @@ TEST_F(RealtimeWriteInteTest, ASSERT_OK(write_one({5, "match", "p0"})); ASSERT_OK(write_one({6, "building-other", "p0"})); - const std::string matching_payload = "match"; - std::shared_ptr scan_predicate = PredicateBuilder::Equal( - /*field_index=*/2, /*field_name=*/"payload", FieldType::STRING, - Literal(FieldType::STRING, matching_payload.data(), matching_payload.size())); std::shared_ptr read_predicate = PredicateBuilder::Equal( /*field_index=*/1, /*field_name=*/"payload", FieldType::STRING, Literal(FieldType::STRING, matching_payload.data(), matching_payload.size())); @@ -3687,6 +3714,8 @@ TEST_F(RealtimeWriteInteTest, ASSERT_OK_AND_ASSIGN(std::vector rows, ReadRows(plan, realtime_context, read_predicate, /*enable_predicate_filter=*/false)); ASSERT_EQ((std::vector{{1, "match", "p0"}, {3, "match", "p0"}, {5, "match", "p0"}}), rows); + ASSERT_NO_FATAL_FAILURE( + check_projection(/*empty_deletions=*/false, "[[0, 1], [0, 3], [0, 5]]")); ASSERT_OK_AND_ASSIGN(std::vector final_progress, writer->PrepareCommitWithProgress(/*commit_identifier=*/1)); ASSERT_EQ(1, final_progress.size()); @@ -4717,6 +4746,49 @@ TEST_F(RealtimeWriteInteTest, TestPkMergeDiskSealedAndActive) { .ValueOrDie(); ASSERT_TRUE(std::make_shared(expected)->Equals(*result)) << result->ToString(); + + // Matching old or deleted versions must be removed before filtering and dropping payload. + const std::shared_ptr predicate = PredicateBuilder::In( + /*field_index=*/1, /*field_name=*/"payload", FieldType::STRING, + {Literal(FieldType::STRING, "disk-1", 6), Literal(FieldType::STRING, "sealed-4", 8), + Literal(FieldType::STRING, "active-5", 8), Literal(FieldType::STRING, "disk-10", 7)}); + const std::shared_ptr projected_type = arrow::struct_( + {arrow::field("_VALUE_KIND", arrow::int8()), arrow::field("id", arrow::int64())}); + const std::shared_ptr expected_projected = + arrow::ipc::internal::json::ArrayFromJSON(projected_type, "[[0, 5], [0, 10]]").ValueOrDie(); + for (bool single_split : {false, true}) { + SCOPED_TRACE(single_split); + ASSERT_OK_AND_ASSIGN(std::shared_ptr projected_plan, + CreatePlan(realtime_context, predicate)); + std::shared_ptr projected_result; + if (single_split) { + ASSERT_EQ(1, projected_plan->Splits().size()); + ASSERT_NE(nullptr, + std::dynamic_pointer_cast(projected_plan->Splits().front())); + ReadContextBuilder read_builder(table_path_); + read_builder.SetOptions(options_) + .SetReadFieldNames({"id"}) + .SetPredicate(predicate) + .EnablePredicateFilter(true) + .WithRealtimeContext(realtime_context) + .WithMemoryPool(pool_); + ASSERT_OK_AND_ASSIGN(std::unique_ptr read_context, read_builder.Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr table_read, + TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + table_read->CreateReader(projected_plan->Splits().front())); + ASSERT_OK_AND_ASSIGN(projected_result, + ReadResultCollector::CollectResult(std::move(reader))); + } else { + ASSERT_OK_AND_ASSIGN(projected_result, + ReadPlan(projected_plan, realtime_context, {"id"}, predicate, + /*enable_predicate_filter=*/true)); + } + ASSERT_NE(nullptr, projected_result); + ASSERT_TRUE( + std::make_shared(expected_projected)->Equals(*projected_result)) + << projected_result->ToString(); + } ASSERT_OK(PrepareAndClose(writer.get())); } @@ -6894,16 +6966,10 @@ class RealtimePreciseIndexInteTest : public RealtimeWriteInteTest { Result> CreateSearchReader( const std::shared_ptr& plan, const std::shared_ptr& realtime_context, const SearchQuery& query) const { - std::map positions; - for (int32_t i = 0; i < static_cast(query.fields.size()); ++i) { - positions.emplace(query.fields[i], i); - } - PAIMON_ASSIGN_OR_RAISE(std::shared_ptr predicate, - PredicateUtils::CreatePickedFieldFilter(query.predicate, positions)); ReadContextBuilder builder(table_path_); builder.SetOptions(options_) .SetReadFieldNames(query.fields) - .SetPredicate(predicate) + .SetPredicate(query.predicate) .SetVectorSearch(query.vector) .SetFullTextSearch(query.text) .EnablePreciseFileIndexEvaluate(true) @@ -6981,9 +7047,8 @@ TEST_F(RealtimePreciseIndexInteTest, TestAppendScalarFilteringBeforeVectorTopK) for (const auto& predicate : predicates) { SCOPED_TRACE(predicate->ToString()); ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, CreatePlan(context, predicate)); - SearchQuery query{ - {"_embedding_INDEX_SCORE", "payload", "id", "pt"}, predicate, Vector(1), nullptr}; - ASSERT_NO_FATAL_FAILURE(CheckSearch(plan, context, query, R"([[0,0.875,"hit",2,"keep"]])")); + SearchQuery query{{"_embedding_INDEX_SCORE", "payload"}, predicate, Vector(1), nullptr}; + ASSERT_NO_FATAL_FAILURE(CheckSearch(plan, context, query, R"([[0,0.875,"hit"]])")); } ASSERT_OK(PrepareAndClose(writer.get())); } @@ -7016,13 +7081,11 @@ TEST_F(RealtimePreciseIndexInteTest, TestFullTextSearchAndMixedPredicateScores) auto range = PredicateBuilder::GreaterThan(0, "id", FieldType::BIGINT, Literal(int64_t{1})); ASSERT_OK_AND_ASSIGN(std::shared_ptr predicate, PredicateBuilder::And({match, range})); - SearchQuery mixed{{"id", "payload", "_payload_INDEX_SCORE", "_embedding_INDEX_SCORE"}, - predicate, - Vector(1), - nullptr}; + SearchQuery mixed{ + {"id", "_payload_INDEX_SCORE", "_embedding_INDEX_SCORE"}, predicate, Vector(1), nullptr}; // Split planning accepts scalar predicates; FullTextMatch is evaluated by the precise reader. ASSERT_OK_AND_ASSIGN(std::shared_ptr mixed_plan, CreatePlan(context, range)); - ASSERT_NO_FATAL_FAILURE(CheckSearch(mixed_plan, context, mixed, R"([[0,3,"lake",0.625,0.5]])")); + ASSERT_NO_FATAL_FAILURE(CheckSearch(mixed_plan, context, mixed, R"([[0,3,0.625,0.5]])")); ASSERT_OK(PrepareAndClose(writer.get())); } @@ -7970,10 +8033,9 @@ TEST_F(RealtimeWriteInteTest, TestProjectionAndPredicateForMemoryAndDisk) { std::shared_ptr read_predicate = PredicateBuilder::GreaterThan(/*field_index=*/1, /*field_name=*/"id", FieldType::BIGINT, Literal(static_cast(1))); - const std::vector read_fields = {"payload", "id"}; + const std::vector read_fields = {"payload"}; std::shared_ptr result_type = arrow::struct_( - {arrow::field("_VALUE_KIND", arrow::int8()), arrow::field("payload", arrow::utf8()), - arrow::field("id", arrow::int64())}); + {arrow::field("_VALUE_KIND", arrow::int8()), arrow::field("payload", arrow::utf8())}); std::vector disk_rows = MakeRows(/*first_id=*/0, /*count=*/3, /*partition=*/"p0"); ASSERT_OK_AND_ASSIGN(std::unique_ptr disk_batch, @@ -7987,7 +8049,7 @@ TEST_F(RealtimeWriteInteTest, TestProjectionAndPredicateForMemoryAndDisk) { /*enable_predicate_filter=*/true)); std::shared_ptr expected_memory = arrow::ipc::internal::json::ArrayFromJSON(result_type, R"([ - [0, "value-2", 2] + [0, "value-2"] ])") .ValueOrDie(); ASSERT_NE(nullptr, memory_result); @@ -8008,10 +8070,10 @@ TEST_F(RealtimeWriteInteTest, TestProjectionAndPredicateForMemoryAndDisk) { /*enable_predicate_filter=*/true)); std::shared_ptr expected_union = arrow::ipc::internal::json::ArrayFromJSON(result_type, R"([ - [0, "value-2", 2], - [0, "value-3", 3], - [0, "value-4", 4], - [0, "value-5", 5] + [0, "value-2"], + [0, "value-3"], + [0, "value-4"], + [0, "value-5"] ])") .ValueOrDie(); ASSERT_NE(nullptr, union_result); diff --git a/test/inte/write_and_read_inte_with_index_test.cpp b/test/inte/write_and_read_inte_with_index_test.cpp index f276b8424..5e92ce447 100644 --- a/test/inte/write_and_read_inte_with_index_test.cpp +++ b/test/inte/write_and_read_inte_with_index_test.cpp @@ -1900,6 +1900,7 @@ TEST_P(WriteAndReadInteWithIndexTest, TestPkDvPreciseScalarPredicates) { ASSERT_OK_AND_ASSIGN(std::shared_ptr disjunction, PredicateBuilder::Or({name, value})); CheckPkDvPreciseResult(split, fields, R"([[0,5,"Bob",16.1]])", conjunction); + CheckPkDvPreciseResult(split, {arrow::field("key", arrow::int32())}, "[[0,5]]", conjunction); CheckPkDvPreciseResult( split, fields, R"([[0,1,"Bob",12.1],[0,5,"Bob",16.1],[0,6,"Tony",17.1],[0,7,"Alice",18.1]])", disjunction); @@ -1931,6 +1932,10 @@ TEST_P(WriteAndReadInteWithIndexTest, TestPkDvMixedFilePredicatesAndScores) { {arrow::field("_f0_INDEX_SCORE", arrow::float32()), arrow::field("key", arrow::int32()), arrow::field("f0", arrow::utf8()), arrow::field("f3", arrow::float64())}, R"([[0,0.125,6,"Tony",17.1],[0,0.5,7,"Alice",18.1]])", predicate); + CheckPkDvPreciseResult(split, + {arrow::field("_f0_INDEX_SCORE", arrow::float32()), + arrow::field("key", arrow::int32())}, + R"([[0,0.125,6],[0,0.5,7]])", predicate); } { ASSERT_OK_AND_ASSIGN( @@ -1971,9 +1976,8 @@ TEST_P(WriteAndReadInteWithIndexTest, TestPkDvFullTextTopKFiltersBeforeLimit) { // the surviving TopK, which is returned in descending full-text score order. CheckPkDvPreciseResult( split, - {arrow::field("key", arrow::int32()), arrow::field("_f0_INDEX_SCORE", arrow::float32()), - arrow::field("f3", arrow::float64())}, - R"([[0,5,0.625,16.1],[0,2,0.5,13.1]])", predicate, /*vector_search=*/nullptr, search); + {arrow::field("key", arrow::int32()), arrow::field("_f0_INDEX_SCORE", arrow::float32())}, + R"([[0,5,0.625],[0,2,0.5]])", predicate, /*vector_search=*/nullptr, search); ASSERT_EQ(statistics_->executions.size(), 1); ASSERT_TRUE(statistics_->executions.front().needs_scores); ASSERT_FALSE(search->include_row_ids); From a798f9f995d3c0443cdd12c47d459641503073cd Mon Sep 17 00:00:00 2001 From: "lisizhuo.lsz" Date: Thu, 26 Nov 2026 09:01:40 +0000 Subject: [PATCH 2/2] docs(read): clarify name-based predicate field binding --- docs/source/user_guide/file_index.rst | 6 +++--- docs/source/user_guide/realtime.rst | 3 ++- include/paimon/predicate/predicate_builder.h | 10 +++++----- include/paimon/read_context.h | 8 ++++---- include/paimon/scan_context.h | 4 ++-- 5 files changed, 16 insertions(+), 15 deletions(-) diff --git a/docs/source/user_guide/file_index.rst b/docs/source/user_guide/file_index.rst index 236f05d43..1516ebdfb 100644 --- a/docs/source/user_guide/file_index.rst +++ b/docs/source/user_guide/file_index.rst @@ -47,9 +47,9 @@ after passing it to a predicate or read context. Compose full-text and scalar predicates with the existing ``PredicateBuilder::And`` and ``PredicateBuilder::Or`` factories. Referenced fields -need not appear in the output projection; field indices refer to zero-based -positions in the complete table schema. For example, for a table whose first two -columns are ``body`` and ``price``, the following constructs +need not appear in the output projection. Table reads resolve predicate fields by +name and rebind their execution indices; supplied ``field_index`` values are not +validated. For a table containing ``body`` and ``price``, the following constructs ``body matches "apple" OR price < 10``: .. code-block:: cpp diff --git a/docs/source/user_guide/realtime.rst b/docs/source/user_guide/realtime.rst index efcceb6cd..10fb61941 100644 --- a/docs/source/user_guide/realtime.rst +++ b/docs/source/user_guide/realtime.rst @@ -432,7 +432,8 @@ candidate offsets; statistics can then skip batches whose maximum ``score`` is at most 100. Statistics cover entire batches, so mixed batches still need row-level filtering. Enable ``ReadContextBuilder::EnablePredicateFilter(true)`` for exact -filtering. Predicate indices refer to the complete table schema; the reader +filtering. Predicate fields are resolved by name; supplied ``field_index`` values +are not validated, and execution indices are rebound internally. The reader fetches any unprojected predicate columns internally. In-memory and disk indexes are configured independently. Use diff --git a/include/paimon/predicate/predicate_builder.h b/include/paimon/predicate/predicate_builder.h index 117bf28e8..c3b36899b 100644 --- a/include/paimon/predicate/predicate_builder.h +++ b/include/paimon/predicate/predicate_builder.h @@ -35,8 +35,8 @@ enum class FieldType; /// /// PredicateBuilder provides static factory methods to create various types of predicates /// that can be used for filtering data in Paimon tables. -/// For table queries, field_index is the zero-based position in the complete table schema, -/// not a persistent field ID or a position in the output projection. +/// Table scans and reads resolve predicate fields by name and rebind their execution indices. +/// They do not validate the supplied field_index values. class PAIMON_EXPORT PredicateBuilder { public: PredicateBuilder() = delete; @@ -45,7 +45,7 @@ class PAIMON_EXPORT PredicateBuilder { /// Create a full-text predicate returning all matching rows without TopK truncation. /// The field must have STRING type and a full-text index. /// Project `__INDEX_SCORE` in the read schema to request score output. - /// @param field_index The index of the field in the complete table schema (0-based). + /// @param field_index Field index stored in the predicate; table queries rebind it by name. /// @param match The full-text request, including the field name, JSON DSL query and /// optional eligible row ids. static Result> FullTextMatch( @@ -53,7 +53,7 @@ class PAIMON_EXPORT PredicateBuilder { /// Create an equality predicate (field == literal). /// - /// @param field_index The index of the field in the complete table schema (0-based). + /// @param field_index Field index stored in the predicate; table queries rebind it by name. /// @param field_name The name of the field. /// @param field_type The data type of the field. /// @param literal The literal value to compare against. @@ -115,7 +115,7 @@ class PAIMON_EXPORT PredicateBuilder { /// /// Tests whether the field value falls within the specified range (inclusive on both ends). /// - /// @param field_index The index of the field in the complete table schema (0-based). + /// @param field_index Field index stored in the predicate; table queries rebind it by name. /// @param field_name The name of the field. /// @param field_type The data type of the field. /// @param included_lower_bound The lower bound of the range (inclusive). diff --git a/include/paimon/read_context.h b/include/paimon/read_context.h index 4e12c2222..53243bfef 100644 --- a/include/paimon/read_context.h +++ b/include/paimon/read_context.h @@ -358,12 +358,12 @@ class PAIMON_EXPORT ReadContextBuilder { /// It can significantly improve performance by reducing the amount of data /// that needs to be read and processed. /// - /// Referenced fields, including full-text match fields, need not be projected. Field indices - /// are zero-based positions in the complete table schema, not field IDs or projection indices. + /// Referenced fields, including full-text match fields, need not be projected. + /// Predicate fields are resolved by name; supplied field_index values are not validated, + /// and execution indices are rebound internally. /// Full-text matches can be combined with scalar predicates using PredicateBuilder::And/Or. - /// Supplied indices are not validated; execution positions are bound by field name. /// Among system fields, only _ROW_ID and _SEQUENCE_NUMBER support user predicates, subject - /// to their option requirements. Their indices do not require fixed table-schema positions. + /// to their option requirements. /// /// @param predicate Shared pointer to the predicate for data filtering. /// @return Reference to this builder for method chaining. diff --git a/include/paimon/scan_context.h b/include/paimon/scan_context.h index d8d8a8cc9..11e12c03c 100644 --- a/include/paimon/scan_context.h +++ b/include/paimon/scan_context.h @@ -216,8 +216,8 @@ class PAIMON_EXPORT ScanContextBuilder { /// partition_filters is {{k1=1,k2=10}, {k1=2,k2=20}} => OR(AND(k1=1,k2=10), AND(k1=2,k2=20)) ScanContextBuilder& SetPartitionFilter( const std::vector>& partition_filters); - /// Set a predicate for filtering data. Field indices are zero-based positions in the - /// complete table schema, independently of the requested output fields. + /// Set a predicate for filtering data. Predicate fields are resolved by name; supplied + /// field_index values are not validated, and execution indices are rebound internally. ScanContextBuilder& SetPredicate(const std::shared_ptr& predicate); /// Set the columns the query reads. A table with `query-auth.enabled=true` asks its catalog /// for the rules of these columns plus those of the predicate and the partition filter; by