diff --git a/docs/source/user_guide/file_index.rst b/docs/source/user_guide/file_index.rst index 5a8378748..1516ebdfb 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. 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/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..10fb61941 100644 --- a/docs/source/user_guide/realtime.rst +++ b/docs/source/user_guide/realtime.rst @@ -431,8 +431,10 @@ 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 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 ``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..c3b36899b 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. +/// 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; @@ -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 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( @@ -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 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. @@ -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 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 dbefd974a..53243bfef 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. + /// 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. - /// Predicates on virtual index score columns (_INDEX_SCORE or __INDEX_SCORE) are not - /// supported. + /// Among system fields, only _ROW_ID and _SEQUENCE_NUMBER support user predicates, subject + /// 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 93f3ba2db..11e12c03c 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. 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 diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt index 4ab30167d..51d1ec0e1 100644 --- a/src/paimon/CMakeLists.txt +++ b/src/paimon/CMakeLists.txt @@ -501,6 +501,7 @@ set(PAIMON_CORE_SRCS core/table/source/merge_tree_split_generator.cpp core/table/source/data_evolution_split_generator.cpp core/table/source/plan_impl.cpp + core/table/source/projection_batch_reader.cpp core/table/source/query_auth_table_read.cpp core/table/source/query_auth_table_scan.cpp core/table/source/realtime_table_scan.cpp @@ -1081,6 +1082,7 @@ if(PAIMON_BUILD_TESTS) core/table/sink/commit_message_impl_test.cpp core/table/source/fallback_data_split_test.cpp core/table/source/primary_key_sorted_index_scan_test.cpp + core/table/source/projection_batch_reader_test.cpp core/table/source/query_auth_split_test.cpp core/table/source/query_auth_table_read_test.cpp core/table/source/table_read_test.cpp diff --git a/src/paimon/common/predicate/predicate_validator.h b/src/paimon/common/predicate/predicate_validator.h index 00241723f..611d2bedf 100644 --- a/src/paimon/common/predicate/predicate_validator.h +++ b/src/paimon/common/predicate/predicate_validator.h @@ -20,15 +20,19 @@ #include #include +#include #include #include #include "arrow/type.h" #include "arrow/util/decimal.h" #include "fmt/format.h" +#include "paimon/common/table/special_fields.h" #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/date_time_utils.h" #include "paimon/common/utils/field_type_utils.h" +#include "paimon/core/core_options.h" +#include "paimon/core/schema/table_schema.h" #include "paimon/data/decimal.h" #include "paimon/defs.h" #include "paimon/predicate/compound_predicate.h" @@ -36,6 +40,8 @@ #include "paimon/predicate/leaf_predicate.h" #include "paimon/predicate/literal.h" #include "paimon/predicate/predicate.h" +#include "paimon/predicate/predicate_utils.h" +#include "paimon/result.h" #include "paimon/status.h" namespace paimon { @@ -44,11 +50,58 @@ class PredicateValidator { PredicateValidator() = delete; ~PredicateValidator() = delete; + /// Checks user predicate names against the system fields supported by the scan/read entry. + static Status ValidatePredicateFieldNames( + const std::set& field_names, + const std::vector>& allowed_system_fields) { + for (const auto& name : field_names) { + if (!SpecialFields::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(); + } + + /// Resolves the schema available to scan/read predicates and checks system-field admission. + static Result> ResolvePredicateSchema( + const std::shared_ptr& table_schema, + const std::shared_ptr& predicate, const CoreOptions& core_options) { + auto arrow_schema = DataField::ConvertDataFieldsToArrowSchema(table_schema->Fields()); + if (!predicate) { + return arrow_schema; + } + 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() || (!table_schema->PrimaryKeys().empty() && + core_options.KeyValueSequenceNumberEnabled())) { + allowed_system_fields.push_back( + DataField::ConvertDataFieldToArrowField(SpecialFields::SequenceNumber())); + } + PAIMON_RETURN_NOT_OK(ValidatePredicateFieldNames(field_names, allowed_system_fields)); + arrow::FieldVector fields = arrow_schema->fields(); + fields.insert(fields.end(), allowed_system_fields.begin(), allowed_system_fields.end()); + return arrow::schema(fields, arrow_schema->metadata()); + } + 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 +143,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 +167,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..c0eed3267 100644 --- a/src/paimon/common/predicate/predicate_validator_test.cpp +++ b/src/paimon/common/predicate/predicate_validator_test.cpp @@ -19,7 +19,9 @@ #include "paimon/common/predicate/predicate_validator.h" #include "arrow/type_fwd.h" +#include "fmt/format.h" #include "gtest/gtest.h" +#include "paimon/common/table/special_fields.h" #include "paimon/data/decimal.h" #include "paimon/data/timestamp.h" #include "paimon/predicate/full_text_match.h" @@ -32,25 +34,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 +64,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 +79,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 +94,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 +138,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 +155,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 +173,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 +190,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 +233,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 +257,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 +282,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 +306,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 +330,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 +354,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 +367,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 +396,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 +405,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 +426,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 +450,38 @@ 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]"); + } +} + +TEST(PredicateValidatorTest, PredicateFieldNamesAllowOnlyConfiguredSystemFields) { + ASSERT_OK(PredicateValidator::ValidatePredicateFieldNames({"id", "name"}, {})); + arrow::FieldVector allowed_fields = {SpecialFields::RowId().ArrowField(), + SpecialFields::SequenceNumber().ArrowField()}; + ASSERT_OK(PredicateValidator::ValidatePredicateFieldNames({"id", "_ROW_ID", "_SEQUENCE_NUMBER"}, + allowed_fields)); + for (const auto& field : allowed_fields) { + ASSERT_OK(PredicateValidator::ValidatePredicateFieldNames({"id", field->name()}, {field})); + ASSERT_NOK_WITH_MSG( + PredicateValidator::ValidatePredicateFieldNames({field->name()}, {}), + fmt::format("Predicate on system field '{}' are not supported", field->name())); + ASSERT_NOK_WITH_MSG(PredicateValidator::ValidatePredicateFieldNames( + {"_ROW_ID", "_SEQUENCE_NUMBER"}, {field}), + "Predicate on system field"); } } + +TEST(PredicateValidatorTest, 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( + PredicateValidator::ValidatePredicateFieldNames({field_name}, allowed_fields), + fmt::format("Predicate on system field '{}' are not supported", field_name)); + } +} + } // namespace paimon::test diff --git a/src/paimon/common/reader/index_score_batch_utils.cpp b/src/paimon/common/reader/index_score_batch_utils.cpp index a72c4beeb..e039d8c46 100644 --- a/src/paimon/common/reader/index_score_batch_utils.cpp +++ b/src/paimon/common/reader/index_score_batch_utils.cpp @@ -74,8 +74,8 @@ Result IndexScoreBatchUtils::CompleteScoresImp PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr array, builder.Finish()); arrays.push_back(std::move(array)); } - PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(std::shared_ptr output, - arrow::StructArray::Make(arrays, output_schema->fields())); + auto output = std::make_shared(arrow::struct_(output_schema->fields()), + data->length(), arrays); PAIMON_RETURN_NOT_OK_FROM_ARROW( arrow::ExportArray(*output, batch.first.first.get(), batch.first.second.get())); PAIMON_RETURN_NOT_OK( 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/table/special_fields_test.cpp b/src/paimon/common/table/special_fields_test.cpp index 94df21676..258293bc3 100644 --- a/src/paimon/common/table/special_fields_test.cpp +++ b/src/paimon/common/table/special_fields_test.cpp @@ -22,6 +22,7 @@ #include "arrow/type.h" #include "gtest/gtest.h" +#include "paimon/testing/utils/testharness.h" 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..68f44e6d4 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,7 @@ #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/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 +39,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 +327,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( + PredicateValidator::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 +342,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..15d45627b 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( @@ -71,9 +73,16 @@ Status CompleteRowTrackingFieldsBatchReader::SetReadSchema( !ObjectUtils::Contains(file_field_names, SpecialFields::SequenceNumber().Name())) { PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(arrow_schema, arrow_schema->RemoveField(sequence_id_idx)); } + // Physically present row-tracking fields can also contain nulls that will be completed. + // Keep their predicates out of physical pushdown until the logical values are available. + std::set excluded_predicate_fields = {SpecialFields::RowId().Name(), + SpecialFields::SequenceNumber().Name()}; + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr physical_predicate, + PredicateUtils::ExcludePredicateWithFields(predicate, excluded_predicate_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/io/complete_row_tracking_fields_reader_test.cpp b/src/paimon/core/io/complete_row_tracking_fields_reader_test.cpp index 04f05c30a..c0f61e1d9 100644 --- a/src/paimon/core/io/complete_row_tracking_fields_reader_test.cpp +++ b/src/paimon/core/io/complete_row_tracking_fields_reader_test.cpp @@ -18,6 +18,7 @@ #include "paimon/core/io/complete_row_tracking_fields_reader.h" +#include #include #include #include @@ -27,10 +28,13 @@ #include "arrow/api.h" #include "arrow/array/array_base.h" #include "arrow/array/array_nested.h" +#include "arrow/c/bridge.h" #include "arrow/ipc/json_simple.h" #include "gtest/gtest.h" +#include "paimon/common/reader/predicate_batch_reader.h" #include "paimon/common/utils/arrow/mem_utils.h" #include "paimon/memory/memory_pool.h" +#include "paimon/predicate/predicate_builder.h" #include "paimon/status.h" #include "paimon/testing/mock/mock_file_batch_reader.h" #include "paimon/testing/utils/read_result_collector.h" @@ -283,6 +287,59 @@ TEST_F(CompleteRowTrackingFieldsBatchReaderTest, TestWithAllNullRowTrackingField CheckResult(src_array, /*first_row_id=*/100, /*snapshot_id=*/8, read_schema, target_array); } +TEST_F(CompleteRowTrackingFieldsBatchReaderTest, TestPredicatesWithNullSequenceNumbers) { + class PredicateRecordingFileBatchReader : public MockFileBatchReader { + public: + using MockFileBatchReader::MockFileBatchReader; + + Status SetReadSchema(ArrowSchema* read_schema, const std::shared_ptr& predicate, + const std::optional& selection_bitmap) override { + predicate_ = predicate; + return MockFileBatchReader::SetReadSchema(read_schema, predicate, selection_bitmap); + } + + std::shared_ptr predicate_; + }; + + auto read_schema = arrow::schema( + {arrow::field("f0", arrow::int32()), arrow::field("_SEQUENCE_NUMBER", arrow::int64())}); + auto read_type = arrow::struct_(read_schema->fields()); + auto data_predicate = PredicateBuilder::GreaterOrEqual(0, "f0", FieldType::INT, Literal(0)); + auto sequence_predicate = + PredicateBuilder::Equal(1, "_SEQUENCE_NUMBER", FieldType::BIGINT, Literal(int64_t{8})); + ASSERT_OK_AND_ASSIGN(std::shared_ptr predicate, + PredicateBuilder::And({data_predicate, sequence_predicate})); + const std::vector> test_cases = { + {"[[0,null],[1,null]]", "[[0,8],[1,8]]"}, + {"[[0,null],[1,3]]", "[[0,8]]"}, + }; + for (const auto& [src_json, expected_json] : test_cases) { + auto src_array = + arrow::ipc::internal::json::ArrayFromJSON(read_type, src_json).ValueOrDie(); + auto file_reader = std::make_unique( + src_array, read_type, /*read_batch_size=*/2); + auto* mock_reader = file_reader.get(); + auto completing_reader = std::make_unique( + std::move(file_reader), /*first_row_id=*/std::nullopt, /*snapshot_id=*/8, + /*file_field_names=*/std::nullopt, GetArrowPool(pool_)); + ArrowSchema c_read_schema; + ASSERT_TRUE(arrow::ExportSchema(*read_schema, &c_read_schema).ok()); + ASSERT_OK(completing_reader->SetReadSchema(&c_read_schema, predicate, + /*selection_bitmap=*/std::nullopt)); + ASSERT_TRUE(mock_reader->predicate_); + ASSERT_TRUE(*mock_reader->predicate_ == *data_predicate); + + ASSERT_OK_AND_ASSIGN(auto reader, + PredicateBatchReader::Create(std::move(completing_reader), predicate, + GetArrowPool(pool_))); + ASSERT_OK_AND_ASSIGN(auto result, ReadResultCollector::CollectResult(std::move(reader))); + auto expected_array = + arrow::ipc::internal::json::ArrayFromJSON(read_type, expected_json).ValueOrDie(); + ASSERT_TRUE(result); + ASSERT_TRUE(result->Equals(arrow::ChunkedArray(expected_array))) << result->ToString(); + } +} + TEST_F(CompleteRowTrackingFieldsBatchReaderTest, TestPartialNullRowTrackingFieldsWithUnorderFields) { arrow::FieldVector fields = { 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..150c4b6f0 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" @@ -166,19 +167,16 @@ AbstractSplitRead::CreateRawFileReadersWithMetaImpl( auto create_reader = [&](const std::shared_ptr& file) -> Result { PAIMON_ASSIGN_OR_RAISE(std::shared_ptr predicate, predicate_provider(file)); - PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr field_mapping_builder, - FieldMappingBuilder::Create( - read_schema, context_->GetPartitionKeys(), - context_->EnablePreciseFileIndexEvaluate() ? nullptr : predicate)); if (context_->EnablePreciseFileIndexEvaluate()) { - PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr reader, - CreatePreciseFileIndexReader(partition, file, read_schema, predicate, - field_mapping_builder.get(), dv_factory, row_ranges, - data_file_path_factory, extra_format_options)); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, + CreatePreciseFileIndexReader( + partition, file, read_schema, predicate, dv_factory, + row_ranges, data_file_path_factory, extra_format_options)); return RawFileReaderWithMeta{file, std::move(reader)}; } + PAIMON_ASSIGN_OR_RAISE( + std::unique_ptr field_mapping_builder, + FieldMappingBuilder::Create(read_schema, context_->GetPartitionKeys(), predicate)); return CreateRawFileReader(partition, file, field_mapping_builder.get(), dv_factory, row_ranges, data_file_path_factory, extra_format_options, attach_blob_context); @@ -251,7 +249,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(); @@ -356,8 +359,7 @@ Result AbstractSplitRead::CreateRawFil Result> AbstractSplitRead::CreatePreciseFileIndexReader( const BinaryRow& partition, const std::shared_ptr& file, const std::shared_ptr& read_schema, const std::shared_ptr& predicate, - const FieldMappingBuilder* field_mapping_builder, DeletionVector::Factory dv_factory, - const std::optional>& row_ranges, + DeletionVector::Factory dv_factory, const std::optional>& row_ranges, const std::shared_ptr& path_factory, const std::map& extra_format_options) const { return Status::NotImplemented("This read path does not support file predicate evaluation"); @@ -374,7 +376,9 @@ bool AbstractSplitRead::NeedCompleteRowTrackingFields( } Result> AbstractSplitRead::ApplyPredicateFilterIfNeeded( std::unique_ptr&& reader, const std::shared_ptr& predicate) const { - if (!context_->EnablePredicateFilter() || predicate == nullptr) { + // Precise readers already evaluated the full predicate before materializing selected rows. + if (context_->EnablePreciseFileIndexEvaluate() || !context_->EnablePredicateFilter() || + predicate == nullptr) { return std::move(reader); } return PredicateBatchReader::Create(std::move(reader), predicate, arrow_pool_); diff --git a/src/paimon/core/operation/abstract_split_read.h b/src/paimon/core/operation/abstract_split_read.h index 70ea02c0c..a2feab696 100644 --- a/src/paimon/core/operation/abstract_split_read.h +++ b/src/paimon/core/operation/abstract_split_read.h @@ -89,8 +89,7 @@ class AbstractSplitRead : public SplitRead { virtual Result> CreatePreciseFileIndexReader( const BinaryRow& partition, const std::shared_ptr& file, const std::shared_ptr& read_schema, - const std::shared_ptr& predicate, - const FieldMappingBuilder* field_mapping_builder, DeletionVector::Factory dv_factory, + const std::shared_ptr& predicate, DeletionVector::Factory dv_factory, const std::optional>& row_ranges, const std::shared_ptr& path_factory, const std::map& extra_format_options) const; diff --git a/src/paimon/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index d13cb9199..5fe8f6dc7 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -243,18 +243,22 @@ 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())); + return batch_reader; } else if (auto data_split = std::dynamic_pointer_cast(split)) { if (HasIndexScoreField(raw_read_schema_)) { return Status::Invalid( "Invalid read schema, read _INDEX_SCORE while split cannot cast to IndexedSplit"); } PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr inner_reader, + std::unique_ptr batch_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(batch_reader, + WrapWithBlobViewResolverIfNeeded(data_split, std::move(batch_reader), + /*row_ranges=*/std::nullopt)); + return batch_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..cfc531970 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: (ProjectionBatchReader)->(ConcatBatchReader across splits) +/// ->(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..e34c86e26 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,24 @@ 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( + has_virtual_field_filter_, + PredicateUtils::ContainAnyField(scan_filters->GetPredicate(), virtual_fields)); + 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/file_store_scan.h b/src/paimon/core/operation/file_store_scan.h index df8c6d614..f70c2bb26 100644 --- a/src/paimon/core/operation/file_store_scan.h +++ b/src/paimon/core/operation/file_store_scan.h @@ -173,6 +173,10 @@ class FileStoreScan { return predicates_; } + bool HasNonPartitionFilter() const { + return predicates_ != nullptr || has_virtual_field_filter_; + } + const std::optional& GetRowRangeIndex() const { return row_range_index_; } @@ -358,5 +362,6 @@ class FileStoreScan { std::shared_ptr metrics_; std::string table_path_; bool drop_stats_ = false; + bool has_virtual_field_filter_ = false; }; } // namespace paimon diff --git a/src/paimon/core/operation/internal_read_context.cpp b/src/paimon/core/operation/internal_read_context.cpp index 75f33565f..d2d28cbad 100644 --- a/src/paimon/core/operation/internal_read_context.cpp +++ b/src/paimon/core/operation/internal_read_context.cpp @@ -221,7 +221,7 @@ Result> InternalReadContext::AlignReadFieldWithTab } std::optional InternalReadContext::TryResolveSpecialFieldById( - int32_t field_id, const CoreOptions& core_options) { + int32_t field_id, const TableSchema& table_schema, const CoreOptions& core_options) { if (field_id == SpecialFields::ValueKind().Id()) { return SpecialFields::ValueKind(); } @@ -232,7 +232,8 @@ std::optional InternalReadContext::TryResolveSpecialFieldById( return std::nullopt; } if (field_id == SpecialFields::SequenceNumber().Id()) { - if (core_options.RowTrackingEnabled() || core_options.KeyValueSequenceNumberEnabled()) { + if (core_options.RowTrackingEnabled() || + (!table_schema.PrimaryKeys().empty() && core_options.KeyValueSequenceNumberEnabled())) { return SpecialFields::SequenceNumber(); } return std::nullopt; @@ -247,7 +248,8 @@ std::optional InternalReadContext::TryResolveSpecialFieldById( } std::optional InternalReadContext::TryResolveSpecialFieldByName( - const std::string& name, const CoreOptions& core_options, int32_t output_field_idx) { + const std::string& name, const TableSchema& table_schema, const CoreOptions& core_options, + int32_t output_field_idx) { if (SpecialFields::ParseIndexScoreFieldName(name)) { // These virtual columns have read-local negative IDs, not persistent table IDs. return DataField(-1 - output_field_idx, arrow::field(name, arrow::float32())); @@ -262,7 +264,8 @@ std::optional InternalReadContext::TryResolveSpecialFieldByName( return std::nullopt; } if (name == SpecialFields::SequenceNumber().Name()) { - if (core_options.RowTrackingEnabled() || core_options.KeyValueSequenceNumberEnabled()) { + if (core_options.RowTrackingEnabled() || + (!table_schema.PrimaryKeys().empty() && core_options.KeyValueSequenceNumberEnabled())) { return SpecialFields::SequenceNumber(); } return std::nullopt; @@ -276,6 +279,19 @@ 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) { + // TODO(lisizhuo.lsz): In non-precise reads without row filtering, avoid materializing fields + // used only for predicate pushdown. + 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) { @@ -328,7 +344,7 @@ Result> InternalReadContext::CreateFromCore // Align special-field validation with read_field_ids/read_field_names branches. for (const auto& read_field : read_schema->fields()) { if (auto resolved_special_field = - TryResolveSpecialFieldByName(read_field->name(), core_options, + TryResolveSpecialFieldByName(read_field->name(), *table_schema, core_options, static_cast(read_data_fields.size()))) { read_data_fields.push_back(*resolved_special_field); continue; @@ -354,7 +370,8 @@ Result> InternalReadContext::CreateFromCore } else if (!context->GetReadFieldIds().empty()) { read_data_fields.reserve(context->GetReadFieldIds().size()); for (const auto& field_id : context->GetReadFieldIds()) { - if (auto resolved_special_field = TryResolveSpecialFieldById(field_id, core_options)) { + if (auto resolved_special_field = + TryResolveSpecialFieldById(field_id, *table_schema, core_options)) { read_data_fields.push_back(*resolved_special_field); continue; } @@ -364,8 +381,9 @@ Result> InternalReadContext::CreateFromCore } else if (!context->GetReadFieldNames().empty()) { read_data_fields.reserve(context->GetReadFieldNames().size()); for (const auto& name : context->GetReadFieldNames()) { - if (auto resolved_special_field = TryResolveSpecialFieldByName( - name, core_options, static_cast(read_data_fields.size()))) { + if (auto resolved_special_field = + TryResolveSpecialFieldByName(name, *table_schema, core_options, + static_cast(read_data_fields.size()))) { read_data_fields.push_back(*resolved_special_field); continue; } @@ -391,35 +409,31 @@ Result> InternalReadContext::CreateFromCore "Precise file-index evaluation does not support _INDEX_SCORE; " "project __INDEX_SCORE instead"); } - // validate predicate + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr source_schema, + PredicateValidator::ResolvePredicateSchema( + table_schema, context->GetPredicate(), core_options)); 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)); - } - } 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 +481,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 +502,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 +521,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..aee10144e 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,8 +83,12 @@ 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,13 +182,19 @@ 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 TableSchema& table_schema, const CoreOptions& core_options); static std::optional TryResolveSpecialFieldByName(const std::string& name, + const TableSchema& table_schema, const CoreOptions& core_options, int32_t output_field_idx); static Result> AlignReadFieldWithTableFieldIds( @@ -194,7 +205,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..24f583ba6 100644 --- a/src/paimon/core/operation/internal_read_context_test.cpp +++ b/src/paimon/core/operation/internal_read_context_test.cpp @@ -49,6 +49,65 @@ 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 (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 +547,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 +559,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 +849,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 +867,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..8ce90b148 100644 --- a/src/paimon/core/operation/merge_file_split_read.cpp +++ b/src/paimon/core/operation/merge_file_split_read.cpp @@ -438,7 +438,9 @@ 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_); + return batch_reader; } Result> MergeFileSplitRead::CreateRealtimeReader( @@ -679,14 +681,10 @@ Result> MergeFileSplitRead::GenerateKeyPredicates( } PAIMON_ASSIGN_OR_RAISE(std::vector trimmed_key_fields, table_schema.TrimmedPrimaryKeys()); - std::set non_primary_keys; - for (const auto& field_name : table_schema.FieldNames()) { - auto iter = std::find(trimmed_key_fields.begin(), trimmed_key_fields.end(), field_name); - if (iter == trimmed_key_fields.end()) { - non_primary_keys.insert(field_name); - } - } - return PredicateUtils::ExcludePredicateWithFields(predicate, non_primary_keys); + // Only key predicates are safe before merging. Virtual fields such as _SEQUENCE_NUMBER + // are absent from the table schema and must also be excluded from pre-merge filtering. + return PredicateUtils::CreatePickedFieldFilter( + predicate, ObjectUtils::CreateIdentifierToIndexMap(trimmed_key_fields)); } Result> MergeFileSplitRead::CreateReaderForSection( diff --git a/src/paimon/core/operation/merge_file_split_read.h b/src/paimon/core/operation/merge_file_split_read.h index 45f19a463..ab4da1fd5 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: (ProjectionBatchReader)->(ConcatBatchReader across splits) +/// ->CompleteRowKindBatchReader->(PredicateBatchReader) /// ->ConcatBatchReader across no overlapped /// files->KeyValueProjectionReader/AsyncKeyValueProjectionReader /// ->DropDeleteReader->SortMergeReader->ConcatKeyValueRecordReader->KeyValueDataFileRecordReader diff --git a/src/paimon/core/operation/precise_file_index_read_test.cpp b/src/paimon/core/operation/precise_file_index_read_test.cpp index 3b69758e5..99aceb1b5 100644 --- a/src/paimon/core/operation/precise_file_index_read_test.cpp +++ b/src/paimon/core/operation/precise_file_index_read_test.cpp @@ -907,12 +907,13 @@ TEST_F(PreciseFileIndexReadTest, TestPredicateProviderFiltersExtraFieldsBeforeRo partition, {first, second, unfiltered}, read_schema, provider, dv_factory, std::nullopt, paths, {})); ASSERT_EQ(3, readers.size()); - const std::vector expected{R"([["Emily",0.8,13.1]])", R"([["Tony",0.7,14.1]])", - R"([["Emily",0.8,13.1]])"}; + const std::vector expected{R"([["Emily",0.8]])", R"([["Tony",0.7]])", + R"([["Emily",0.8]])"}; for (size_t i = 0; i < readers.size(); ++i) { ASSERT_OK_AND_ASSIGN(std::shared_ptr result, ReadResultCollector::CollectResult(std::move(readers[i]))); - CheckSearchResult(result, fields, expected[i]); + CheckSearchResult(result, context->GetReadSchemaPlan()->GetOutputSchema()->fields(), + expected[i]); } } } diff --git a/src/paimon/core/operation/raw_file_split_read.cpp b/src/paimon/core/operation/raw_file_split_read.cpp index cf3b6b35e..5b1983b90 100644 --- a/src/paimon/core/operation/raw_file_split_read.cpp +++ b/src/paimon/core/operation/raw_file_split_read.cpp @@ -38,6 +38,7 @@ #include "paimon/core/schema/schema_manager.h" #include "paimon/core/schema/table_schema.h" #include "paimon/core/table/source/data_split_impl.h" +#include "paimon/core/utils/field_mapping.h" #include "paimon/core/utils/file_store_path_factory.h" #include "paimon/memory/memory_pool.h" #include "paimon/reader/file_batch_reader.h" @@ -186,9 +187,7 @@ Result> RawFileSplitRead::CreateReaderWithPredicate arrow_pool_, GetReaderBuildExecutor())); PAIMON_ASSIGN_OR_RAISE( std::unique_ptr batch_reader, - ApplyPredicateFilterIfNeeded( - std::move(concat_batch_reader), - context_->EnablePreciseFileIndexEvaluate() ? nullptr : residual_predicate)); + ApplyPredicateFilterIfNeeded(std::move(concat_batch_reader), residual_predicate)); return std::make_unique(std::move(batch_reader), arrow_pool_); } @@ -240,14 +239,19 @@ Result RawFileSplitRead::Match(const std::shared_ptr& split, Result> RawFileSplitRead::CreatePreciseFileIndexReader( const BinaryRow& partition, const std::shared_ptr& file, const std::shared_ptr& read_schema, const std::shared_ptr& predicate, - const FieldMappingBuilder* field_mapping_builder, DeletionVector::Factory dv_factory, - const std::optional>& row_ranges, + DeletionVector::Factory dv_factory, const std::optional>& row_ranges, const std::shared_ptr& path_factory, const std::map& extra_format_options) const { + // Evaluate against the complete read schema, including scalar fallback dependencies. + // Materialization reads only output fields, without pushing the predicate down a second time. PAIMON_ASSIGN_OR_RAISE( - std::unique_ptr precise_read, - PreciseFileIndexRead::Create(*this, partition, file, read_schema, predicate, - field_mapping_builder, path_factory, extra_format_options)); + std::unique_ptr field_mapping_builder, + FieldMappingBuilder::Create(context_->GetReadSchemaPlan()->GetOutputSchema(), + context_->GetPartitionKeys(), /*predicate=*/nullptr)); + PAIMON_ASSIGN_OR_RAISE(std::unique_ptr precise_read, + PreciseFileIndexRead::Create(*this, partition, file, read_schema, + predicate, field_mapping_builder.get(), + path_factory, extra_format_options)); return precise_read->CreateReader(dv_factory, row_ranges); } diff --git a/src/paimon/core/operation/raw_file_split_read.h b/src/paimon/core/operation/raw_file_split_read.h index 82d87beb1..d2ddbdadf 100644 --- a/src/paimon/core/operation/raw_file_split_read.h +++ b/src/paimon/core/operation/raw_file_split_read.h @@ -52,8 +52,9 @@ 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: (TopKBatchReader) -> (ConcatBatchReader across splits) -/// -> CompleteRowKindBatchReader -> (PredicateBatchReader) -> ConcatBatchReader across files +/// Readers Overview: (ProjectionBatchReader) -> (TopKBatchReader) +/// -> (ConcatBatchReader across splits) -> CompleteRowKindBatchReader -> (PredicateBatchReader) +/// -> ConcatBatchReader across files /// -> (CompleteIndexScoreFileBatchReader) -> FieldMappingReader /// -> (ApplyDeletionVectorBatchReader) -> (ApplyBitmapIndexBatchReader) /// -> (CompleteRowTrackingFieldsBatchReader) -> (ShreddingFileReader) @@ -112,8 +113,7 @@ class RawFileSplitRead : public AbstractSplitRead { Result> CreatePreciseFileIndexReader( const BinaryRow& partition, const std::shared_ptr& file, const std::shared_ptr& read_schema, - const std::shared_ptr& predicate, - const FieldMappingBuilder* field_mapping_builder, DeletionVector::Factory dv_factory, + const std::shared_ptr& predicate, DeletionVector::Factory dv_factory, const std::optional>& row_ranges, const std::shared_ptr& path_factory, const std::map& extra_format_options) const override; diff --git a/src/paimon/core/realtime/precise_realtime_index_read.cpp b/src/paimon/core/realtime/precise_realtime_index_read.cpp index c131b7d84..415ad6166 100644 --- a/src/paimon/core/realtime/precise_realtime_index_read.cpp +++ b/src/paimon/core/realtime/precise_realtime_index_read.cpp @@ -186,7 +186,7 @@ class RealtimeSourceRead { } else if (context_->GetFullTextSearch()) { root_search_field_name = context_->GetFullTextSearch()->field_name; } - auto output_schema = context_->GetReadSchema(); + auto output_schema = context_->GetReadSchemaPlan()->GetOutputSchema(); if (root_search_field_name) { std::string score_name = SpecialFields::IndexScoreFieldName(root_search_field_name.value()); @@ -211,12 +211,12 @@ class RealtimeSourceRead { } } arrow::FieldVector fields; - for (const auto& field : context_->GetReadSchema()->fields()) { + for (const auto& field : output_schema->fields()) { if (!SpecialFields::ParseIndexScoreFieldName(field->name())) { fields.push_back(field); } } - if (context_->GetReadSchema()->GetFieldIndex(OffsetField()->name()) < 0) { + if (output_schema->GetFieldIndex(OffsetField()->name()) < 0) { fields.push_back(OffsetField()); } PAIMON_ASSIGN_OR_RAISE(std::unique_ptr reader, diff --git a/src/paimon/core/realtime/precise_realtime_index_read_test.cpp b/src/paimon/core/realtime/precise_realtime_index_read_test.cpp index 0e7130dc3..e31f9f61f 100644 --- a/src/paimon/core/realtime/precise_realtime_index_read_test.cpp +++ b/src/paimon/core/realtime/precise_realtime_index_read_test.cpp @@ -44,6 +44,7 @@ #include "paimon/core/realtime/realtime_schema_layout.h" #include "paimon/core/schema/table_schema.h" #include "paimon/core/table/source/append_only_table_read.h" +#include "paimon/core/table/source/projection_batch_reader.h" #include "paimon/core/table/source/realtime_split.h" #include "paimon/core/table/source/topk_batch_reader.h" #include "paimon/factories/factory_creator.h" @@ -179,6 +180,7 @@ class PreciseRealtimeIndexReadTest : public testing::Test { PreciseRealtimeIndexRead::CreateReader( context, mode, query_store_ ? query_store_ : store_, view, range)); reader = TopKBatchReader::ApplyTopkReaderIfNeeded(std::move(reader), *context); + reader = ProjectionBatchReader::ApplyOutputProjectionIfNeeded(std::move(reader), *context); return ReadResultCollector::CollectResult(std::move(reader)); } diff --git a/src/paimon/core/table/file_store_table.cpp b/src/paimon/core/table/file_store_table.cpp index 496d207f8..3fb7d746d 100644 --- a/src/paimon/core/table/file_store_table.cpp +++ b/src/paimon/core/table/file_store_table.cpp @@ -90,6 +90,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 +506,12 @@ Result> FileStoreTable::NewScan( auto arrow_schema = DataField::ConvertDataFieldsToArrowSchema(table_schema->Fields()); if (context->GetScanFilters() && context->GetScanFilters()->GetPredicate()) { - PAIMON_RETURN_NOT_OK(PredicateValidator::ValidatePredicateWithSchema( - *arrow_schema, context->GetScanFilters()->GetPredicate(), - /*validate_field_idx=*/false)); + const auto& predicate = context->GetScanFilters()->GetPredicate(); + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr validation_schema, + PredicateValidator::ResolvePredicateSchema(table_schema, predicate, core_options)); + PAIMON_RETURN_NOT_OK( + PredicateValidator::ValidatePredicateWithSchema(*validation_schema, 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..b39e7fe23 100644 --- a/src/paimon/core/table/format/format_table_read.cpp +++ b/src/paimon/core/table/format/format_table_read.cpp @@ -46,11 +46,14 @@ #include "paimon/core/table/format/format_data_split.h" #include "paimon/core/table/format/format_path_validation.h" #include "paimon/core/table/format/lazy_concat_batch_reader.h" +#include "paimon/core/table/source/projection_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 +239,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 +396,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(PredicateValidator::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 +417,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 +438,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 +599,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..a77a83e62 100644 --- a/src/paimon/core/table/source/append_only_table_read.cpp +++ b/src/paimon/core/table/source/append_only_table_read.cpp @@ -51,6 +51,7 @@ #include "paimon/core/schema/schema_manager.h" #include "paimon/core/table/source/append_count_reader.h" #include "paimon/core/table/source/data_split_impl.h" +#include "paimon/core/table/source/projection_batch_reader.h" #include "paimon/core/table/source/realtime_split.h" #include "paimon/core/table/source/table_read_utils.h" #include "paimon/core/table/source/topk_batch_reader.h" @@ -165,7 +166,8 @@ Result> AppendOnlyTableRead::CreateReader( return owned_read->CreateRealtimeReader(split, view); }, *context_)); - return TopKBatchReader::ApplyTopkReaderIfNeeded(std::move(reader), *context_); + reader = TopKBatchReader::ApplyTopkReaderIfNeeded(std::move(reader), *context_); + return ProjectionBatchReader::ApplyOutputProjectionIfNeeded(std::move(reader), *context_); } Result> AppendOnlyTableRead::CreateRealtimeReader( 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/data_table_batch_scan.cpp b/src/paimon/core/table/source/data_table_batch_scan.cpp index e06e665aa..fc4fa032b 100644 --- a/src/paimon/core/table/source/data_table_batch_scan.cpp +++ b/src/paimon/core/table/source/data_table_batch_scan.cpp @@ -81,8 +81,9 @@ bool DataTableBatchScan::CanPushDownLimit() const { if (push_down_limit_ == std::nullopt) { return false; } - if (snapshot_reader_->GetNonPartitionPredicate()) { - // a non-partition filter runs while reading, so the metadata count is an upper bound + if (snapshot_reader_->HasNonPartitionFilter()) { + // Non-partition filters, including virtual fields omitted from statistics pruning, + // can drop rows while reading, so the metadata count is only an upper bound. return false; } if (snapshot_reader_->GetRowRangeIndex()) { 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..c16990dcd 100644 --- a/src/paimon/core/table/source/full_text_search_builder.cpp +++ b/src/paimon/core/table/source/full_text_search_builder.cpp @@ -20,6 +20,7 @@ #include "paimon/table/source/full_text_search_builder.h" #include +#include #include #include "fmt/format.h" @@ -224,6 +225,13 @@ Result ResolveFilters(const std::vector field_names; + if (filter) { + PAIMON_RETURN_NOT_OK(PredicateUtils::GetAllNames(filter, &field_names)); + } + PAIMON_RETURN_NOT_OK( + PredicateValidator::ValidatePredicateFieldNames(field_names, /*allowed_system_fields=*/{})); + std::map partition_key_to_idx = ObjectUtils::CreateIdentifierToIndexMap(partition_keys); std::vector> partition_conjuncts; @@ -253,8 +261,7 @@ Result ResolveFilters(const std::vector> KeyValueTableRead::CreateReader( return owned_read->CreateRealtimeReader(split, view); }, *context_)); - return TopKBatchReader::ApplyTopkReaderIfNeeded(std::move(reader), *context_); + reader = TopKBatchReader::ApplyTopkReaderIfNeeded(std::move(reader), *context_); + return ProjectionBatchReader::ApplyOutputProjectionIfNeeded(std::move(reader), *context_); } Result> KeyValueTableRead::CreateRealtimeReader( diff --git a/src/paimon/core/table/source/projection_batch_reader.cpp b/src/paimon/core/table/source/projection_batch_reader.cpp new file mode 100644 index 000000000..66f52c1ad --- /dev/null +++ b/src/paimon/core/table/source/projection_batch_reader.cpp @@ -0,0 +1,98 @@ +/* + * 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/core/table/source/projection_batch_reader.h" + +#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/status_utils.h" +#include "paimon/common/utils/checked_cast.h" +#include "paimon/common/utils/scope_guard.h" +#include "paimon/core/operation/internal_read_context.h" + +namespace paimon { + +std::unique_ptr ProjectionBatchReader::ApplyOutputProjectionIfNeeded( + std::unique_ptr reader, const InternalReadContext& context) { + const auto& plan = context.GetReadSchemaPlan(); + // Root searches can add an implicit score even when the plan has no extra predicate fields. + if (!plan->NeedsProjection() && !context.HasVectorOrFullTextSearch()) { + return reader; + } + return std::make_unique( + std::move(reader), plan->GetOutputSchema()->field_names(), context.GetArrowMemoryPool()); +} + +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 array, + arrow::ImportArray(c_array.get(), c_schema.get())); + if (array->type_id() != arrow::Type::STRUCT) { + return Status::Invalid("projection batch reader requires a struct array"); + } + 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)); + } + } + // 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(), c_schema.get())); + release.Release(); + return Status::OK(); +} +} // namespace paimon diff --git a/src/paimon/core/table/source/projection_batch_reader.h b/src/paimon/core/table/source/projection_batch_reader.h new file mode 100644 index 000000000..922176206 --- /dev/null +++ b/src/paimon/core/table/source/projection_batch_reader.h @@ -0,0 +1,66 @@ +/* + * 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 { +class InternalReadContext; + +/// Projects the explicitly requested fields. +class ProjectionBatchReader : public BatchReader { + public: + static std::unique_ptr ApplyOutputProjectionIfNeeded( + std::unique_ptr reader, const InternalReadContext& context); + + 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/core/table/source/projection_batch_reader_test.cpp b/src/paimon/core/table/source/projection_batch_reader_test.cpp new file mode 100644 index 000000000..c334d420b --- /dev/null +++ b/src/paimon/core/table/source/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/core/table/source/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/core/table/source/query_auth_table_read.cpp b/src/paimon/core/table/source/query_auth_table_read.cpp index b004ddaab..0cbb51713 100644 --- a/src/paimon/core/table/source/query_auth_table_read.cpp +++ b/src/paimon/core/table/source/query_auth_table_read.cpp @@ -26,6 +26,7 @@ #include "arrow/c/bridge.h" #include "arrow/compute/cast.h" #include "fmt/format.h" +#include "paimon/common/predicate/predicate_validator.h" #include "paimon/common/reader/concat_batch_reader.h" #include "paimon/common/reader/predicate_batch_reader.h" #include "paimon/common/utils/arrow/arrow_utils.h" @@ -36,8 +37,10 @@ #include "paimon/common/utils/scope_guard.h" #include "paimon/core/casting/casting_utils.h" #include "paimon/core/catalog/catalog_utils.h" +#include "paimon/core/table/source/projection_batch_reader.h" #include "paimon/core/table/source/query_auth_split.h" #include "paimon/core/utils/branch_manager.h" +#include "paimon/core/utils/read_schema_plan.h" #include "paimon/defs.h" #include "paimon/predicate/predicate.h" #include "paimon/predicate/predicate_builder.h" @@ -105,11 +108,10 @@ class RowFilterBoundaryReader : public BatchReader { QueryAuthBatchReader::QueryAuthBatchReader( std::unique_ptr 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 +190,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 +277,13 @@ Result> QueryAuthTableRead::Create( name)); } } + // TODO(lisizhuo.lsz): Support authorized reads of projected system fields as Java does. + PAIMON_RETURN_NOT_OK( + PredicateValidator::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 +441,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 +484,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..b6da2510f 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,7 @@ #include "arrow/c/abi.h" #include "arrow/c/bridge.h" #include "fmt/format.h" +#include "paimon/common/predicate/predicate_validator.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 +150,13 @@ Result> QueryAuthTableScan::Create( columns.push_back(name); } } + if (scan_filter && scan_filter->GetPredicate()) { + PAIMON_RETURN_NOT_OK(PredicateValidator::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/snapshot/snapshot_reader.h b/src/paimon/core/table/source/snapshot/snapshot_reader.h index 6faadb9fe..2e7bc42b9 100644 --- a/src/paimon/core/table/source/snapshot/snapshot_reader.h +++ b/src/paimon/core/table/source/snapshot/snapshot_reader.h @@ -109,6 +109,10 @@ class SnapshotReader { return scan_->GetNonPartitionPredicate(); } + bool HasNonPartitionFilter() const { + return scan_->HasNonPartitionFilter(); + } + const std::optional& GetRowRangeIndex() const { return scan_->GetRowRangeIndex(); } diff --git a/src/paimon/core/table/source/table_read_test.cpp b/src/paimon/core/table/source/table_read_test.cpp index 46c5b844a..97ab12b8d 100644 --- a/src/paimon/core/table/source/table_read_test.cpp +++ b/src/paimon/core/table/source/table_read_test.cpp @@ -48,6 +48,7 @@ #include "paimon/core/table/source/append_only_table_read.h" #include "paimon/core/table/source/data_split_impl.h" #include "paimon/core/table/source/key_value_table_read.h" +#include "paimon/core/table/source/projection_batch_reader.h" #include "paimon/core/table/source/topk_batch_reader.h" #include "paimon/defs.h" #include "paimon/fs/local/local_file_system.h" @@ -100,18 +101,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 +121,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 +260,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) { @@ -297,10 +349,12 @@ TEST(TableReadTest, TestRootTopKCombinesDifferentFieldNullability) { if (project_score) { fields.push_back(arrow::field(score_name, arrow::float32())); } - auto reader = std::make_unique( + std::unique_ptr reader = std::make_unique( std::make_unique(std::move(readers), pool), score_name, TopKBatchReader::ScoreOrder::ASCENDING, /*limit=*/3, /*batch_size=*/1, arrow::schema(fields), pool); + reader = std::make_unique( + std::move(reader), arrow::schema(fields)->field_names(), pool); ASSERT_OK_AND_ASSIGN(std::shared_ptr actual, ReadResultCollector::CollectResult(std::move(reader))); ASSERT_NE(nullptr, actual); diff --git a/src/paimon/core/table/source/topk_batch_reader.cpp b/src/paimon/core/table/source/topk_batch_reader.cpp index 8bfe9fb72..4c22c20d6 100644 --- a/src/paimon/core/table/source/topk_batch_reader.cpp +++ b/src/paimon/core/table/source/topk_batch_reader.cpp @@ -71,8 +71,7 @@ TopKBatchReader::TopKBatchReader(std::unique_ptr reader, score_order_(score_order), limit_(limit), batch_size_(batch_size), - read_type_(arrow::struct_(read_schema->fields())), - remove_score_(read_schema->GetFieldIndex(score_field_name) < 0) {} + read_type_(arrow::struct_(read_schema->fields())) {} Result TopKBatchReader::NextBatch() { if (!initialized_) { @@ -185,10 +184,6 @@ Status TopKBatchReader::ReadTopK() { std::sort(candidates.begin(), candidates.end(), better); PAIMON_RETURN_NOT_OK(CompactCandidates(&candidates)); output_ = checked_pointer_cast(candidates.front().values); - if (remove_score_) { - PAIMON_ASSIGN_OR_RAISE(output_, - ArrowUtils::RemoveFieldFromStructArray(output_, score_name_)); - } return Status::OK(); } diff --git a/src/paimon/core/table/source/topk_batch_reader.h b/src/paimon/core/table/source/topk_batch_reader.h index 8087883fb..232552d8d 100644 --- a/src/paimon/core/table/source/topk_batch_reader.h +++ b/src/paimon/core/table/source/topk_batch_reader.h @@ -39,6 +39,7 @@ namespace paimon { class InternalReadContext; /// Selects and sorts the global TopK from all rows produced by the input reader. +/// Keeps input columns, including scores, for the final output projection. class TopKBatchReader : public BatchReader { public: static std::unique_ptr ApplyTopkReaderIfNeeded(std::unique_ptr reader, @@ -76,7 +77,6 @@ class TopKBatchReader : public BatchReader { int32_t limit_; int32_t batch_size_; std::shared_ptr read_type_; - bool remove_score_; bool initialized_ = false; std::shared_ptr output_; 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..38f82ce01 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)); } } @@ -4248,6 +4257,83 @@ TEST_P(DataEvolutionTableTest, TestLimitPushDownDisabledByNonPartitionFilter) { ASSERT_EQ(values, (std::vector{100, 101, 102, 103})); } +TEST_P(DataEvolutionTableTest, TestLimitPushDownDisabledByRowTrackingFilter) { + for (bool data_evolution_enabled : {false, true}) { + auto table_dir = UniqueTestDirectory::Create("local"); + std::map options = { + {Options::FILE_FORMAT, FileFormat()}, + {Options::BUCKET, "-1"}, + {Options::ROW_TRACKING_ENABLED, "true"}, + {Options::DATA_EVOLUTION_ENABLED, data_evolution_enabled ? "true" : "false"}, + {Options::SOURCE_SPLIT_TARGET_SIZE, "1"}}; + ASSERT_OK_AND_ASSIGN( + std::unique_ptr helper, + TestHelper::Create(table_dir->Str(), arrow::schema(fields_), /*partition_keys=*/{"f1"}, + /*primary_keys=*/{}, options, /*is_streaming_mode=*/false)); + helper.reset(); + const std::string table_path = PathUtil::JoinPath(table_dir->Str(), "foo.db/bar"); + // Separate commits produce two files with distinct row ids and sequence numbers. + for (int32_t value : {0, 1}) { + auto array = + arrow::ipc::internal::json::ArrayFromJSON( + arrow::struct_(fields_), fmt::format(R"([[{}, "p0", "value"]])", value)) + .ValueOrDie(); + ASSERT_OK_AND_ASSIGN(std::vector> commit_msgs, + WriteArray(table_path, /*partition=*/{{"f1", "p0"}}, + arrow::schema(fields_)->field_names(), array)); + ASSERT_OK(Commit(table_path, commit_msgs)); + } + const std::vector read_fields = {"f0", "_ROW_ID", "_SEQUENCE_NUMBER"}; + ASSERT_OK_AND_ASSIGN(LimitScanResult all, + ScanAndReadWithLimit(table_path, read_fields, /*limit=*/100)); + ASSERT_EQ(all.splits.size(), 2); + ASSERT_TRUE(all.rows); + ASSERT_EQ(all.rows->length(), 2); + + // Discover which split a limit of one keeps, without relying on manifest file order. + ASSERT_OK_AND_ASSIGN(LimitScanResult first, + ScanAndReadWithLimit(table_path, read_fields, /*limit=*/1)); + ASSERT_EQ(first.splits.size(), 1); + ASSERT_TRUE(first.rows); + ASSERT_EQ(first.rows->length(), 1); + ASSERT_OK_AND_ASSIGN(std::vector first_values, CollectF0Values(first.rows)); + ASSERT_EQ(first_values.size(), 1); + ASSERT_OK_AND_ASSIGN(std::vector expected_values, CollectF0Values(all.rows)); + auto first_value_iter = + std::find(expected_values.begin(), expected_values.end(), first_values.front()); + ASSERT_NE(first_value_iter, expected_values.end()); + expected_values.erase(first_value_iter); + auto first_row = checked_pointer_cast(first.rows->chunk(0)); + + for (const std::string field_name : {"_ROW_ID", "_SEQUENCE_NUMBER"}) { + auto first_column = + checked_pointer_cast(first_row->GetFieldByName(field_name)); + ASSERT_EQ(first_column->null_count(), 0); + auto system_predicate = PredicateBuilder::NotEqual( + /*field_index=*/77, field_name, FieldType::BIGINT, Literal(first_column->Value(0))); + auto impossible = + PredicateBuilder::LessThan(/*field_index=*/0, "f0", FieldType::INT, Literal(0)); + auto partition = PredicateBuilder::Equal(/*field_index=*/1, "f1", FieldType::STRING, + Literal(FieldType::STRING, "p0", 2)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr disjunction, + PredicateBuilder::Or({system_predicate, impossible})); + ASSERT_OK_AND_ASSIGN(std::shared_ptr conjunction, + PredicateBuilder::And({partition, system_predicate})); + for (const auto& predicate : {system_predicate, disjunction, conjunction}) { + // Only the other split matches. Counting the first split's unfiltered row + // would discard that match before the read can apply the virtual predicate. + ASSERT_OK_AND_ASSIGN( + LimitScanResult limited, + ScanAndReadWithLimit(table_path, {"f0"}, /*limit=*/1, predicate, + /*row_ranges=*/{}, /*enable_predicate_filter=*/true)); + ASSERT_EQ(limited.splits.size(), all.splits.size()); + ASSERT_OK_AND_ASSIGN(std::vector values, CollectF0Values(limited.rows)); + ASSERT_EQ(values, expected_values); + } + } + } +} + TEST_P(DataEvolutionTableTest, TestLimitPushDownKeptByPartitionFilter) { std::vector partition_keys = {"f1"}; CreateTable(partition_keys); diff --git a/test/inte/read_inte_test.cpp b/test/inte/read_inte_test.cpp index cdb354ccf..93a2d16a8 100644 --- a/test/inte/read_inte_test.cpp +++ b/test/inte/read_inte_test.cpp @@ -633,6 +633,241 @@ TEST_P(ReadInteTest, TestReadOnlyPartitionField) { ASSERT_TRUE(result_array->Equals(expected_array)) << result_array->ToString(); } +TEST(PredicateReadInteTest, TestSequenceNumberFilterAfterPrimaryKeyMerge) { + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + arrow::field("val", arrow::int32())}; + std::map options = { + {Options::FILE_SYSTEM, "local"}, + {Options::FILE_FORMAT, "parquet"}, + {Options::BUCKET, "1"}, + {Options::WRITE_ONLY, "true"}, + {Options::KEY_VALUE_SEQUENCE_NUMBER_ENABLED, "true"}}; + ASSERT_OK_AND_ASSIGN(std::unique_ptr helper, + TestHelper::Create(dir->Str(), arrow::schema(fields), + /*partition_keys=*/{}, /*primary_keys=*/{"id"}, options, + /*is_streaming_mode=*/true)); + for (int64_t version : {1, 2}) { + ASSERT_OK_AND_ASSIGN(std::unique_ptr batch, + TestHelper::MakeRecordBatch(arrow::struct_(fields), + fmt::format("[[1, {}]]", version * 10), + /*partition_map=*/{}, /*bucket=*/0, {})); + ASSERT_OK(helper->WriteAndCommit(std::move(batch), version, + /*expected_commit_messages=*/std::nullopt)); + } + std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + ASSERT_OK_AND_ASSIGN(std::unique_ptr baseline_context, + ScanContextBuilder(table_path).SetOptions(options).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_EQ(baseline->Splits().size(), 1); + auto split = std::dynamic_pointer_cast(baseline->Splits()[0]); + ASSERT_TRUE(split); + ASSERT_FALSE(split->IsStreaming()); + ASSERT_EQ(split->DataFiles().size(), 2); + std::vector sequences; + for (const auto& file : split->DataFiles()) { + ASSERT_EQ(file->row_count, 1); + sequences.push_back(file->max_sequence_number); + } + std::sort(sequences.begin(), sequences.end()); + ASSERT_LT(sequences[0], sequences[1]); + for (int64_t sequence_number : sequences) { + auto sequence = PredicateBuilder::Equal(2, "_SEQUENCE_NUMBER", FieldType::BIGINT, + Literal(sequence_number)); + auto key = PredicateBuilder::Equal(0, "id", FieldType::INT, Literal(1)); + auto absent_key = PredicateBuilder::Equal(0, "id", FieldType::INT, Literal(999)); + ASSERT_OK_AND_ASSIGN(std::shared_ptr conjunction, + PredicateBuilder::And({key, sequence})); + ASSERT_OK_AND_ASSIGN(std::shared_ptr disjunction, + PredicateBuilder::Or({absent_key, sequence})); + for (const auto& predicate : {sequence, conjunction, disjunction}) { + ASSERT_OK_AND_ASSIGN(std::unique_ptr scan_context, + ScanContextBuilder(table_path) + .SetOptions(options) + .SetPredicate(predicate) + .Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr scan, + TableScan::Create(std::move(scan_context))); + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, scan->CreatePlan()); + ASSERT_EQ(plan->Splits().size(), 1); + ASSERT_OK_AND_ASSIGN(int64_t file_count, CountDataFiles(plan->Splits())); + // Both versions must participate in the merge, including the nonmatching version. + ASSERT_EQ(file_count, 2); + ASSERT_OK_AND_ASSIGN(std::unique_ptr read_context, + ReadContextBuilder(table_path) + .SetOptions(options) + .SetReadFieldNames({"val"}) + .SetPredicate(predicate) + .EnablePredicateFilter(true) + .Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr read, + TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + read->CreateReader(plan->Splits())); + ASSERT_OK_AND_ASSIGN(std::shared_ptr result, + ReadResultCollector::CollectResult(std::move(reader))); + if (sequence_number == sequences.front()) { + ASSERT_TRUE(!result || result->length() == 0) << (result ? result->ToString() : ""); + } else { + ASSERT_TRUE(result); + auto array = SingleStructChunk(result); + ASSERT_EQ(StructFieldNames(array), + (std::vector{"_VALUE_KIND", "val"})); + AssertStructArrayEqualsJson(array, "[[0, 20]]"); + } + } + } +} + +TEST(PredicateReadInteTest, TestAppendSequenceNumberPredicateRequiresRowTracking) { + for (bool row_tracking : {false, true}) { + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + arrow::FieldVector fields = {arrow::field("val", arrow::int32())}; + std::map options = { + {Options::FILE_SYSTEM, "local"}, + {Options::FILE_FORMAT, "parquet"}, + {Options::BUCKET, "-1"}, + {Options::ROW_TRACKING_ENABLED, row_tracking ? "true" : "false"}}; + ASSERT_OK_AND_ASSIGN(std::unique_ptr helper, + TestHelper::Create(dir->Str(), arrow::schema(fields), + /*partition_keys=*/{}, /*primary_keys=*/{}, options, + /*is_streaming_mode=*/false)); + ASSERT_OK_AND_ASSIGN(std::unique_ptr batch, + TestHelper::MakeRecordBatch(arrow::struct_(fields), "[[10]]", + /*partition_map=*/{}, /*bucket=*/0, {})); + ASSERT_OK(helper->WriteAndCommit(std::move(batch), /*commit_identifier=*/0, + /*expected_commit_messages=*/std::nullopt)); + std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + for (bool key_value_sequence : {false, true}) { + options[Options::KEY_VALUE_SEQUENCE_NUMBER_ENABLED] = + key_value_sequence ? "true" : "false"; + auto predicate = PredicateBuilder::IsNotNull(1, "_SEQUENCE_NUMBER", FieldType::BIGINT); + ASSERT_OK_AND_ASSIGN(std::unique_ptr scan_context, + ScanContextBuilder(table_path) + .SetOptions(options) + .SetPredicate(predicate) + .Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr read_context, + ReadContextBuilder(table_path) + .SetOptions(options) + .SetReadFieldNames({"val"}) + .SetPredicate(predicate) + .EnablePredicateFilter(true) + .Finish()); + if (!row_tracking) { + ASSERT_NOK_WITH_MSG(TableScan::Create(std::move(scan_context)), + "Predicate on system field '_SEQUENCE_NUMBER'"); + ASSERT_NOK_WITH_MSG(TableRead::Create(std::move(read_context)), + "Predicate on system field '_SEQUENCE_NUMBER'"); + continue; + } + ASSERT_OK_AND_ASSIGN(std::unique_ptr scan, + TableScan::Create(std::move(scan_context))); + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, scan->CreatePlan()); + ASSERT_EQ(plan->Splits().size(), 1); + ASSERT_OK_AND_ASSIGN(std::unique_ptr read, + TableRead::Create(std::move(read_context))); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + read->CreateReader(plan->Splits())); + ASSERT_OK_AND_ASSIGN(std::shared_ptr result, + ReadResultCollector::CollectResult(std::move(reader))); + ASSERT_TRUE(result); + auto array = SingleStructChunk(result); + ASSERT_EQ(StructFieldNames(array), (std::vector{"_VALUE_KIND", "val"})); + AssertStructArrayEqualsJson(array, "[[0, 10]]"); + } + } +} + +TEST(PredicateReadInteTest, TestSequenceNumberProjectionAvailability) { + for (bool has_primary_key : {false, true}) { + for (bool row_tracking : {false, true}) { + if (has_primary_key && row_tracking) { + continue; // Row tracking is only supported for append tables. + } + auto dir = UniqueTestDirectory::Create(); + ASSERT_TRUE(dir); + arrow::FieldVector fields = {arrow::field("id", arrow::int32()), + arrow::field("val", arrow::int32())}; + std::vector primary_keys; + if (has_primary_key) { + primary_keys.push_back("id"); + } + std::map options = { + {Options::FILE_SYSTEM, "local"}, + {Options::FILE_FORMAT, "parquet"}, + {Options::BUCKET, has_primary_key ? "1" : "-1"}, + {Options::WRITE_ONLY, "true"}, + {Options::ROW_TRACKING_ENABLED, row_tracking ? "true" : "false"}}; + ASSERT_OK_AND_ASSIGN( + std::unique_ptr helper, + TestHelper::Create(dir->Str(), arrow::schema(fields), /*partition_keys=*/{}, + primary_keys, options, /*is_streaming_mode=*/false)); + ASSERT_OK_AND_ASSIGN( + std::unique_ptr batch, + TestHelper::MakeRecordBatch(arrow::struct_(fields), "[[1, 10]]", + /*partition_map=*/{}, /*bucket=*/0, {})); + ASSERT_OK(helper->WriteAndCommit(std::move(batch), /*commit_identifier=*/0, + /*expected_commit_messages=*/std::nullopt)); + std::string table_path = PathUtil::JoinPath(dir->Str(), "foo.db/bar"); + ASSERT_OK_AND_ASSIGN(std::unique_ptr scan_context, + ScanContextBuilder(table_path).SetOptions(options).Finish()); + ASSERT_OK_AND_ASSIGN(std::unique_ptr scan, + TableScan::Create(std::move(scan_context))); + ASSERT_OK_AND_ASSIGN(std::shared_ptr plan, scan->CreatePlan()); + ASSERT_EQ(plan->Splits().size(), 1); + auto split = std::dynamic_pointer_cast(plan->Splits()[0]); + ASSERT_TRUE(split); + ASSERT_EQ(split->DataFiles().size(), 1); + int64_t expected_sequence = split->DataFiles()[0]->max_sequence_number; + for (bool key_value_sequence : {false, true}) { + options[Options::KEY_VALUE_SEQUENCE_NUMBER_ENABLED] = + key_value_sequence ? "true" : "false"; + for (const std::string projection : {"names", "ids", "schema"}) { + SCOPED_TRACE( + fmt::format("pk={}, row_tracking={}, kv_sequence={}, projection={}", + has_primary_key, row_tracking, key_value_sequence, projection)); + ReadContextBuilder builder(table_path); + builder.SetOptions(options); + if (projection == "names") { + builder.SetReadFieldNames({"val", "_SEQUENCE_NUMBER"}); + } else if (projection == "ids") { + builder.SetReadFieldIds({1, SpecialFields::SequenceNumber().Id()}); + } else { + auto schema = arrow::schema( + {fields[1], SpecialFields::SequenceNumber().ArrowField()}); + auto c_schema = std::make_unique(); + ASSERT_TRUE(arrow::ExportSchema(*schema, c_schema.get()).ok()); + builder.SetReadSchema(std::move(c_schema)); + } + ASSERT_OK_AND_ASSIGN(std::unique_ptr context, builder.Finish()); + if (!row_tracking && !(has_primary_key && key_value_sequence)) { + ASSERT_NOK_WITH_MSG(TableRead::Create(std::move(context)), + "not exist in table schema"); + continue; + } + ASSERT_OK_AND_ASSIGN(std::unique_ptr read, + TableRead::Create(std::move(context))); + ASSERT_OK_AND_ASSIGN(std::unique_ptr reader, + read->CreateReader(plan->Splits())); + ASSERT_OK_AND_ASSIGN(std::shared_ptr result, + ReadResultCollector::CollectResult(std::move(reader))); + ASSERT_TRUE(result); + auto array = SingleStructChunk(result); + ASSERT_EQ(StructFieldNames(array), + (std::vector{"_VALUE_KIND", "val", "_SEQUENCE_NUMBER"})); + AssertStructArrayEqualsJson(array, + fmt::format("[[0, 10, {}]]", expected_sequence)); + } + } + } + } +} + TEST(SystemTableReadInteTest, TestReadOptionsSystemTable) { std::map options = {{Options::FILE_SYSTEM, "local"}, {Options::FILE_FORMAT, "orc"}, @@ -2309,6 +2544,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 +3981,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);