You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@paimon.apache.org by "ChaomingZhangCN (via GitHub)" <gi...@apache.org> on 2026/08/13 03:43:12 UTC

[PR] feat(parquet): support vector type storage [paimon-cpp]

ChaomingZhangCN opened a new pull request, #198:
URL: https://github.com/apache/paimon-cpp/pull/198

   ### Purpose
   
   Linked issue: [#186](https://github.com/apache/paimon-cpp/issues/186) (tracks the first phase of VECTOR support; this PR does not close the umbrella issue)
   
   Related design: [PIP-40: Introduce a new Vector data type](https://cwiki.apache.org/confluence/spaces/PAIMON/pages/399279132/PIP-40+Introduce+a+new+Vector+data+type)
   
   This PR implements the first phase of VECTOR<T, N> support in Paimon C++. It introduces the logical type and schema representation, maps it to Arrow FixedSizeList<T, N>, and provides end-to-end Parquet reads and writes while keeping the physical Parquet representation interoperable with standard readers.
   
   The main changes are:
   - Add FieldType::VECTOR and support the SQL-style representation VECTOR<T, N>.
   - Add JSON schema serialization and parsing, for example:
   
     ```json
     {
       "type": "VECTOR",
       "element": "FLOAT",
       "length": 3
     }
     ```
   - Support BOOLEAN, TINYINT, SMALLINT, INT, BIGINT, FLOAT, and DOUBLE element types.
   - Allow a VECTOR value to be null, but reject null elements inside a non-null VECTOR.
   - Validate that the vector length is positive and that every value matches the dimension declared by the schema.
   - Support VECTOR values nested in STRUCT, LIST, and MAP using the default MAP layout.
   - Preserve nested field IDs and collect nested null-count statistics for VECTOR columns.
   - Reject VECTOR columns in primary, partition, and bucket keys.
   - Restrict VECTOR data files to Parquet in this phase.
   - Reject VECTOR values inside a shared-shredding MAP until the two features can be integrated safely.
   
   #### Logical and physical representation
   
   ```mermaid
   flowchart LR
       subgraph WritePath["Write path"]
           W1["Paimon schema VECTOR&lt;T, N&gt;"] --> W2["Arrow logical array FixedSizeList&lt;T, N&gt;"]
           W2 -->|"validate dimension and nulls"| W3["Parquet write array List&lt;T&gt;"]
       end
   
       subgraph Storage["Physical storage"]
           P[("Parquet data file standard LIST encoding")]
       end
   
       subgraph ReadPath["Read path"]
           R1["Parquet reader List&lt;T&gt;"] -->|"validate T and N"| R2["Arrow result FixedSizeList&lt;T, N&gt;"]
       end
   
       W3 --> P --> R1
       E[("Third-party Parquet file ordinary LIST column")] --> R1
   ```
   
   VECTOR has a fixed-size logical representation in Paimon and Arrow, but it is written as a standard Parquet LIST. On read, the converter validates the element type, row length, and nullability before restoring the Arrow FixedSizeList. This also allows a compatible LIST column written by another Parquet implementation to be read as VECTOR when the Paimon schema declares VECTOR<T, N>.
   
   #### Scope of this phase
   
   ```mermaid
   flowchart TB
       V["VECTOR&lt;T, N&gt; phase 1"]
   
       V --> S["Schema and type system"]
       S --> S1["SQL and JSON representation"]
       S --> S2["Arrow FixedSizeList mapping"]
       S --> S3["Dimension and null validation"]
   
       V --> IO["Parquet I/O"]
       IO --> IO1["FixedSizeList → LIST writes"]
       IO --> IO2["LIST → FixedSizeList reads"]
       IO --> IO3["STRUCT / LIST / MAP nesting"]
   
       V --> M["Metadata integration"]
       M --> M1["Nested field IDs"]
       M --> M2["Nested null-count statistics"]
   
       V -.-> F["Follow-up phases"]
       F --> F1["Data Evolution"]
       F --> F2["Dedicated vector-store format"]
       F --> F3["Vector indexes and search"]
       F --> F4["Shared-shredding MAP integration"]
   ```
   
   Data Evolution, a dedicated point-lookup-optimized vector format, vector indexes/search, and shared-shredding MAP integration are intentionally left for follow-up work.
   
   ### Tests
   
   Added focused coverage for:
   - VECTOR SQL/JSON parsing, serialization, supported element types, and invalid definitions.
   - Arrow type conversion and schema validation.
   - Primary/partition/bucket key restrictions and Parquet-only validation.
   - Nested field ID propagation and nested column statistics.
   - VECTOR-to-LIST and LIST-to-VECTOR conversion, including nullable vectors, sliced arrays, invalid dimensions, and null elements.
   - VECTOR values nested in STRUCT, LIST, and MAP.
   - Reading an ordinary third-party Parquet LIST column as VECTOR.
   - End-to-end Parquet I/O for FLOAT and nested DOUBLE vectors.
   - Table-level append/write/read coverage in WriteAndReadInteTest.TestAppendVector.
   
   Validation performed locally:
   - 22 focused unit tests passed across type/JSON handling, Arrow utilities, schema validation, field IDs/statistics, and Parquet conversion/I/O.
   - paimon-write-and-read-inte-test and paimon-data-evolution-table-test built successfully.
   - All changed files passed the repository pre-commit hooks, including clang-format, C++ lint, CMake format, codespell, and Sphinx lint.
   - git diff --check passed.
   
   The table-level VECTOR test could not be executed successfully in the current macOS Debug build because Arrow is statically embedded in multiple dynamic libraries, causing a cross-DSO RTTI std::bad_cast. The existing non-VECTOR TestAppendSimple baseline also fails in the same environment. The test is included for validation in the supported CI/Linux environment.
   
   ### API and Format
   
   **API**: Yes.
   - Add public FieldType::VECTOR = 18.
   - Represent VECTOR columns through Arrow FixedSizeList<T, N> at the C++/Arrow boundary.
   - Extend schema parsing, validation, field type utilities, and nested statistics to recognize VECTOR.
   
   **Schema protocol**: Yes.
   - Add the VECTOR JSON type with element and length attributes.
   - Add the SQL-style type string VECTOR<T, N>.
   
   **Storage format**: The change adds VECTOR storage support but does not introduce a new Parquet physical encoding.
   - VECTOR is persisted using the standard Parquet LIST representation.
   - Existing non-VECTOR files and schemas are unchanged.
   - Compatible Parquet LIST data can be restored as VECTOR using the Paimon logical schema.
   - Dedicated vector storage and Data Evolution are outside the scope of this PR.
   
   ### Documentation
   
   Yes. The data types documentation now describes:
   - VECTOR<T, N> and its Arrow FixedSizeList mapping.
   - Supported element types and nullability rules.
   - The standard Parquet LIST representation used in this phase.
   - Current restrictions and follow-up scope.
   
   ### Generative AI tooling
   
   Generated-by: OpenAI Codex (GPT-5)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3800776380


##########
src/paimon/format/parquet/parquet_vector_io_test.cpp:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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 <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/ipc/json_simple.h"
+#include "gtest/gtest.h"
+#include "paimon/common/utils/arrow/arrow_input_stream_adapter.h"
+#include "paimon/common/utils/arrow/arrow_output_stream_adapter.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/core/io/vector_file_batch_reader.h"
+#include "paimon/defs.h"
+#include "paimon/format/parquet/parquet_file_batch_reader.h"
+#include "paimon/format/parquet/parquet_format_defs.h"
+#include "paimon/format/parquet/parquet_format_writer.h"
+#include "paimon/fs/file_system.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/testing/utils/read_result_collector.h"
+#include "paimon/testing/utils/testharness.h"
+#include "parquet/arrow/writer.h"
+#include "parquet/properties.h"
+
+namespace paimon {
+class Predicate;
+}  // namespace paimon
+
+namespace paimon::parquet::test {
+
+class ParquetVectorIoTest : public ::testing::Test {
+ public:
+    void SetUp() override {
+        pool_ = GetDefaultPool();
+        arrow_pool_ = GetArrowPool(pool_);
+        dir_ = paimon::test::UniqueTestDirectory::Create();
+        ASSERT_TRUE(dir_);
+        fs_ = dir_->GetFileSystem();
+    }
+
+    void WriteAndCheck(const std::string& file_name,
+                       const std::shared_ptr<arrow::StructType>& write_type,
+                       const std::shared_ptr<arrow::StructType>& read_type,
+                       const std::string& json) {
+        std::string file_path = dir_->Str() + "/" + file_name;
+        WriteWithFormatWriter(file_path, write_type, json, /*max_row_group_length=*/1024);
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        auto file_type =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+        std::shared_ptr<arrow::DataType> physical_value_type = file_type->field(1)->type();
+        if (physical_value_type->id() == arrow::Type::STRUCT) {
+            physical_value_type = physical_value_type->field(0)->type();
+        }
+        ASSERT_EQ(physical_value_type->id(), arrow::Type::LIST);
+
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*arrow::schema(read_type->fields()), c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), /*predicate=*/nullptr,
+                                               /*selection_bitmap=*/std::nullopt));
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+
+        arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+            arrow::ipc::internal::json::ArrayFromJSON(read_type, json);
+        ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+        std::shared_ptr<arrow::Array> expected = std::move(expected_result).ValueOrDie();
+        ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(expected)->Equals(actual))
+            << actual->ToString();
+    }
+
+    /// Writes the JSON rows through the Paimon Parquet writer, which stores VECTOR values as
+    /// Parquet LIST.
+    void WriteWithFormatWriter(const std::string& file_path,
+                               const std::shared_ptr<arrow::StructType>& write_type,
+                               const std::string& json, int64_t max_row_group_length) {
+        arrow::Result<std::shared_ptr<arrow::Array>> write_array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(write_type, json);
+        ASSERT_TRUE(write_array_result.ok()) << write_array_result.status().ToString();
+        std::shared_ptr<arrow::Array> write_array = std::move(write_array_result).ValueOrDie();
+        auto c_array = std::make_unique<ArrowArray>();
+        ASSERT_TRUE(arrow::ExportArray(*write_array, c_array.get()).ok());
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        ::parquet::WriterProperties::Builder properties_builder;
+        properties_builder.max_row_group_length(max_row_group_length);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFormatWriter> writer,
+            ParquetFormatWriter::Create(out, arrow::schema(write_type->fields()),
+                                        properties_builder.build(),
+                                        DEFAULT_PARQUET_WRITER_MAX_MEMORY_USE, arrow_pool_));
+        ASSERT_OK(writer->AddBatch(c_array.get()));
+        ASSERT_OK(writer->Finish());
+        ASSERT_OK(out->Close());
+    }
+
+    /// Writes `array` with the plain Arrow Parquet writer, so FixedSizeList columns keep their
+    /// Arrow type in the file schema the way Paimon Rust and Python writers store them.
+    void WriteWithArrowWriter(const std::string& file_path,
+                              const std::shared_ptr<arrow::StructType>& type,
+                              const std::string& json) {
+        arrow::Result<std::shared_ptr<arrow::Array>> array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(type, json);
+        ASSERT_TRUE(array_result.ok()) << array_result.status().ToString();
+        arrow::Result<std::shared_ptr<arrow::RecordBatch>> batch_result =
+            arrow::RecordBatch::FromStructArray(std::move(array_result).ValueOrDie());
+        ASSERT_TRUE(batch_result.ok()) << batch_result.status().ToString();
+        arrow::Result<std::shared_ptr<arrow::Table>> table_result =
+            arrow::Table::FromRecordBatches({std::move(batch_result).ValueOrDie()});
+        ASSERT_TRUE(table_result.ok()) << table_result.status().ToString();
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        auto arrow_out = std::make_shared<ArrowOutputStreamAdapter>(out);
+        ::parquet::WriterProperties::Builder properties_builder;
+        arrow::Status status = ::parquet::arrow::WriteTable(
+            *std::move(table_result).ValueOrDie(), arrow_pool_.get(), arrow_out,
+            /*chunk_size=*/1024, properties_builder.build());
+        ASSERT_TRUE(status.ok()) << status.ToString();
+        ASSERT_OK(out->Close());
+    }
+
+    void CreateVectorReader(const std::string& file_path,
+                            const std::shared_ptr<arrow::Schema>& read_schema,
+                            const std::shared_ptr<Predicate>& predicate,
+                            const std::map<std::string, std::string>& options, int32_t batch_size,
+                            std::unique_ptr<FileBatchReader>* vector_reader_out) {
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), options, batch_size,
+                                           /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*read_schema, c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), predicate,
+                                               /*selection_bitmap=*/std::nullopt));
+        *vector_reader_out = std::move(vector_reader);
+    }
+
+    void ReadFixtureAndCheck(
+        const std::string& file_name, arrow::Type::type expected_file_vector_type,
+        int32_t vector_length, const std::vector<int32_t>& expected_ids,
+        const std::vector<std::optional<std::vector<float>>>& expected_vectors) {
+        std::string file_path =
+            paimon::test::GetDataDir() + "/parquet/vector_compatibility/" + file_name;
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        auto file_type =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+        std::shared_ptr<arrow::Field> file_vector_field = file_type->GetFieldByName("embedding");
+        ASSERT_TRUE(file_vector_field);
+        ASSERT_EQ(file_vector_field->type()->id(), expected_file_vector_type);
+        std::shared_ptr<arrow::Field> file_id_field = file_type->GetFieldByName("id");
+        ASSERT_TRUE(file_id_field);
+
+        auto vector_type = arrow::fixed_size_list(
+            arrow::field("element", arrow::float32(), /*nullable=*/false), vector_length);
+        auto logical_schema =
+            arrow::schema({file_id_field, file_vector_field->WithType(vector_type)});
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_read_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*logical_schema, c_read_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_read_schema.get(), /*predicate=*/nullptr,
+                                               /*selection_bitmap=*/std::nullopt));
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));

Review Comment:
   Why not reuse `CreateVectorReader` here?



##########
src/paimon/core/schema/schema_validation.cpp:
##########
@@ -648,4 +662,26 @@ Status SchemaValidation::ValidateMapStorageLayout(const TableSchema& schema,
     return Status::OK();
 }
 
+Status SchemaValidation::ValidateVectorFields(const TableSchema& schema,
+                                              const CoreOptions& options) {
+    bool has_vector = false;
+    for (const auto& field : schema.Fields()) {
+        if (VectorUtils::ContainsVectorField(field.ArrowField())) {
+            has_vector = true;
+            break;
+        }
+    }
+    if (!has_vector) {
+        return Status::OK();
+    }
+    if (!schema.PrimaryKeys().empty()) {
+        return Status::NotImplemented(
+            "VECTOR fields in primary-key tables are not implemented yet.");
+    }

Review Comment:
   Please explicitly reject Data Evolution mode here.



##########
test/inte/write_and_read_inte_test.cpp:
##########
@@ -309,6 +309,132 @@ TEST_P(WriteAndReadInteTest, TestAppendSimple) {
     ASSERT_TRUE(success);
 }
 
+TEST_P(WriteAndReadInteTest, TestAppendVector) {
+    auto [file_format, file_system] = GetParam();
+    if (file_format != "parquet") {
+        return;
+    }
+
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float32(), /*nullable=*/false), 3);
+    arrow::FieldVector fields = {arrow::field("id", arrow::int32()),
+                                 arrow::field("embedding", vector_type)};
+    std::map<std::string, std::string> options = {
+        {Options::MANIFEST_FORMAT, "avro"},  {Options::FILE_FORMAT, file_format},
+        {Options::TARGET_FILE_SIZE, "1024"}, {Options::BUCKET, "-1"},
+        {Options::FILE_SYSTEM, file_system},
+    };
+    if (file_system == "jindo") {
+        options = AddOptionsForJindo(options);
+    }
+    ASSERT_OK_AND_ASSIGN(auto helper,
+                         TestHelper::Create(test_dir_, arrow::schema(fields), /*partition_keys=*/{},
+                                            /*primary_keys=*/{}, options,
+                                            /*is_streaming_mode=*/false));
+    const std::string data_json = R"([
+        [1, [1.0, 2.0, 3.0]],
+        [2, null],
+        [3, [4.0, 5.0, 6.0]]
+    ])";
+    auto data =
+        arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(fields), data_json).ValueOrDie();
+    auto c_array = std::make_unique<ArrowArray>();
+    ASSERT_TRUE(arrow::ExportArray(*data, c_array.get()).ok());
+    RecordBatchBuilder batch_builder(c_array.get());
+    ASSERT_OK_AND_ASSIGN(std::unique_ptr<RecordBatch> batch, batch_builder.SetBucket(0).Finish());
+    ASSERT_OK_AND_ASSIGN(auto commit_messages,
+                         helper->WriteAndCommit(std::move(batch), /*commit_identifier=*/0,
+                                                /*expected_commit_messages=*/std::nullopt));
+    (void)commit_messages;
+
+    arrow::FieldVector result_fields = fields;
+    result_fields.insert(result_fields.begin(), arrow::field("_VALUE_KIND", arrow::int8()));
+    ASSERT_OK_AND_ASSIGN(std::vector<std::shared_ptr<Split>> data_splits,
+                         helper->NewScan(StartupMode::LatestFull(), /*snapshot_id=*/std::nullopt));
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                         helper->ReadResult(data_splits));
+    const std::string expected_json = R"([
+        [0, 1, [1.0, 2.0, 3.0]],
+        [0, 2, null],
+        [0, 3, [4.0, 5.0, 6.0]]
+    ])";
+    auto expected =
+        arrow::ipc::internal::json::ArrayFromJSON(arrow::struct_(result_fields), expected_json)
+            .ValueOrDie();
+    ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(expected)->Equals(actual));
+}

Review Comment:
   Thank you very much for the contribution and for the patience through multiple rounds of updates. As a final step, could you please add one more end-to-end case that writes and reads nested types with vectors inside struct / map / list?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3800901688


##########
src/paimon/format/parquet/parquet_vector_io_test.cpp:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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 <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/ipc/json_simple.h"
+#include "gtest/gtest.h"
+#include "paimon/common/utils/arrow/arrow_input_stream_adapter.h"
+#include "paimon/common/utils/arrow/arrow_output_stream_adapter.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/core/io/vector_file_batch_reader.h"
+#include "paimon/defs.h"
+#include "paimon/format/parquet/parquet_file_batch_reader.h"
+#include "paimon/format/parquet/parquet_format_defs.h"
+#include "paimon/format/parquet/parquet_format_writer.h"
+#include "paimon/fs/file_system.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/testing/utils/read_result_collector.h"
+#include "paimon/testing/utils/testharness.h"
+#include "parquet/arrow/writer.h"
+#include "parquet/properties.h"
+
+namespace paimon {
+class Predicate;
+}  // namespace paimon
+
+namespace paimon::parquet::test {
+
+class ParquetVectorIoTest : public ::testing::Test {
+ public:
+    void SetUp() override {
+        pool_ = GetDefaultPool();
+        arrow_pool_ = GetArrowPool(pool_);
+        dir_ = paimon::test::UniqueTestDirectory::Create();
+        ASSERT_TRUE(dir_);
+        fs_ = dir_->GetFileSystem();
+    }
+
+    void WriteAndCheck(const std::string& file_name,
+                       const std::shared_ptr<arrow::StructType>& write_type,
+                       const std::shared_ptr<arrow::StructType>& read_type,
+                       const std::string& json) {
+        std::string file_path = dir_->Str() + "/" + file_name;
+        WriteWithFormatWriter(file_path, write_type, json, /*max_row_group_length=*/1024);
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        auto file_type =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+        std::shared_ptr<arrow::DataType> physical_value_type = file_type->field(1)->type();
+        if (physical_value_type->id() == arrow::Type::STRUCT) {
+            physical_value_type = physical_value_type->field(0)->type();
+        }
+        ASSERT_EQ(physical_value_type->id(), arrow::Type::LIST);
+
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*arrow::schema(read_type->fields()), c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), /*predicate=*/nullptr,
+                                               /*selection_bitmap=*/std::nullopt));
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+
+        arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+            arrow::ipc::internal::json::ArrayFromJSON(read_type, json);
+        ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+        std::shared_ptr<arrow::Array> expected = std::move(expected_result).ValueOrDie();
+        ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(expected)->Equals(actual))
+            << actual->ToString();
+    }
+
+    /// Writes the JSON rows through the Paimon Parquet writer, which stores VECTOR values as
+    /// Parquet LIST.
+    void WriteWithFormatWriter(const std::string& file_path,
+                               const std::shared_ptr<arrow::StructType>& write_type,
+                               const std::string& json, int64_t max_row_group_length) {
+        arrow::Result<std::shared_ptr<arrow::Array>> write_array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(write_type, json);
+        ASSERT_TRUE(write_array_result.ok()) << write_array_result.status().ToString();
+        std::shared_ptr<arrow::Array> write_array = std::move(write_array_result).ValueOrDie();
+        auto c_array = std::make_unique<ArrowArray>();
+        ASSERT_TRUE(arrow::ExportArray(*write_array, c_array.get()).ok());
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        ::parquet::WriterProperties::Builder properties_builder;
+        properties_builder.max_row_group_length(max_row_group_length);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFormatWriter> writer,
+            ParquetFormatWriter::Create(out, arrow::schema(write_type->fields()),
+                                        properties_builder.build(),
+                                        DEFAULT_PARQUET_WRITER_MAX_MEMORY_USE, arrow_pool_));
+        ASSERT_OK(writer->AddBatch(c_array.get()));
+        ASSERT_OK(writer->Finish());
+        ASSERT_OK(out->Close());
+    }
+
+    /// Writes `array` with the plain Arrow Parquet writer, so FixedSizeList columns keep their
+    /// Arrow type in the file schema the way Paimon Rust and Python writers store them.
+    void WriteWithArrowWriter(const std::string& file_path,
+                              const std::shared_ptr<arrow::StructType>& type,
+                              const std::string& json) {
+        arrow::Result<std::shared_ptr<arrow::Array>> array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(type, json);
+        ASSERT_TRUE(array_result.ok()) << array_result.status().ToString();
+        arrow::Result<std::shared_ptr<arrow::RecordBatch>> batch_result =
+            arrow::RecordBatch::FromStructArray(std::move(array_result).ValueOrDie());
+        ASSERT_TRUE(batch_result.ok()) << batch_result.status().ToString();
+        arrow::Result<std::shared_ptr<arrow::Table>> table_result =
+            arrow::Table::FromRecordBatches({std::move(batch_result).ValueOrDie()});
+        ASSERT_TRUE(table_result.ok()) << table_result.status().ToString();
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        auto arrow_out = std::make_shared<ArrowOutputStreamAdapter>(out);
+        ::parquet::WriterProperties::Builder properties_builder;
+        arrow::Status status = ::parquet::arrow::WriteTable(
+            *std::move(table_result).ValueOrDie(), arrow_pool_.get(), arrow_out,
+            /*chunk_size=*/1024, properties_builder.build());
+        ASSERT_TRUE(status.ok()) << status.ToString();
+        ASSERT_OK(out->Close());
+    }
+
+    void CreateVectorReader(const std::string& file_path,
+                            const std::shared_ptr<arrow::Schema>& read_schema,
+                            const std::shared_ptr<Predicate>& predicate,
+                            const std::map<std::string, std::string>& options, int32_t batch_size,
+                            std::unique_ptr<FileBatchReader>* vector_reader_out) {
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), options, batch_size,
+                                           /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*read_schema, c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), predicate,
+                                               /*selection_bitmap=*/std::nullopt));
+        *vector_reader_out = std::move(vector_reader);
+    }
+
+    void ReadFixtureAndCheck(
+        const std::string& file_name, arrow::Type::type expected_file_vector_type,
+        int32_t vector_length, const std::vector<int32_t>& expected_ids,
+        const std::vector<std::optional<std::vector<float>>>& expected_vectors) {
+        std::string file_path =
+            paimon::test::GetDataDir() + "/parquet/vector_compatibility/" + file_name;
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        auto file_type =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+        std::shared_ptr<arrow::Field> file_vector_field = file_type->GetFieldByName("embedding");
+        ASSERT_TRUE(file_vector_field);
+        ASSERT_EQ(file_vector_field->type()->id(), expected_file_vector_type);
+        std::shared_ptr<arrow::Field> file_id_field = file_type->GetFieldByName("id");
+        ASSERT_TRUE(file_id_field);
+
+        auto vector_type = arrow::fixed_size_list(
+            arrow::field("element", arrow::float32(), /*nullable=*/false), vector_length);
+        auto logical_schema =
+            arrow::schema({file_id_field, file_vector_field->WithType(vector_type)});
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_read_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*logical_schema, c_read_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_read_schema.get(), /*predicate=*/nullptr,
+                                               /*selection_bitmap=*/std::nullopt));
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+        ASSERT_EQ(actual->num_chunks(), 1);
+        ASSERT_EQ(actual->type()->id(), arrow::Type::STRUCT);
+        auto struct_array = checked_pointer_cast<arrow::StructArray>(actual->chunk(0));
+        std::shared_ptr<arrow::Array> id_field = struct_array->GetFieldByName("id");
+        std::shared_ptr<arrow::Array> vector_field = struct_array->GetFieldByName("embedding");
+        ASSERT_TRUE(id_field);
+        ASSERT_TRUE(vector_field);
+        ASSERT_EQ(id_field->type_id(), arrow::Type::INT32);
+        ASSERT_EQ(vector_field->type_id(), arrow::Type::FIXED_SIZE_LIST);
+        auto vector_array = checked_pointer_cast<arrow::FixedSizeListArray>(vector_field);
+        ASSERT_EQ(id_field->length(), static_cast<int64_t>(expected_ids.size()));
+        ASSERT_EQ(vector_array->length(), static_cast<int64_t>(expected_vectors.size()));
+        const int32_t* id_values = id_field->data()->GetValues<int32_t>(1);
+        for (int64_t i = 0; i < id_field->length(); ++i) {

Review Comment:
   Please change this to use `ids->Value(i)` instead:
   
   ```cpp
   auto ids = checked_pointer_cast<arrow::Int32Array>(id_field);
   ASSERT_EQ(ids->Value(i), expected_ids[i]);
   ```
   
   `GetValues<int32_t>(1)` already accounts for `ArrayData::offset`, so adding `id_field->offset()` again effectively applies the offset twice. This is not exposed at the moment because the current reader happens to produce arrays with offset 0.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "ChaomingZhangCN (via GitHub)" <gi...@apache.org>.
ChaomingZhangCN commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3792062315


##########
src/paimon/format/parquet/parquet_file_batch_reader.cpp:
##########
@@ -65,6 +66,13 @@ class Predicate;
 namespace paimon::parquet {
 
 namespace {
+std::shared_ptr<arrow::DataType> GetListElementType(const std::shared_ptr<arrow::DataType>& type) {
+    if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        return static_cast<const arrow::FixedSizeListType&>(*type).value_type();
+    }
+    return static_cast<const arrow::ListType&>(*type).value_type();
+}

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "ChaomingZhangCN (via GitHub)" <gi...@apache.org>.
ChaomingZhangCN commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3800439694


##########
src/paimon/common/utils/arrow/arrow_utils.cpp:
##########
@@ -363,6 +375,25 @@ Status ArrowUtils::InnerCheckNullabilityMatch(const std::shared_ptr<arrow::Field
         auto list_array = checked_pointer_cast<arrow::ListArray>(data);
         PAIMON_RETURN_NOT_OK(
             InnerCheckNullabilityMatch(list_type->value_field(), list_array->values()));
+    } else if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        auto vector_type = checked_pointer_cast<arrow::FixedSizeListType>(field->type());
+        auto vector_array = checked_pointer_cast<arrow::FixedSizeListArray>(data);
+        const std::shared_ptr<arrow::Array>& values = vector_array->values();
+        if (values->null_count() != 0) {
+            int32_t vector_length = vector_type->list_size();
+            for (int64_t i = 0; i < vector_array->length(); ++i) {
+                if (vector_array->IsNull(i)) {
+                    continue;
+                }
+                int64_t value_offset = (vector_array->offset() + i) * vector_length;
+                for (int32_t j = 0; j < vector_length; ++j) {
+                    if (values->IsNull(value_offset + j)) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "zjw1111 (via GitHub)" <gi...@apache.org>.
zjw1111 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3795288649


##########
src/paimon/common/utils/arrow/arrow_utils.cpp:
##########
@@ -363,6 +375,25 @@ Status ArrowUtils::InnerCheckNullabilityMatch(const std::shared_ptr<arrow::Field
         auto list_array = checked_pointer_cast<arrow::ListArray>(data);
         PAIMON_RETURN_NOT_OK(
             InnerCheckNullabilityMatch(list_type->value_field(), list_array->values()));
+    } else if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        auto vector_type = checked_pointer_cast<arrow::FixedSizeListType>(field->type());
+        auto vector_array = checked_pointer_cast<arrow::FixedSizeListArray>(data);
+        const std::shared_ptr<arrow::Array>& values = vector_array->values();
+        if (values->null_count() != 0) {
+            int32_t vector_length = vector_type->list_size();
+            for (int64_t i = 0; i < vector_array->length(); ++i) {
+                if (vector_array->IsNull(i)) {
+                    continue;
+                }
+                int64_t value_offset = (vector_array->offset() + i) * vector_length;
+                for (int32_t j = 0; j < vector_length; ++j) {
+                    if (values->IsNull(value_offset + j)) {

Review Comment:
   This element scan can read out of bounds on the write path.
   
   `AbstractFileStoreWrite::Write` builds `data` via `arrow::ImportArray(batch->GetData(), arrow::struct_(write_schema_->fields()))`, and Arrow's C importer does not verify that a `FixedSizeList` child holds `length * list_size` values (`ArrayImporter::Visit(const FixedSizeListType&)` only checks the child/buffer counts). No `Validate()` runs before `CheckNullabilityMatch` either. So if a caller passes an array whose child is shorter than the declared dimension, `values->IsNull(value_offset + j)` indexes past the child's validity bitmap.
   
   Could you add a structural check before the scan? `data->Validate()` in `AbstractFileStoreWrite::Write` would be enough — it is O(1) for this layout and already rejects `values->length() < (offset + length) * list_size`. It would also turn the opposite case (child longer than declared, currently reinterpreted silently with the wrong dimension) into a clear error instead of corrupt data.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "dalingmeng (via GitHub)" <gi...@apache.org>.
dalingmeng commented on PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#issuecomment-5339682968

   +1


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3800909096


##########
src/paimon/format/parquet/parquet_vector_io_test.cpp:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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 <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/ipc/json_simple.h"
+#include "gtest/gtest.h"
+#include "paimon/common/utils/arrow/arrow_input_stream_adapter.h"
+#include "paimon/common/utils/arrow/arrow_output_stream_adapter.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/core/io/vector_file_batch_reader.h"
+#include "paimon/defs.h"
+#include "paimon/format/parquet/parquet_file_batch_reader.h"
+#include "paimon/format/parquet/parquet_format_defs.h"
+#include "paimon/format/parquet/parquet_format_writer.h"
+#include "paimon/fs/file_system.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/testing/utils/read_result_collector.h"
+#include "paimon/testing/utils/testharness.h"
+#include "parquet/arrow/writer.h"
+#include "parquet/properties.h"
+
+namespace paimon {
+class Predicate;
+}  // namespace paimon
+
+namespace paimon::parquet::test {
+
+class ParquetVectorIoTest : public ::testing::Test {
+ public:
+    void SetUp() override {
+        pool_ = GetDefaultPool();
+        arrow_pool_ = GetArrowPool(pool_);
+        dir_ = paimon::test::UniqueTestDirectory::Create();
+        ASSERT_TRUE(dir_);
+        fs_ = dir_->GetFileSystem();
+    }
+
+    void WriteAndCheck(const std::string& file_name,
+                       const std::shared_ptr<arrow::StructType>& write_type,
+                       const std::shared_ptr<arrow::StructType>& read_type,
+                       const std::string& json) {
+        std::string file_path = dir_->Str() + "/" + file_name;
+        WriteWithFormatWriter(file_path, write_type, json, /*max_row_group_length=*/1024);
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        auto file_type =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+        std::shared_ptr<arrow::DataType> physical_value_type = file_type->field(1)->type();
+        if (physical_value_type->id() == arrow::Type::STRUCT) {
+            physical_value_type = physical_value_type->field(0)->type();
+        }
+        ASSERT_EQ(physical_value_type->id(), arrow::Type::LIST);
+
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*arrow::schema(read_type->fields()), c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), /*predicate=*/nullptr,
+                                               /*selection_bitmap=*/std::nullopt));
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+
+        arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+            arrow::ipc::internal::json::ArrayFromJSON(read_type, json);
+        ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+        std::shared_ptr<arrow::Array> expected = std::move(expected_result).ValueOrDie();
+        ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(expected)->Equals(actual))
+            << actual->ToString();
+    }
+
+    /// Writes the JSON rows through the Paimon Parquet writer, which stores VECTOR values as
+    /// Parquet LIST.
+    void WriteWithFormatWriter(const std::string& file_path,
+                               const std::shared_ptr<arrow::StructType>& write_type,
+                               const std::string& json, int64_t max_row_group_length) {
+        arrow::Result<std::shared_ptr<arrow::Array>> write_array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(write_type, json);
+        ASSERT_TRUE(write_array_result.ok()) << write_array_result.status().ToString();
+        std::shared_ptr<arrow::Array> write_array = std::move(write_array_result).ValueOrDie();
+        auto c_array = std::make_unique<ArrowArray>();
+        ASSERT_TRUE(arrow::ExportArray(*write_array, c_array.get()).ok());
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        ::parquet::WriterProperties::Builder properties_builder;
+        properties_builder.max_row_group_length(max_row_group_length);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFormatWriter> writer,
+            ParquetFormatWriter::Create(out, arrow::schema(write_type->fields()),
+                                        properties_builder.build(),
+                                        DEFAULT_PARQUET_WRITER_MAX_MEMORY_USE, arrow_pool_));
+        ASSERT_OK(writer->AddBatch(c_array.get()));
+        ASSERT_OK(writer->Finish());
+        ASSERT_OK(out->Close());
+    }
+
+    /// Writes `array` with the plain Arrow Parquet writer, so FixedSizeList columns keep their
+    /// Arrow type in the file schema the way Paimon Rust and Python writers store them.
+    void WriteWithArrowWriter(const std::string& file_path,
+                              const std::shared_ptr<arrow::StructType>& type,
+                              const std::string& json) {
+        arrow::Result<std::shared_ptr<arrow::Array>> array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(type, json);
+        ASSERT_TRUE(array_result.ok()) << array_result.status().ToString();
+        arrow::Result<std::shared_ptr<arrow::RecordBatch>> batch_result =
+            arrow::RecordBatch::FromStructArray(std::move(array_result).ValueOrDie());
+        ASSERT_TRUE(batch_result.ok()) << batch_result.status().ToString();
+        arrow::Result<std::shared_ptr<arrow::Table>> table_result =
+            arrow::Table::FromRecordBatches({std::move(batch_result).ValueOrDie()});
+        ASSERT_TRUE(table_result.ok()) << table_result.status().ToString();
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        auto arrow_out = std::make_shared<ArrowOutputStreamAdapter>(out);
+        ::parquet::WriterProperties::Builder properties_builder;
+        arrow::Status status = ::parquet::arrow::WriteTable(
+            *std::move(table_result).ValueOrDie(), arrow_pool_.get(), arrow_out,
+            /*chunk_size=*/1024, properties_builder.build());
+        ASSERT_TRUE(status.ok()) << status.ToString();
+        ASSERT_OK(out->Close());
+    }
+
+    void CreateVectorReader(const std::string& file_path,
+                            const std::shared_ptr<arrow::Schema>& read_schema,
+                            const std::shared_ptr<Predicate>& predicate,
+                            const std::map<std::string, std::string>& options, int32_t batch_size,
+                            std::unique_ptr<FileBatchReader>* vector_reader_out) {
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), options, batch_size,
+                                           /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*read_schema, c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), predicate,
+                                               /*selection_bitmap=*/std::nullopt));
+        *vector_reader_out = std::move(vector_reader);
+    }
+
+    void ReadFixtureAndCheck(
+        const std::string& file_name, arrow::Type::type expected_file_vector_type,
+        int32_t vector_length, const std::vector<int32_t>& expected_ids,
+        const std::vector<std::optional<std::vector<float>>>& expected_vectors) {
+        std::string file_path =
+            paimon::test::GetDataDir() + "/parquet/vector_compatibility/" + file_name;
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        auto file_type =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+        std::shared_ptr<arrow::Field> file_vector_field = file_type->GetFieldByName("embedding");
+        ASSERT_TRUE(file_vector_field);
+        ASSERT_EQ(file_vector_field->type()->id(), expected_file_vector_type);
+        std::shared_ptr<arrow::Field> file_id_field = file_type->GetFieldByName("id");
+        ASSERT_TRUE(file_id_field);
+
+        auto vector_type = arrow::fixed_size_list(
+            arrow::field("element", arrow::float32(), /*nullable=*/false), vector_length);
+        auto logical_schema =
+            arrow::schema({file_id_field, file_vector_field->WithType(vector_type)});
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_read_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*logical_schema, c_read_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_read_schema.get(), /*predicate=*/nullptr,
+                                               /*selection_bitmap=*/std::nullopt));
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+        ASSERT_EQ(actual->num_chunks(), 1);
+        ASSERT_EQ(actual->type()->id(), arrow::Type::STRUCT);
+        auto struct_array = checked_pointer_cast<arrow::StructArray>(actual->chunk(0));
+        std::shared_ptr<arrow::Array> id_field = struct_array->GetFieldByName("id");
+        std::shared_ptr<arrow::Array> vector_field = struct_array->GetFieldByName("embedding");
+        ASSERT_TRUE(id_field);
+        ASSERT_TRUE(vector_field);
+        ASSERT_EQ(id_field->type_id(), arrow::Type::INT32);
+        ASSERT_EQ(vector_field->type_id(), arrow::Type::FIXED_SIZE_LIST);
+        auto vector_array = checked_pointer_cast<arrow::FixedSizeListArray>(vector_field);
+        ASSERT_EQ(id_field->length(), static_cast<int64_t>(expected_ids.size()));
+        ASSERT_EQ(vector_array->length(), static_cast<int64_t>(expected_vectors.size()));
+        const int32_t* id_values = id_field->data()->GetValues<int32_t>(1);
+        for (int64_t i = 0; i < id_field->length(); ++i) {
+            ASSERT_FALSE(id_field->IsNull(i));
+            ASSERT_EQ(id_values[id_field->offset() + i], expected_ids[i]);
+            if (!expected_vectors[i]) {
+                ASSERT_TRUE(vector_array->IsNull(i));
+                continue;
+            }
+            ASSERT_FALSE(vector_array->IsNull(i));
+            ASSERT_EQ(vector_array->value_length(i),
+                      static_cast<int64_t>(expected_vectors[i]->size()));
+            std::shared_ptr<arrow::Array> values = vector_array->value_slice(i);
+            const float* vector_values = values->data()->GetValues<float>(1);
+            for (int64_t j = 0; j < vector_array->value_length(i); ++j) {
+                ASSERT_FLOAT_EQ(vector_values[j], expected_vectors[i].value()[j]);
+            }
+        }
+    }
+
+ private:
+    std::shared_ptr<MemoryPool> pool_;
+    std::shared_ptr<arrow::MemoryPool> arrow_pool_;
+    std::shared_ptr<FileSystem> fs_;
+    std::unique_ptr<paimon::test::UniqueTestDirectory> dir_;
+};
+
+TEST_F(ParquetVectorIoTest, WriteAndReadVector) {
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float32(), /*nullable=*/false), 3);
+    auto struct_type = checked_pointer_cast<arrow::StructType>(arrow::struct_(
+        {arrow::field("id", arrow::int32()), arrow::field("embedding", vector_type)}));
+    WriteAndCheck("vector.parquet", struct_type, struct_type,
+                  R"([[1, [1.0, 2.0, 3.0]], [2, null], [3, [4.0, 5.0, 6.0]]])");
+}
+
+TEST_F(ParquetVectorIoTest, ReadOrdinaryParquetListAsVector) {
+    auto physical_type = checked_pointer_cast<arrow::StructType>(
+        arrow::struct_({arrow::field("id", arrow::int32()),
+                        arrow::field("embedding", arrow::list(arrow::float32()))}));
+    auto logical_type = checked_pointer_cast<arrow::StructType>(arrow::struct_({
+        arrow::field("id", arrow::int32()),
+        arrow::field("embedding", arrow::fixed_size_list(arrow::float32(), 3)),
+    }));
+    WriteAndCheck("list.parquet", physical_type, logical_type,
+                  R"([[1, [1.0, 2.0, 3.0]], [2, null], [3, [4.0, 5.0, 6.0]]])");
+}
+
+TEST_F(ParquetVectorIoTest, WriteAndReadNestedDoubleVector) {
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float64(), /*nullable=*/false), 2);
+    auto struct_type = checked_pointer_cast<arrow::StructType>(arrow::struct_({
+        arrow::field("id", arrow::int32()),
+        arrow::field("payload", arrow::struct_({arrow::field("embedding", vector_type),
+                                                arrow::field("history", arrow::list(vector_type)),
+                                                arrow::field("by_name", arrow::map(arrow::utf8(),
+                                                                                   vector_type))})),
+    }));
+    WriteAndCheck("nested-vector.parquet", struct_type, struct_type,
+                  R"([[1, [[1.0, 2.0], [[3.0, 4.0], null], [["a", [5.0, 6.0]]]]],
+                       [2, [null, null, [["b", null]]]]])");
+}
+
+// Vectors nested in a LIST keep their Arrow type when a third-party writer stores them as
+// FixedSizeList, so the Parquet reader must accept a FixedSizeList read type as well.
+TEST_F(ParquetVectorIoTest, ReadNestedFixedSizeListFile) {
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float32(), /*nullable=*/false), 3);
+    auto logical_type = checked_pointer_cast<arrow::StructType>(arrow::struct_({
+        arrow::field("id", arrow::int32()),
+        arrow::field("history", arrow::list(vector_type)),
+    }));
+    const std::string json = R"([[1, [[1.0, 2.0, 3.0], null]], [2, null]])";
+    std::string file_path = dir_->Str() + "/nested-fixed-size-list.parquet";
+    WriteWithArrowWriter(file_path, logical_type, json);
+
+    std::unique_ptr<FileBatchReader> reader;
+    CreateVectorReader(file_path, arrow::schema(logical_type->fields()), /*predicate=*/nullptr,
+                       /*options=*/{}, /*batch_size=*/10, &reader);
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                         paimon::test::ReadResultCollector::CollectResult(reader.get()));
+    arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+        arrow::ipc::internal::json::ArrayFromJSON(logical_type, json);
+    ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+    ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(std::move(expected_result).ValueOrDie())
+                    ->Equals(actual))
+        << actual->ToString();
+}
+
+TEST_F(ParquetVectorIoTest, ReadVectorWithPredicatePushdown) {
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float32(), /*nullable=*/false), 3);
+    auto logical_type = checked_pointer_cast<arrow::StructType>(arrow::struct_(
+        {arrow::field("id", arrow::int32()), arrow::field("embedding", vector_type)}));
+    // One row per row group, so the predicate on `id` prunes row groups while reading.
+    std::string file_path = dir_->Str() + "/vector-predicate.parquet";
+    WriteWithFormatWriter(file_path, logical_type,
+                          R"([[1, [1.0, 2.0, 3.0]], [2, null], [3, [4.0, 5.0, 6.0]],
+                              [4, [7.0, 8.0, 9.0]]])",
+                          /*max_row_group_length=*/1);
+
+    std::shared_ptr<Predicate> predicate = PredicateBuilder::GreaterThan(
+        /*field_index=*/0, /*field_name=*/"id", FieldType::INT, Literal(2));
+    std::unique_ptr<FileBatchReader> reader;
+    CreateVectorReader(file_path, arrow::schema(logical_type->fields()), predicate,
+                       /*options=*/{}, /*batch_size=*/10, &reader);
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                         paimon::test::ReadResultCollector::CollectResult(reader.get()));
+    arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+        arrow::ipc::internal::json::ArrayFromJSON(
+            logical_type, R"([[3, [4.0, 5.0, 6.0]], [4, [7.0, 8.0, 9.0]]])");
+    ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+    ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(std::move(expected_result).ValueOrDie())
+                    ->Equals(actual))
+        << actual->ToString();
+}
+
+TEST_F(ParquetVectorIoTest, ReadJavaFixture) {
+    ReadFixtureAndCheck(
+        "java_vector.parquet", arrow::Type::LIST, /*vector_length=*/2,

Review Comment:
   The helper supports null vectors, but the current Java and Rust fixtures do not contain any null vector, so cross-language compatibility is not fully covered. Please add nullable fixtures for Java `LIST` and Rust `FixedSizeList`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#issuecomment-5328187644

   @dalingmeng Please double-check this pr.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "dalingmeng (via GitHub)" <gi...@apache.org>.
dalingmeng commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3810967040


##########
src/paimon/common/utils/arrow/vector_utils.h:
##########


Review Comment:
   Dead code: `VectorUtils::ValidateNestedVectorElements` has no production caller — only its own recursion and one unit test reference it. Nested VECTOR validation is already covered by `InnerCheckNullabilityMatch` (write path) and by the recursion in `ConvertToReadType`/`ConvertToWriteType`. Suggest removing it (and its test), or wiring it in as the single entry point if that was the intent.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "SteNicholas (via GitHub)" <gi...@apache.org>.
SteNicholas merged PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3800929111


##########
src/paimon/format/parquet/parquet_vector_io_test.cpp:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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 <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/ipc/json_simple.h"
+#include "gtest/gtest.h"
+#include "paimon/common/utils/arrow/arrow_input_stream_adapter.h"
+#include "paimon/common/utils/arrow/arrow_output_stream_adapter.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/core/io/vector_file_batch_reader.h"
+#include "paimon/defs.h"
+#include "paimon/format/parquet/parquet_file_batch_reader.h"
+#include "paimon/format/parquet/parquet_format_defs.h"
+#include "paimon/format/parquet/parquet_format_writer.h"
+#include "paimon/fs/file_system.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/testing/utils/read_result_collector.h"
+#include "paimon/testing/utils/testharness.h"
+#include "parquet/arrow/writer.h"
+#include "parquet/properties.h"
+
+namespace paimon {
+class Predicate;
+}  // namespace paimon
+
+namespace paimon::parquet::test {
+
+class ParquetVectorIoTest : public ::testing::Test {
+ public:
+    void SetUp() override {
+        pool_ = GetDefaultPool();
+        arrow_pool_ = GetArrowPool(pool_);
+        dir_ = paimon::test::UniqueTestDirectory::Create();
+        ASSERT_TRUE(dir_);
+        fs_ = dir_->GetFileSystem();
+    }
+
+    void WriteAndCheck(const std::string& file_name,
+                       const std::shared_ptr<arrow::StructType>& write_type,
+                       const std::shared_ptr<arrow::StructType>& read_type,
+                       const std::string& json) {
+        std::string file_path = dir_->Str() + "/" + file_name;
+        WriteWithFormatWriter(file_path, write_type, json, /*max_row_group_length=*/1024);
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        auto file_type =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+        std::shared_ptr<arrow::DataType> physical_value_type = file_type->field(1)->type();
+        if (physical_value_type->id() == arrow::Type::STRUCT) {
+            physical_value_type = physical_value_type->field(0)->type();
+        }
+        ASSERT_EQ(physical_value_type->id(), arrow::Type::LIST);
+
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*arrow::schema(read_type->fields()), c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), /*predicate=*/nullptr,
+                                               /*selection_bitmap=*/std::nullopt));
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+
+        arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+            arrow::ipc::internal::json::ArrayFromJSON(read_type, json);
+        ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+        std::shared_ptr<arrow::Array> expected = std::move(expected_result).ValueOrDie();
+        ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(expected)->Equals(actual))
+            << actual->ToString();
+    }
+
+    /// Writes the JSON rows through the Paimon Parquet writer, which stores VECTOR values as
+    /// Parquet LIST.
+    void WriteWithFormatWriter(const std::string& file_path,
+                               const std::shared_ptr<arrow::StructType>& write_type,
+                               const std::string& json, int64_t max_row_group_length) {
+        arrow::Result<std::shared_ptr<arrow::Array>> write_array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(write_type, json);
+        ASSERT_TRUE(write_array_result.ok()) << write_array_result.status().ToString();
+        std::shared_ptr<arrow::Array> write_array = std::move(write_array_result).ValueOrDie();
+        auto c_array = std::make_unique<ArrowArray>();
+        ASSERT_TRUE(arrow::ExportArray(*write_array, c_array.get()).ok());
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        ::parquet::WriterProperties::Builder properties_builder;
+        properties_builder.max_row_group_length(max_row_group_length);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFormatWriter> writer,
+            ParquetFormatWriter::Create(out, arrow::schema(write_type->fields()),
+                                        properties_builder.build(),
+                                        DEFAULT_PARQUET_WRITER_MAX_MEMORY_USE, arrow_pool_));
+        ASSERT_OK(writer->AddBatch(c_array.get()));
+        ASSERT_OK(writer->Finish());
+        ASSERT_OK(out->Close());
+    }
+
+    /// Writes `array` with the plain Arrow Parquet writer, so FixedSizeList columns keep their
+    /// Arrow type in the file schema the way Paimon Rust and Python writers store them.
+    void WriteWithArrowWriter(const std::string& file_path,
+                              const std::shared_ptr<arrow::StructType>& type,
+                              const std::string& json) {
+        arrow::Result<std::shared_ptr<arrow::Array>> array_result =

Review Comment:
   `WriteWithArrowWriter` currently cannot guarantee that the data will be read back as `FixedSizeList`. If we want to guarantee that arrow::parquet reads it back as `FixedSizeList`, we need to store the schema.
   
   ```cpp
   ::parquet::WriterProperties::Builder properties_builder;
   auto arrow_properties =
       ::parquet::ArrowWriterProperties::Builder()
           .store_schema()
           ->build();
   
   arrow::Status status = ::parquet::arrow::WriteTable(
       *table,
       arrow_pool_.get(),
       arrow_out,
       /*chunk_size=*/1024,
       properties_builder.build(),
       arrow_properties);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3788466836


##########
src/paimon/format/parquet/parquet_file_batch_reader.cpp:
##########
@@ -762,7 +783,7 @@ Status ParquetFileBatchReader::CollectLeafIndices(const std::shared_ptr<arrow::D
 void ParquetFileBatchReader::SkipLeafIndices(const std::shared_ptr<arrow::DataType>& file_type,
                                              int32_t* leaf_index) {
     if (file_type->id() == arrow::Type::STRUCT || file_type->id() == arrow::Type::LIST ||
-        file_type->id() == arrow::Type::MAP) {

Review Comment:
   For write side, I noticed that the current Paimon library is using Arrow 17, which does not handle `fixed size list -> list` conversion very well in the presence of nulls. For example, cases like `[valid vec, null, valid vec]` may fail.
   
   If that’s the case, then the write path may also need to reuse the current `ParquetVectorConverter::ConvertToWriteType` logic.
   
   Since this issue has already been fixed in newer Arrow versions, I’d suggest keeping the write-side handling as isolated as possible within the Parquet format layer, and adding a TODO so that the extra conversion can be removed directly once we upgrade Arrow.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "ChaomingZhangCN (via GitHub)" <gi...@apache.org>.
ChaomingZhangCN commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3792061684


##########
src/paimon/common/types/data_type_json_parser.cpp:
##########
@@ -607,6 +615,34 @@ Result<std::shared_ptr<arrow::DataType>> TokenParser::ParseTimestampLtzType() {
     return ts_type;
 }
 
+Result<std::shared_ptr<arrow::DataType>> TokenParser::ParseVectorType() {
+    PAIMON_RETURN_NOT_OK(NextToken(TokenType::BEGIN_SUBTYPE));
+    bool element_nullable = true;
+    AtomicTypeAttributes element_attributes;
+    PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<arrow::DataType> element_type,
+                           ParseTypeWithNullability(&element_nullable, &element_attributes));
+    if (element_attributes.is_blob || element_attributes.is_variant ||
+        !VectorType::IsValidElementType(element_type)) {
+        return Status::Invalid(
+            fmt::format("Invalid element type for vector: {}", element_type->ToString()));
+    }
+    PAIMON_RETURN_NOT_OK(NextToken(TokenType::LIST_SEPARATOR));
+    PAIMON_RETURN_NOT_OK(NextToken(TokenType::LITERAL_INT));
+    const std::string& length_token = GetToken().value;
+    int64_t length = 0;
+    const auto [end, error] =
+        std::from_chars(length_token.data(), length_token.data() + length_token.size(), length);
+    if (error != std::errc() || end != length_token.data() + length_token.size() || length < 1 ||
+        length > std::numeric_limits<int32_t>::max()) {
+        return Status::Invalid(
+            fmt::format("Vector length must be between 1 and {} (both inclusive), but was {}",
+                        std::numeric_limits<int32_t>::max(), length_token));
+    }

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "SteNicholas (via GitHub)" <gi...@apache.org>.
SteNicholas commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3803574743


##########
src/paimon/core/io/vector_file_batch_reader.cpp:
##########
@@ -0,0 +1,274 @@
+/*
+ * 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/io/vector_file_batch_reader.h"
+
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/compute/api.h"
+#include "arrow/type.h"
+#include "fmt/format.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/arrow/vector_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/status.h"
+
+namespace paimon {
+namespace {
+
+std::shared_ptr<arrow::Field> FindField(const std::shared_ptr<arrow::DataType>& type,
+                                        const std::string& name) {
+    for (const auto& field : type->fields()) {
+        if (field->name() == name) {
+            return field;
+        }
+    }
+    return nullptr;
+}
+
+/// Rebuilds `map_type` with new key and item types, keeping the name and metadata of its
+/// entries field.
+std::shared_ptr<arrow::DataType> MakeMapType(const arrow::MapType& map_type,
+                                             const std::shared_ptr<arrow::Field>& key_field,
+                                             const std::shared_ptr<arrow::Field>& item_field) {
+    return std::make_shared<arrow::MapType>(
+        map_type.value_field()->WithType(arrow::struct_({key_field, item_field})),
+        map_type.keys_sorted());
+}
+
+/// Returns the type to request from the file format plugin. A VECTOR is only read back as a
+/// LIST when the file itself stores it as one: writers such as Paimon Java expose VECTOR
+/// columns as Arrow LIST, while Paimon Rust and Python expose them as FixedSizeList.
+std::shared_ptr<arrow::DataType> GetPhysicalReadType(
+    const std::shared_ptr<arrow::DataType>& logical_type,
+    const std::shared_ptr<arrow::DataType>& file_type) {
+    switch (logical_type->id()) {
+        case arrow::Type::FIXED_SIZE_LIST: {
+            if (!file_type || file_type->id() != arrow::Type::LIST) {
+                return logical_type;
+            }
+            const auto& vector_type = checked_cast<const arrow::FixedSizeListType&>(*logical_type);
+            const auto& list_type = checked_cast<const arrow::ListType&>(*file_type);
+            return arrow::list(vector_type.value_field()->WithType(
+                GetPhysicalReadType(vector_type.value_type(), list_type.value_type())));
+        }
+        case arrow::Type::STRUCT: {
+            if (!file_type || file_type->id() != arrow::Type::STRUCT) {
+                return logical_type;
+            }
+            arrow::FieldVector fields;
+            fields.reserve(logical_type->num_fields());
+            for (const auto& field : logical_type->fields()) {
+                std::shared_ptr<arrow::Field> file_field = FindField(file_type, field->name());
+                fields.push_back(field->WithType(
+                    GetPhysicalReadType(field->type(), file_field ? file_field->type() : nullptr)));
+            }
+            return arrow::struct_(fields);
+        }
+        case arrow::Type::LIST: {
+            if (!file_type || file_type->id() != arrow::Type::LIST) {
+                return logical_type;
+            }
+            return arrow::list(logical_type->field(0)->WithType(
+                GetPhysicalReadType(logical_type->field(0)->type(), file_type->field(0)->type())));
+        }
+        case arrow::Type::MAP: {
+            if (!file_type || file_type->id() != arrow::Type::MAP) {
+                return logical_type;
+            }
+            const auto& map_type = checked_cast<const arrow::MapType&>(*logical_type);
+            const auto& file_map_type = checked_cast<const arrow::MapType&>(*file_type);
+            return MakeMapType(map_type,
+                               map_type.key_field()->WithType(GetPhysicalReadType(
+                                   map_type.key_type(), file_map_type.key_type())),
+                               map_type.item_field()->WithType(GetPhysicalReadType(
+                                   map_type.item_type(), file_map_type.item_type())));
+        }
+        default:
+            return logical_type;
+    }
+}
+
+Result<std::shared_ptr<arrow::Array>> CastListToVector(
+    const std::shared_ptr<arrow::Array>& array,
+    const std::shared_ptr<arrow::FixedSizeListType>& read_type, arrow::MemoryPool* pool) {
+    if (array->type_id() != arrow::Type::LIST) {
+        return Status::Invalid(
+            fmt::format("Cannot restore VECTOR from type {}", array->type()->ToString()));
+    }
+    PAIMON_RETURN_NOT_OK(VectorUtils::ValidateVectorElements(*array));
+    arrow::compute::ExecContext exec_context(pool);
+    arrow::TypeHolder type_holder(read_type.get());
+    arrow::compute::CastOptions options = arrow::compute::CastOptions::Safe();
+    PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(
+        std::shared_ptr<arrow::Array> result,
+        arrow::compute::Cast(*array, type_holder, options, &exec_context));
+    return result;
+}
+
+std::shared_ptr<arrow::DataType> RebuildNestedType(
+    const std::shared_ptr<arrow::DataType>& read_type,
+    const std::vector<std::shared_ptr<arrow::ArrayData>>& children) {
+    if (read_type->id() == arrow::Type::STRUCT) {
+        arrow::FieldVector fields;
+        fields.reserve(children.size());
+        for (int32_t i = 0; i < static_cast<int32_t>(children.size()); ++i) {
+            fields.push_back(read_type->field(i)->WithType(children[i]->type));
+        }
+        return arrow::struct_(fields);
+    }
+    if (read_type->id() == arrow::Type::LIST) {
+        return arrow::list(read_type->field(0)->WithType(children[0]->type));
+    }
+
+    const auto& entries_type = checked_cast<const arrow::StructType&>(*children[0]->type);
+    const auto& map_type = checked_cast<const arrow::MapType&>(*read_type);
+    return MakeMapType(map_type, map_type.key_field()->WithType(entries_type.field(0)->type()),
+                       map_type.item_field()->WithType(entries_type.field(1)->type()));
+}
+
+Result<std::shared_ptr<arrow::Array>> ConvertToReadType(
+    const std::shared_ptr<arrow::Array>& array, const std::shared_ptr<arrow::DataType>& read_type,
+    arrow::MemoryPool* pool) {
+    if (!VectorUtils::ContainsVectorType(read_type)) {
+        return array;
+    }
+    switch (read_type->id()) {
+        case arrow::Type::FIXED_SIZE_LIST: {
+            if (array->type_id() == arrow::Type::FIXED_SIZE_LIST) {
+                const auto& source_type =
+                    checked_cast<const arrow::FixedSizeListType&>(*array->type());
+                const auto& vector_type = checked_cast<const arrow::FixedSizeListType&>(*read_type);
+                if (source_type.list_size() != vector_type.list_size() ||
+                    !source_type.value_type()->Equals(vector_type.value_type())) {
+                    return Status::Invalid(fmt::format("VECTOR type mismatch: data {} vs read {}",
+                                                       source_type.ToString(),
+                                                       vector_type.ToString()));
+                }
+                PAIMON_RETURN_NOT_OK(VectorUtils::ValidateVectorElements(*array));
+                return array;

Review Comment:
   **[P1] Normalize the FixedSizeList output type**
   
   This returns the file FixedSizeList type unchanged after comparing only the list size and value data type. The physical child field name/nullability can therefore remain different from the requested logical schema (for example, the Rust fixture uses `element: float not null`, while the C++ schema uses `item: float`). Java/C++ `LIST` files are cast to the logical type, so reading mixed encodings yields unequal batch types and `ChunkedArray::Make` fails with “Array chunks must all be same type.” Please zero-copy rewrap a copy of `array->data()` with `read_type` after validation, and add a regression test that reads mixed `LIST`/`FixedSizeList` files using the actual table schema.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3800929111


##########
src/paimon/format/parquet/parquet_vector_io_test.cpp:
##########
@@ -0,0 +1,364 @@
+/*
+ * 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 <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/ipc/json_simple.h"
+#include "gtest/gtest.h"
+#include "paimon/common/utils/arrow/arrow_input_stream_adapter.h"
+#include "paimon/common/utils/arrow/arrow_output_stream_adapter.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/core/io/vector_file_batch_reader.h"
+#include "paimon/defs.h"
+#include "paimon/format/parquet/parquet_file_batch_reader.h"
+#include "paimon/format/parquet/parquet_format_defs.h"
+#include "paimon/format/parquet/parquet_format_writer.h"
+#include "paimon/fs/file_system.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/testing/utils/read_result_collector.h"
+#include "paimon/testing/utils/testharness.h"
+#include "parquet/arrow/writer.h"
+#include "parquet/properties.h"
+
+namespace paimon {
+class Predicate;
+}  // namespace paimon
+
+namespace paimon::parquet::test {
+
+class ParquetVectorIoTest : public ::testing::Test {
+ public:
+    void SetUp() override {
+        pool_ = GetDefaultPool();
+        arrow_pool_ = GetArrowPool(pool_);
+        dir_ = paimon::test::UniqueTestDirectory::Create();
+        ASSERT_TRUE(dir_);
+        fs_ = dir_->GetFileSystem();
+    }
+
+    void WriteAndCheck(const std::string& file_name,
+                       const std::shared_ptr<arrow::StructType>& write_type,
+                       const std::shared_ptr<arrow::StructType>& read_type,
+                       const std::string& json) {
+        std::string file_path = dir_->Str() + "/" + file_name;
+        WriteWithFormatWriter(file_path, write_type, json, /*max_row_group_length=*/1024);
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        auto file_type =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+        std::shared_ptr<arrow::DataType> physical_value_type = file_type->field(1)->type();
+        if (physical_value_type->id() == arrow::Type::STRUCT) {
+            physical_value_type = physical_value_type->field(0)->type();
+        }
+        ASSERT_EQ(physical_value_type->id(), arrow::Type::LIST);
+
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*arrow::schema(read_type->fields()), c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), /*predicate=*/nullptr,
+                                               /*selection_bitmap=*/std::nullopt));
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+
+        arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+            arrow::ipc::internal::json::ArrayFromJSON(read_type, json);
+        ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+        std::shared_ptr<arrow::Array> expected = std::move(expected_result).ValueOrDie();
+        ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(expected)->Equals(actual))
+            << actual->ToString();
+    }
+
+    /// Writes the JSON rows through the Paimon Parquet writer, which stores VECTOR values as
+    /// Parquet LIST.
+    void WriteWithFormatWriter(const std::string& file_path,
+                               const std::shared_ptr<arrow::StructType>& write_type,
+                               const std::string& json, int64_t max_row_group_length) {
+        arrow::Result<std::shared_ptr<arrow::Array>> write_array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(write_type, json);
+        ASSERT_TRUE(write_array_result.ok()) << write_array_result.status().ToString();
+        std::shared_ptr<arrow::Array> write_array = std::move(write_array_result).ValueOrDie();
+        auto c_array = std::make_unique<ArrowArray>();
+        ASSERT_TRUE(arrow::ExportArray(*write_array, c_array.get()).ok());
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        ::parquet::WriterProperties::Builder properties_builder;
+        properties_builder.max_row_group_length(max_row_group_length);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFormatWriter> writer,
+            ParquetFormatWriter::Create(out, arrow::schema(write_type->fields()),
+                                        properties_builder.build(),
+                                        DEFAULT_PARQUET_WRITER_MAX_MEMORY_USE, arrow_pool_));
+        ASSERT_OK(writer->AddBatch(c_array.get()));
+        ASSERT_OK(writer->Finish());
+        ASSERT_OK(out->Close());
+    }
+
+    /// Writes `array` with the plain Arrow Parquet writer, so FixedSizeList columns keep their
+    /// Arrow type in the file schema the way Paimon Rust and Python writers store them.
+    void WriteWithArrowWriter(const std::string& file_path,
+                              const std::shared_ptr<arrow::StructType>& type,
+                              const std::string& json) {
+        arrow::Result<std::shared_ptr<arrow::Array>> array_result =

Review Comment:
   `WriteWithArrowWriter` currently cannot guarantee that the data will be read back as `FixedSizeList`. If we want to guarantee that arrow::parquet reads it back as `FixedSizeList`, wouldn’t we need to store the schema.
   
   ```cpp
   ::parquet::WriterProperties::Builder properties_builder;
   auto arrow_properties =
       ::parquet::ArrowWriterProperties::Builder()
           .store_schema()
           ->build();
   
   arrow::Status status = ::parquet::arrow::WriteTable(
       *table,
       arrow_pool_.get(),
       arrow_out,
       /*chunk_size=*/1024,
       properties_builder.build(),
       arrow_properties);
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "ChaomingZhangCN (via GitHub)" <gi...@apache.org>.
ChaomingZhangCN commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3800435027


##########
src/paimon/format/parquet/parquet_format_writer.h:
##########
@@ -72,7 +72,8 @@ class ParquetFormatWriter : public FormatWriter {
     ParquetFormatWriter(std::unique_ptr<::parquet::arrow::FileWriter> writer,
                         const std::shared_ptr<ArrowOutputStreamAdapter>& out,
                         const std::shared_ptr<arrow::Schema>& schema, uint64_t max_memory_use,
-                        const std::shared_ptr<arrow::MemoryPool>& pool);
+                        const std::shared_ptr<arrow::MemoryPool>& pool,
+                        bool needs_vector_conversion);

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3801367008


##########
src/paimon/format/parquet/parquet_vector_io_test.cpp:
##########
@@ -0,0 +1,393 @@
+/*
+ * 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 <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/ipc/json_simple.h"
+#include "gtest/gtest.h"
+#include "paimon/common/utils/arrow/arrow_input_stream_adapter.h"
+#include "paimon/common/utils/arrow/arrow_output_stream_adapter.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/core/io/vector_file_batch_reader.h"
+#include "paimon/defs.h"
+#include "paimon/format/parquet/parquet_file_batch_reader.h"
+#include "paimon/format/parquet/parquet_format_defs.h"
+#include "paimon/format/parquet/parquet_format_writer.h"
+#include "paimon/fs/file_system.h"
+#include "paimon/memory/memory_pool.h"
+#include "paimon/predicate/literal.h"
+#include "paimon/predicate/predicate_builder.h"
+#include "paimon/testing/utils/read_result_collector.h"
+#include "paimon/testing/utils/testharness.h"
+#include "parquet/arrow/writer.h"
+#include "parquet/properties.h"
+
+namespace paimon {
+class Predicate;
+}  // namespace paimon
+
+namespace paimon::parquet::test {
+
+class ParquetVectorIoTest : public ::testing::Test {
+ public:
+    void SetUp() override {
+        pool_ = GetDefaultPool();
+        arrow_pool_ = GetArrowPool(pool_);
+        dir_ = paimon::test::UniqueTestDirectory::Create();
+        ASSERT_TRUE(dir_);
+        fs_ = dir_->GetFileSystem();
+    }
+
+    void WriteAndCheck(const std::string& file_name,
+                       const std::shared_ptr<arrow::StructType>& write_type,
+                       const std::shared_ptr<arrow::StructType>& read_type,
+                       const std::string& json) {
+        std::string file_path = dir_->Str() + "/" + file_name;
+        WriteWithFormatWriter(file_path, write_type, json, /*max_row_group_length=*/1024);
+
+        std::shared_ptr<arrow::StructType> file_type;
+        ReadFileType(file_path, &file_type);
+        std::shared_ptr<arrow::DataType> physical_value_type = file_type->field(1)->type();
+        if (physical_value_type->id() == arrow::Type::STRUCT) {
+            physical_value_type = physical_value_type->field(0)->type();
+        }
+        ASSERT_EQ(physical_value_type->id(), arrow::Type::LIST);
+
+        std::unique_ptr<FileBatchReader> vector_reader;
+        CreateVectorReader(file_path, arrow::schema(read_type->fields()), /*predicate=*/nullptr,
+                           /*options=*/{}, /*batch_size=*/10, &vector_reader);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+
+        arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+            arrow::ipc::internal::json::ArrayFromJSON(read_type, json);
+        ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+        std::shared_ptr<arrow::Array> expected = std::move(expected_result).ValueOrDie();
+        ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(expected)->Equals(actual))
+            << actual->ToString();
+    }
+
+    /// Writes the JSON rows through the Paimon Parquet writer, which stores VECTOR values as
+    /// Parquet LIST.
+    void WriteWithFormatWriter(const std::string& file_path,
+                               const std::shared_ptr<arrow::StructType>& write_type,
+                               const std::string& json, int64_t max_row_group_length) {
+        arrow::Result<std::shared_ptr<arrow::Array>> write_array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(write_type, json);
+        ASSERT_TRUE(write_array_result.ok()) << write_array_result.status().ToString();
+        std::shared_ptr<arrow::Array> write_array = std::move(write_array_result).ValueOrDie();
+        auto c_array = std::make_unique<ArrowArray>();
+        ASSERT_TRUE(arrow::ExportArray(*write_array, c_array.get()).ok());
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        ::parquet::WriterProperties::Builder properties_builder;
+        properties_builder.max_row_group_length(max_row_group_length);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFormatWriter> writer,
+            ParquetFormatWriter::Create(out, arrow::schema(write_type->fields()),
+                                        properties_builder.build(),
+                                        DEFAULT_PARQUET_WRITER_MAX_MEMORY_USE, arrow_pool_));
+        ASSERT_OK(writer->AddBatch(c_array.get()));
+        ASSERT_OK(writer->Finish());
+        ASSERT_OK(out->Close());
+    }
+
+    /// Writes `array` with the plain Arrow Parquet writer, storing the Arrow schema so that
+    /// FixedSizeList columns are read back as FixedSizeList, the way Paimon Rust and Python
+    /// writers store them.
+    void WriteWithArrowWriter(const std::string& file_path,
+                              const std::shared_ptr<arrow::StructType>& type,
+                              const std::string& json) {
+        arrow::Result<std::shared_ptr<arrow::Array>> array_result =
+            arrow::ipc::internal::json::ArrayFromJSON(type, json);
+        ASSERT_TRUE(array_result.ok()) << array_result.status().ToString();
+        arrow::Result<std::shared_ptr<arrow::RecordBatch>> batch_result =
+            arrow::RecordBatch::FromStructArray(std::move(array_result).ValueOrDie());
+        ASSERT_TRUE(batch_result.ok()) << batch_result.status().ToString();
+        arrow::Result<std::shared_ptr<arrow::Table>> table_result =
+            arrow::Table::FromRecordBatches({std::move(batch_result).ValueOrDie()});
+        ASSERT_TRUE(table_result.ok()) << table_result.status().ToString();
+
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<OutputStream> out,
+                             fs_->Create(file_path, /*overwrite=*/false));
+        auto arrow_out = std::make_shared<ArrowOutputStreamAdapter>(out);
+        ::parquet::WriterProperties::Builder properties_builder;
+        std::shared_ptr<::parquet::ArrowWriterProperties> arrow_properties =
+            ::parquet::ArrowWriterProperties::Builder().store_schema()->build();
+        arrow::Status status = ::parquet::arrow::WriteTable(
+            *std::move(table_result).ValueOrDie(), arrow_pool_.get(), arrow_out,
+            /*chunk_size=*/1024, properties_builder.build(), arrow_properties);
+        ASSERT_TRUE(status.ok()) << status.ToString();
+        ASSERT_OK(out->Close());
+    }
+
+    void ReadFileType(const std::string& file_path,
+                      std::shared_ptr<arrow::StructType>* file_type_out) {
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), /*options=*/{},
+                                           /*batch_size=*/10, /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        ASSERT_OK_AND_ASSIGN(std::unique_ptr<ArrowSchema> c_file_schema, reader->GetFileSchema());
+        arrow::Result<std::shared_ptr<arrow::DataType>> file_type_result =
+            arrow::ImportType(c_file_schema.get());
+        ASSERT_TRUE(file_type_result.ok()) << file_type_result.status().ToString();
+        *file_type_out =
+            checked_pointer_cast<arrow::StructType>(std::move(file_type_result).ValueOrDie());
+    }
+
+    void CreateVectorReader(const std::string& file_path,
+                            const std::shared_ptr<arrow::Schema>& read_schema,
+                            const std::shared_ptr<Predicate>& predicate,
+                            const std::map<std::string, std::string>& options, int32_t batch_size,
+                            std::unique_ptr<FileBatchReader>* vector_reader_out) {
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<InputStream> in, fs_->Open(file_path));
+        ASSERT_OK_AND_ASSIGN(int64_t length, in->Length());
+        auto in_stream = std::make_shared<ArrowInputStreamAdapter>(in, length, arrow_pool_);
+        ASSERT_OK_AND_ASSIGN(
+            std::unique_ptr<ParquetFileBatchReader> reader,
+            ParquetFileBatchReader::Create(std::move(in_stream), options, batch_size,
+                                           /*file_metadata=*/nullptr,
+                                           /*storage_read_bytes=*/nullptr, arrow_pool_));
+        std::unique_ptr<FileBatchReader> vector_reader =
+            std::make_unique<VectorFileBatchReader>(std::move(reader), pool_);
+        auto c_schema = std::make_unique<ArrowSchema>();
+        ASSERT_TRUE(arrow::ExportSchema(*read_schema, c_schema.get()).ok());
+        ASSERT_OK(vector_reader->SetReadSchema(c_schema.get(), predicate,
+                                               /*selection_bitmap=*/std::nullopt));
+        *vector_reader_out = std::move(vector_reader);
+    }
+
+    void ReadFixtureAndCheck(
+        const std::string& file_name, arrow::Type::type expected_file_vector_type,
+        int32_t vector_length, const std::vector<int32_t>& expected_ids,
+        const std::vector<std::optional<std::vector<float>>>& expected_vectors) {
+        std::string file_path =
+            paimon::test::GetDataDir() + "/parquet/vector_compatibility/" + file_name;
+        std::shared_ptr<arrow::StructType> file_type;
+        ReadFileType(file_path, &file_type);
+        std::shared_ptr<arrow::Field> file_vector_field = file_type->GetFieldByName("embedding");
+        ASSERT_TRUE(file_vector_field);
+        ASSERT_EQ(file_vector_field->type()->id(), expected_file_vector_type);
+        std::shared_ptr<arrow::Field> file_id_field = file_type->GetFieldByName("id");
+        ASSERT_TRUE(file_id_field);
+
+        auto vector_type = arrow::fixed_size_list(
+            arrow::field("element", arrow::float32(), /*nullable=*/false), vector_length);
+        auto logical_schema =
+            arrow::schema({file_id_field, file_vector_field->WithType(vector_type)});
+        std::unique_ptr<FileBatchReader> vector_reader;
+        CreateVectorReader(file_path, logical_schema, /*predicate=*/nullptr, /*options=*/{},
+                           /*batch_size=*/10, &vector_reader);
+        ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                             paimon::test::ReadResultCollector::CollectResult(vector_reader.get()));
+        ASSERT_EQ(actual->num_chunks(), 1);
+        ASSERT_EQ(actual->type()->id(), arrow::Type::STRUCT);
+        auto struct_array = checked_pointer_cast<arrow::StructArray>(actual->chunk(0));
+        std::shared_ptr<arrow::Array> id_field = struct_array->GetFieldByName("id");
+        std::shared_ptr<arrow::Array> vector_field = struct_array->GetFieldByName("embedding");
+        ASSERT_TRUE(id_field);
+        ASSERT_TRUE(vector_field);
+        ASSERT_EQ(id_field->type_id(), arrow::Type::INT32);
+        ASSERT_EQ(vector_field->type_id(), arrow::Type::FIXED_SIZE_LIST);
+        auto ids = checked_pointer_cast<arrow::Int32Array>(id_field);
+        auto vector_array = checked_pointer_cast<arrow::FixedSizeListArray>(vector_field);
+        ASSERT_EQ(ids->length(), static_cast<int64_t>(expected_ids.size()));
+        ASSERT_EQ(vector_array->length(), static_cast<int64_t>(expected_vectors.size()));
+        for (int64_t i = 0; i < ids->length(); ++i) {
+            ASSERT_FALSE(ids->IsNull(i));
+            ASSERT_EQ(ids->Value(i), expected_ids[i]);
+            if (!expected_vectors[i]) {
+                ASSERT_TRUE(vector_array->IsNull(i));
+                continue;
+            }
+            ASSERT_FALSE(vector_array->IsNull(i));
+            ASSERT_EQ(vector_array->value_length(i),
+                      static_cast<int64_t>(expected_vectors[i]->size()));
+            auto values = checked_pointer_cast<arrow::FloatArray>(vector_array->value_slice(i));
+            for (int64_t j = 0; j < values->length(); ++j) {
+                ASSERT_FALSE(values->IsNull(j));
+                ASSERT_FLOAT_EQ(values->Value(j), expected_vectors[i].value()[j]);
+            }
+        }
+    }
+
+ private:
+    std::shared_ptr<MemoryPool> pool_;
+    std::shared_ptr<arrow::MemoryPool> arrow_pool_;
+    std::shared_ptr<FileSystem> fs_;
+    std::unique_ptr<paimon::test::UniqueTestDirectory> dir_;
+};
+
+TEST_F(ParquetVectorIoTest, WriteAndReadVector) {
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float32(), /*nullable=*/false), 3);
+    auto struct_type = checked_pointer_cast<arrow::StructType>(arrow::struct_(
+        {arrow::field("id", arrow::int32()), arrow::field("embedding", vector_type)}));
+    WriteAndCheck("vector.parquet", struct_type, struct_type,
+                  R"([[1, [1.0, 2.0, 3.0]], [2, null], [3, [4.0, 5.0, 6.0]]])");
+}
+
+TEST_F(ParquetVectorIoTest, ReadOrdinaryParquetListAsVector) {
+    auto physical_type = checked_pointer_cast<arrow::StructType>(
+        arrow::struct_({arrow::field("id", arrow::int32()),
+                        arrow::field("embedding", arrow::list(arrow::float32()))}));
+    auto logical_type = checked_pointer_cast<arrow::StructType>(arrow::struct_({
+        arrow::field("id", arrow::int32()),
+        arrow::field("embedding", arrow::fixed_size_list(arrow::float32(), 3)),
+    }));
+    WriteAndCheck("list.parquet", physical_type, logical_type,
+                  R"([[1, [1.0, 2.0, 3.0]], [2, null], [3, [4.0, 5.0, 6.0]]])");
+}
+
+TEST_F(ParquetVectorIoTest, WriteAndReadNestedDoubleVector) {
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float64(), /*nullable=*/false), 2);
+    auto struct_type = checked_pointer_cast<arrow::StructType>(arrow::struct_({
+        arrow::field("id", arrow::int32()),
+        arrow::field("payload", arrow::struct_({arrow::field("embedding", vector_type),
+                                                arrow::field("history", arrow::list(vector_type)),
+                                                arrow::field("by_name", arrow::map(arrow::utf8(),
+                                                                                   vector_type))})),
+    }));
+    WriteAndCheck("nested-vector.parquet", struct_type, struct_type,
+                  R"([[1, [[1.0, 2.0], [[3.0, 4.0], null], [["a", [5.0, 6.0]]]]],
+                       [2, [null, null, [["b", null]]]]])");
+}
+
+// Vectors nested in a LIST keep their Arrow type when a third-party writer stores them as
+// FixedSizeList, so the Parquet reader must accept a FixedSizeList read type as well.
+TEST_F(ParquetVectorIoTest, ReadNestedFixedSizeListFile) {
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float32(), /*nullable=*/false), 3);
+    auto logical_type = checked_pointer_cast<arrow::StructType>(arrow::struct_({
+        arrow::field("id", arrow::int32()),
+        arrow::field("history", arrow::list(vector_type)),
+    }));
+    const std::string json = R"([[1, [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]], [2, []]])";
+    std::string file_path = dir_->Str() + "/nested-fixed-size-list.parquet";
+    WriteWithArrowWriter(file_path, logical_type, json);
+
+    // Without this the file would expose the column as list<list<float>> and the read would take
+    // the LIST to VECTOR conversion instead of the nested FixedSizeList path under test.
+    std::shared_ptr<arrow::StructType> file_type;
+    ReadFileType(file_path, &file_type);
+    std::shared_ptr<arrow::Field> file_history_field = file_type->GetFieldByName("history");
+    ASSERT_TRUE(file_history_field);
+    ASSERT_EQ(file_history_field->type()->id(), arrow::Type::LIST);
+    ASSERT_EQ(file_history_field->type()->field(0)->type()->id(), arrow::Type::FIXED_SIZE_LIST);
+
+    std::unique_ptr<FileBatchReader> reader;
+    CreateVectorReader(file_path, arrow::schema(logical_type->fields()), /*predicate=*/nullptr,
+                       /*options=*/{}, /*batch_size=*/10, &reader);
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                         paimon::test::ReadResultCollector::CollectResult(reader.get()));
+    arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+        arrow::ipc::internal::json::ArrayFromJSON(logical_type, json);
+    ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+    ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(std::move(expected_result).ValueOrDie())
+                    ->Equals(actual))
+        << actual->ToString();
+}
+
+TEST_F(ParquetVectorIoTest, ReadVectorWithPredicatePushdown) {
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float32(), /*nullable=*/false), 3);
+    auto logical_type = checked_pointer_cast<arrow::StructType>(arrow::struct_(
+        {arrow::field("id", arrow::int32()), arrow::field("embedding", vector_type)}));
+    // One row per row group, so the predicate on `id` prunes row groups while reading.
+    std::string file_path = dir_->Str() + "/vector-predicate.parquet";
+    WriteWithFormatWriter(file_path, logical_type,
+                          R"([[1, [1.0, 2.0, 3.0]], [2, null], [3, [4.0, 5.0, 6.0]],
+                              [4, [7.0, 8.0, 9.0]]])",
+                          /*max_row_group_length=*/1);
+
+    std::shared_ptr<Predicate> predicate = PredicateBuilder::GreaterThan(
+        /*field_index=*/0, /*field_name=*/"id", FieldType::INT, Literal(2));
+    std::unique_ptr<FileBatchReader> reader;
+    CreateVectorReader(file_path, arrow::schema(logical_type->fields()), predicate,
+                       /*options=*/{}, /*batch_size=*/10, &reader);
+    ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::ChunkedArray> actual,
+                         paimon::test::ReadResultCollector::CollectResult(reader.get()));
+    arrow::Result<std::shared_ptr<arrow::Array>> expected_result =
+        arrow::ipc::internal::json::ArrayFromJSON(
+            logical_type, R"([[3, [4.0, 5.0, 6.0]], [4, [7.0, 8.0, 9.0]]])");
+    ASSERT_TRUE(expected_result.ok()) << expected_result.status().ToString();
+    ASSERT_TRUE(std::make_shared<arrow::ChunkedArray>(std::move(expected_result).ValueOrDie())
+                    ->Equals(actual))
+        << actual->ToString();
+}
+
+TEST_F(ParquetVectorIoTest, ReadJavaFixture) {
+    ReadFixtureAndCheck(
+        "java_vector.parquet", arrow::Type::LIST, /*vector_length=*/2,
+        /*expected_ids=*/{0, 1, 2, 3, 4},
+        /*expected_vectors=*/
+        {{{0.0f, 0.0f}}, {{1.0f, 0.0f}}, {{2.0f, 0.0f}}, {{3.0f, 0.0f}}, {{4.0f, 0.0f}}});
+}
+
+TEST_F(ParquetVectorIoTest, ReadRustFixture) {
+    ReadFixtureAndCheck("rust_vector.parquet", arrow::Type::FIXED_SIZE_LIST,
+                        /*vector_length=*/3, /*expected_ids=*/{1, 2, 3},
+                        /*expected_vectors=*/
+                        {{{1.0f, 2.0f, 3.0f}}, {{7.0f, 8.0f, 9.0f}}, {{4.0f, 5.0f, 6.0f}}});
+}
+
+TEST_F(ParquetVectorIoTest, ReadNullableJavaFixture) {
+    ReadFixtureAndCheck("java_vector_nullable.parquet", arrow::Type::LIST, /*vector_length=*/3,
+                        /*expected_ids=*/{1, 2, 3},
+                        /*expected_vectors=*/
+                        {{{1.0f, 2.0f, 3.0f}}, std::nullopt, {{4.0f, 5.0f, 6.0f}}});
+}
+
+// A writer that stores the Arrow schema, such as Paimon Rust or Python, exposes the VECTOR column
+// as FixedSizeList. Arrow 17 cannot read a null value from such a column: Parquet stores a null
+// list slot with no values, while FixedSizeListReader::AssembleArray in
+// parquet/arrow/reader.cc requires every slot to span exactly `list_size` values.
+//
+// TODO(ChaomingZhangCN): Turn this into a read check once Arrow is upgraded.
+TEST_F(ParquetVectorIoTest, ReadNullableRustFixtureIsUnsupported) {
+    std::string file_path =
+        paimon::test::GetDataDir() + "/parquet/vector_compatibility/rust_vector_nullable.parquet";
+    std::shared_ptr<arrow::StructType> file_type;
+    ReadFileType(file_path, &file_type);
+    std::shared_ptr<arrow::Field> file_vector_field = file_type->GetFieldByName("embedding");
+    ASSERT_TRUE(file_vector_field);
+    ASSERT_EQ(file_vector_field->type()->id(), arrow::Type::FIXED_SIZE_LIST);
+
+    std::unique_ptr<FileBatchReader> reader;
+    CreateVectorReader(file_path, arrow::schema(file_type->fields()), /*predicate=*/nullptr,
+                       /*options=*/{}, /*batch_size=*/10, &reader);
+    ASSERT_NOK_WITH_MSG(paimon::test::ReadResultCollector::CollectResult(reader.get()),
+                        "Expected all lists to be of size=3");

Review Comment:
   LGTM. For now, since the Arrow fix has landed on master but has not yet been released on the release branch, we plan to keep this PR as-is and not support it for the time being. Later, we can update arrow.patch to temporarily cherry-pick the fix onto the current Arrow 17 we are using, so that Rust-based file can read it correctly.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "ChaomingZhangCN (via GitHub)" <gi...@apache.org>.
ChaomingZhangCN commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3811043458


##########
src/paimon/common/utils/arrow/vector_utils.h:
##########


Review Comment:
   I'll remove it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3788370161


##########
src/paimon/core/schema/table_schema.cpp:
##########
@@ -118,6 +118,14 @@ Result<std::shared_ptr<arrow::Field>> TableSchema::AssignFieldIdsRecursively(
                                                          /*set_field_id=*/false, field_id));
         return arrow::field(field->name(), arrow::list(new_value_field), field->nullable(),
                             metadata);
+    } else if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        auto vector_type = std::static_pointer_cast<arrow::FixedSizeListType>(field->type());
+        PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<arrow::Field> new_value_field,
+                               AssignFieldIdsRecursively(vector_type->value_field(),
+                                                         /*set_field_id=*/false, field_id));
+        return arrow::field(field->name(),
+                            arrow::fixed_size_list(new_value_field, vector_type->list_size()),

Review Comment:
   I found a blocker.
   
   ### [Blocking] Reject VECTOR fields in primary-key tables until merge-tree support is implemented
   
   This PR keeps VECTOR columns as Arrow `FixedSizeList` throughout the framework and converts them to Parquet `LIST` only at the Parquet writer boundary. Therefore, supporting VECTOR in primary-key tables requires the merge-tree and row-based framework paths to understand `FIXED_SIZE_LIST`.
   
   The current integration test only covers an append-only table. Primary-key tables containing a VECTOR value column are currently accepted by schema validation but fail in several deterministic places:
   
   1. `InMemorySortBuffer::EstimateMemoryUse` has no `FIXED_SIZE_LIST` branch, so a PK write fails while buffering the first batch.
   2. `RowToArrowArrayConverter` does not support `FixedSizeListBuilder` in `AppendField`, `Reserve`, or `Accumulate`. This blocks PK flush, compaction, spill, and PK scan projection.
   3. `ColumnarRow`, `ColumnarRowRef`, and `ColumnarArray` assume `GetArray` always wraps an Arrow `ListArray`. They cannot expose values backed by a `FixedSizeListArray`.
   
   There are also missing branches in additional framework components:
   
   - `InternalRow::CreateFieldGetter` does not recognize VECTOR.
   - `BinarySerializerUtils::WriteBinaryArray` casts the type directly to `arrow::ListType`.
   - `RowCompactedSerializer` has no VECTOR reader or writer, affecting lookup persistence.
   - Partial-update and aggregation merge functions create field getters for every value field and therefore cannot be initialized when the schema contains VECTOR.
   - `CastedRow` also lacks VECTOR handling. This one is not strictly PK-only and may affect schema/stats evolution paths as well.
   
   Most of the above work is specific to primary-key tables and can reasonably be implemented in a follow-up PR. However, this PR must not expose a schema configuration that is known to fail at runtime.
   
   Please update `SchemaValidation::ValidateVectorFields` to reject any table that both:
   
   - contains a VECTOR field, including a nested VECTOR field; and
   - has a non-empty primary-key definition.
   
   For example:
   
   ```cpp
   if (has_vector && !schema.PrimaryKeys().empty()) {
       return Status::NotImplemented(
           "VECTOR fields in primary-key tables are not implemented yet.");
   }
   ```
   
   The existing test only verifies that the VECTOR column itself cannot be used as a primary key. Please also add a test for a schema such as:
   
   ```text
   id BIGINT,
   embedding VECTOR<FLOAT, 3>,
   PRIMARY KEY (id)
   ```
   
   and verify that schema validation rejects it.
   
   The documentation should likewise state that the current implementation supports VECTOR only in append-only Parquet tables. Full primary-key support, including write buffering, row-to-column conversion, reads, compaction, spill, lookup, and merge engines, can then be added and tested in a second PR.



##########
src/paimon/format/parquet/parquet_file_batch_reader.cpp:
##########
@@ -762,7 +783,7 @@ Status ParquetFileBatchReader::CollectLeafIndices(const std::shared_ptr<arrow::D
 void ParquetFileBatchReader::SkipLeafIndices(const std::shared_ptr<arrow::DataType>& file_type,
                                              int32_t* leaf_index) {
     if (file_type->id() == arrow::Type::STRUCT || file_type->id() == arrow::Type::LIST ||
-        file_type->id() == arrow::Type::MAP) {

Review Comment:
   I looked into the Rust and Python implementations, and I think we could move `ParquetVectorConverter::ConvertToReadType` — specifically the `list -> fixed size list` conversion — up into the framework layer, and introduce a generic reader wrapper on top of `ParquetFileBatchReader`.
   
   My suggestion would be:
   - convert the schema during `SetReadSchema`, and
   - convert the data during `NextBatch`.
   
   You could refer to `CompleteRowTrackingFieldsBatchReader` for a similar pattern.
   
   This would reduce the amount of change needed in the Parquet plugin layer. Some external engines use their own Parquet plugin implementations, and ideally we want plugin authors to make as few changes as possible when adding vector support.
   
   For the write path, could we just pass `fixed size list` directly to the Parquet writer? In theory, Parquet does not distinguish between `fixed size list` and `list`, and Arrow should be able to handle the conversion properly.



##########
src/paimon/format/parquet/parquet_file_batch_reader.cpp:
##########
@@ -65,6 +66,13 @@ class Predicate;
 namespace paimon::parquet {
 
 namespace {
+std::shared_ptr<arrow::DataType> GetListElementType(const std::shared_ptr<arrow::DataType>& type) {
+    if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        return static_cast<const arrow::FixedSizeListType&>(*type).value_type();
+    }
+    return static_cast<const arrow::ListType&>(*type).value_type();
+}

Review Comment:
   We recently made some conventions around casts. In the latest code, please use `paimon::check_cast` instead of `static_cast` (for more details  please refer to `docs/code-style.md`).



##########
test/inte/write_and_read_inte_test.cpp:
##########
@@ -309,6 +309,66 @@ TEST_P(WriteAndReadInteTest, TestAppendSimple) {
     ASSERT_TRUE(success);
 }
 
+TEST_P(WriteAndReadInteTest, TestAppendVector) {
+    auto [file_format, file_system] = GetParam();
+    if (file_format != "parquet") {
+        return;
+    }
+
+    auto vector_type =
+        arrow::fixed_size_list(arrow::field("item", arrow::float32(), /*nullable=*/false), 3);
+    arrow::FieldVector fields = {arrow::field("id", arrow::int32()),
+                                 arrow::field("embedding", vector_type)};
+    std::map<std::string, std::string> options = {
+        {Options::MANIFEST_FORMAT, "avro"},  {Options::FILE_FORMAT, file_format},
+        {Options::TARGET_FILE_SIZE, "1024"}, {Options::BUCKET, "-1"},
+        {Options::FILE_SYSTEM, file_system},
+    };
+    if (file_system == "jindo") {
+        options = AddOptionsForJindo(options);
+    }
+    ASSERT_OK_AND_ASSIGN(auto helper,
+                         TestHelper::Create(test_dir_, arrow::schema(fields), /*partition_keys=*/{},
+                                            /*primary_keys=*/{}, options,
+                                            /*is_streaming_mode=*/false));
+    arrow::Int32Builder ids_builder;
+    ASSERT_TRUE(ids_builder.AppendValues({1, 2, 3}).ok());
+    std::shared_ptr<arrow::Array> ids;

Review Comment:
   For the tests, could you please try to use JSON-style expressions to construct the source or expected arrays, as they’re easier to read and understand.



##########
src/paimon/common/types/data_type_json_parser.cpp:
##########
@@ -607,6 +615,34 @@ Result<std::shared_ptr<arrow::DataType>> TokenParser::ParseTimestampLtzType() {
     return ts_type;
 }
 
+Result<std::shared_ptr<arrow::DataType>> TokenParser::ParseVectorType() {
+    PAIMON_RETURN_NOT_OK(NextToken(TokenType::BEGIN_SUBTYPE));
+    bool element_nullable = true;
+    AtomicTypeAttributes element_attributes;
+    PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<arrow::DataType> element_type,
+                           ParseTypeWithNullability(&element_nullable, &element_attributes));
+    if (element_attributes.is_blob || element_attributes.is_variant ||
+        !VectorType::IsValidElementType(element_type)) {
+        return Status::Invalid(
+            fmt::format("Invalid element type for vector: {}", element_type->ToString()));
+    }
+    PAIMON_RETURN_NOT_OK(NextToken(TokenType::LIST_SEPARATOR));
+    PAIMON_RETURN_NOT_OK(NextToken(TokenType::LITERAL_INT));
+    const std::string& length_token = GetToken().value;
+    int64_t length = 0;
+    const auto [end, error] =
+        std::from_chars(length_token.data(), length_token.data() + length_token.size(), length);
+    if (error != std::errc() || end != length_token.data() + length_token.size() || length < 1 ||
+        length > std::numeric_limits<int32_t>::max()) {
+        return Status::Invalid(
+            fmt::format("Vector length must be between 1 and {} (both inclusive), but was {}",
+                        std::numeric_limits<int32_t>::max(), length_token));
+    }

Review Comment:
   Could we use `StringUtils::StringToValue` here?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3793373684


##########
src/paimon/core/io/vector_file_batch_reader.cpp:
##########
@@ -0,0 +1,325 @@
+/*
+ * 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/io/vector_file_batch_reader.h"
+
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "arrow/array.h"
+#include "arrow/array/array_nested.h"
+#include "arrow/array/builder_primitive.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/compute/api.h"
+#include "arrow/type.h"
+#include "fmt/format.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/status.h"
+
+namespace paimon {
+namespace {
+
+bool ContainsVectorType(const std::shared_ptr<arrow::DataType>& type) {
+    if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        return true;
+    }
+    for (const auto& field : type->fields()) {
+        if (ContainsVectorType(field->type())) {
+            return true;
+        }
+    }
+    return false;
+}
+
+std::shared_ptr<arrow::DataType> GetPhysicalReadType(
+    const std::shared_ptr<arrow::DataType>& logical_type) {
+    switch (logical_type->id()) {
+        case arrow::Type::FIXED_SIZE_LIST: {
+            const auto& vector_type = checked_cast<const arrow::FixedSizeListType&>(*logical_type);
+            return arrow::list(
+                vector_type.value_field()->WithType(GetPhysicalReadType(vector_type.value_type())));
+        }
+        case arrow::Type::STRUCT: {
+            arrow::FieldVector fields;

Review Comment:
   One thing to note here: for data written by Java, vectors are indeed read back as `list`, while for data written by Python/Rust, vectors seem to already come back as `fixed size list`.
   
   So I’d suggest narrowing this conversion to only the case where the **file schema is `list`** but the **read schema is `fixed size list`**.
   
   Also, could you please add test data generated from both Rust and Java for vector columns, and verify that C++ can read them correctly?



##########
src/paimon/core/io/vector_file_batch_reader.cpp:
##########
@@ -0,0 +1,325 @@
+/*
+ * 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/io/vector_file_batch_reader.h"
+
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "arrow/array.h"
+#include "arrow/array/array_nested.h"
+#include "arrow/array/builder_primitive.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/compute/api.h"
+#include "arrow/type.h"
+#include "fmt/format.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/status.h"
+
+namespace paimon {
+namespace {
+
+bool ContainsVectorType(const std::shared_ptr<arrow::DataType>& type) {
+    if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        return true;
+    }
+    for (const auto& field : type->fields()) {
+        if (ContainsVectorType(field->type())) {
+            return true;
+        }
+    }
+    return false;
+}
+
+std::shared_ptr<arrow::DataType> GetPhysicalReadType(
+    const std::shared_ptr<arrow::DataType>& logical_type) {
+    switch (logical_type->id()) {
+        case arrow::Type::FIXED_SIZE_LIST: {
+            const auto& vector_type = checked_cast<const arrow::FixedSizeListType&>(*logical_type);
+            return arrow::list(
+                vector_type.value_field()->WithType(GetPhysicalReadType(vector_type.value_type())));
+        }
+        case arrow::Type::STRUCT: {
+            arrow::FieldVector fields;
+            fields.reserve(logical_type->num_fields());
+            for (const auto& field : logical_type->fields()) {
+                fields.push_back(field->WithType(GetPhysicalReadType(field->type())));
+            }
+            return arrow::struct_(fields);
+        }
+        case arrow::Type::LIST:
+            return arrow::list(logical_type->field(0)->WithType(
+                GetPhysicalReadType(logical_type->field(0)->type())));
+        case arrow::Type::MAP: {
+            const auto& map_type = checked_cast<const arrow::MapType&>(*logical_type);
+            return std::make_shared<arrow::MapType>(
+                map_type.key_field()->WithType(GetPhysicalReadType(map_type.key_type())),
+                map_type.item_field()->WithType(GetPhysicalReadType(map_type.item_type())),
+                map_type.keys_sorted());
+        }
+        default:
+            return logical_type;
+    }
+}
+
+Status ValidateVectorElements(const arrow::FixedSizeListArray& array, int32_t vector_length) {
+    const std::shared_ptr<arrow::Array>& values = array.values();
+    if (values->null_count() == 0) {
+        return Status::OK();
+    }
+    for (int64_t i = 0; i < array.length(); ++i) {
+        if (array.IsNull(i)) {
+            continue;
+        }
+        int64_t value_offset = (array.offset() + i) * vector_length;
+        for (int32_t j = 0; j < vector_length; ++j) {
+            if (values->IsNull(value_offset + j)) {
+                return Status::Invalid("VECTOR cannot contain null elements");
+            }
+        }
+    }
+    return Status::OK();
+}
+
+Result<int64_t> GetIndexCapacity(int64_t row_count, int32_t vector_length) {
+    if (vector_length < 1) {
+        return Status::Invalid("VECTOR length must be positive");
+    }
+    if (row_count > std::numeric_limits<int64_t>::max() / vector_length) {
+        return Status::Invalid("VECTOR values exceed the supported Arrow array length");
+    }
+    return row_count * vector_length;
+}
+
+Result<std::shared_ptr<arrow::Array>> ConvertListToVector(
+    const std::shared_ptr<arrow::Array>& array,
+    const std::shared_ptr<arrow::FixedSizeListType>& read_type, arrow::MemoryPool* pool) {
+    int32_t vector_length = read_type->list_size();
+    if (array->type()->id() == arrow::Type::FIXED_SIZE_LIST) {
+        const auto& source_type = checked_cast<const arrow::FixedSizeListType&>(*array->type());
+        if (source_type.list_size() != vector_length ||
+            !source_type.value_type()->Equals(read_type->value_type())) {
+            return Status::Invalid(fmt::format("VECTOR type mismatch: data {} vs read {}",
+                                               array->type()->ToString(), read_type->ToString()));
+        }
+        const auto& vector_array = checked_cast<const arrow::FixedSizeListArray&>(*array);
+        PAIMON_RETURN_NOT_OK(ValidateVectorElements(vector_array, vector_length));
+        std::shared_ptr<arrow::ArrayData> data = array->data()->Copy();
+        data->type = read_type;
+        return arrow::MakeArray(data);
+    }
+    if (array->type()->id() != arrow::Type::LIST) {
+        return Status::Invalid(
+            fmt::format("Cannot restore VECTOR from type {}", array->type()->ToString()));
+    }
+
+    const auto& list_array = checked_cast<const arrow::ListArray&>(*array);
+    if (!list_array.value_type()->Equals(read_type->value_type())) {
+        return Status::Invalid(fmt::format("VECTOR element type mismatch: data {} vs read {}",
+                                           list_array.value_type()->ToString(),
+                                           read_type->value_type()->ToString()));
+    }
+
+    arrow::Int64Builder indices_builder(pool);
+    PAIMON_ASSIGN_OR_RAISE(int64_t index_capacity,
+                           GetIndexCapacity(list_array.length(), vector_length));
+    PAIMON_RETURN_NOT_OK_FROM_ARROW(indices_builder.Reserve(index_capacity));
+    arrow::BooleanBuilder validity_builder(pool);
+    PAIMON_RETURN_NOT_OK_FROM_ARROW(validity_builder.Reserve(list_array.length()));
+

Review Comment:
   I’m wondering whether we really need to rebuild the array with a builder here to make a deep copy. It seems Arrow provides `arrow::compute::Cast(array, read_type, ...)`, which may support a more lightweight conversion and avoid deep copying where possible.



##########
src/paimon/format/parquet/parquet_vector_converter.cpp:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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/format/parquet/parquet_vector_converter.h"
+
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <vector>
+
+#include "arrow/array.h"
+#include "arrow/array/array_nested.h"
+#include "arrow/array/builder_primitive.h"
+#include "arrow/compute/api.h"
+#include "arrow/type.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/status.h"
+
+namespace paimon::parquet {
+namespace {
+
+bool ContainsVectorType(const std::shared_ptr<arrow::DataType>& type) {
+    if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        return true;
+    }
+    for (const auto& field : type->fields()) {
+        if (ContainsVectorType(field->type())) {
+            return true;
+        }
+    }
+    return false;
+}
+
+Status ValidateVectorElements(const arrow::FixedSizeListArray& array, int32_t vector_length) {
+    const std::shared_ptr<arrow::Array>& values = array.values();
+    if (values->null_count() == 0) {
+        return Status::OK();
+    }
+    for (int64_t i = 0; i < array.length(); ++i) {
+        if (array.IsNull(i)) {
+            continue;
+        }
+        int64_t value_offset = (array.offset() + i) * vector_length;
+        for (int32_t j = 0; j < vector_length; ++j) {
+            if (values->IsNull(value_offset + j)) {
+                return Status::Invalid("VECTOR cannot contain null elements");
+            }
+        }
+    }
+    return Status::OK();
+}
+
+Result<int64_t> GetIndexCapacity(int64_t row_count, int32_t vector_length) {
+    if (vector_length < 1) {
+        return Status::Invalid("VECTOR length must be positive");
+    }
+    if (row_count > std::numeric_limits<int64_t>::max() / vector_length) {
+        return Status::Invalid("VECTOR values exceed the supported Arrow array length");
+    }
+    return row_count * vector_length;
+}
+
+Result<std::shared_ptr<arrow::Array>> ConvertVectorToList(
+    const std::shared_ptr<arrow::Array>& array, arrow::MemoryPool* pool) {
+    const auto& vector_array = checked_cast<const arrow::FixedSizeListArray&>(*array);
+    const auto& vector_type = checked_cast<const arrow::FixedSizeListType&>(*array->type());
+    int32_t vector_length = vector_type.list_size();
+    PAIMON_RETURN_NOT_OK(ValidateVectorElements(vector_array, vector_length));
+
+    arrow::Int32Builder offsets_builder(pool);
+    arrow::Int64Builder indices_builder(pool);
+    arrow::BooleanBuilder validity_builder(pool);
+    PAIMON_RETURN_NOT_OK_FROM_ARROW(offsets_builder.Reserve(vector_array.length() + 1));
+    PAIMON_ASSIGN_OR_RAISE(int64_t index_capacity,
+                           GetIndexCapacity(vector_array.length(), vector_length));
+    PAIMON_RETURN_NOT_OK_FROM_ARROW(indices_builder.Reserve(index_capacity));
+    PAIMON_RETURN_NOT_OK_FROM_ARROW(validity_builder.Reserve(vector_array.length()));
+    PAIMON_RETURN_NOT_OK_FROM_ARROW(offsets_builder.Append(0));
+
+    int32_t offset = 0;
+    for (int64_t i = 0; i < vector_array.length(); ++i) {

Review Comment:
   Similar to the read path, it seems the write path could also use `arrow::cast`. We could validate nulls before casting.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "ChaomingZhangCN (via GitHub)" <gi...@apache.org>.
ChaomingZhangCN commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3800435979


##########
src/paimon/core/schema/schema_validation.cpp:
##########
@@ -648,4 +673,26 @@ Status SchemaValidation::ValidateMapStorageLayout(const TableSchema& schema,
     return Status::OK();
 }
 
+Status SchemaValidation::ValidateVectorFields(const TableSchema& schema,
+                                              const CoreOptions& options) {
+    bool has_vector = false;
+    for (const auto& field : schema.Fields()) {
+        if (ContainsVectorField(field.ArrowField())) {

Review Comment:
   ok



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(parquet): support vector type storage [paimon-cpp]

Posted by "lxy-9602 (via GitHub)" <gi...@apache.org>.
lxy-9602 commented on code in PR #198:
URL: https://github.com/apache/paimon-cpp/pull/198#discussion_r3795124961


##########
src/paimon/format/parquet/parquet_format_writer.h:
##########
@@ -72,7 +72,8 @@ class ParquetFormatWriter : public FormatWriter {
     ParquetFormatWriter(std::unique_ptr<::parquet::arrow::FileWriter> writer,
                         const std::shared_ptr<ArrowOutputStreamAdapter>& out,
                         const std::shared_ptr<arrow::Schema>& schema, uint64_t max_memory_use,
-                        const std::shared_ptr<arrow::MemoryPool>& pool);
+                        const std::shared_ptr<arrow::MemoryPool>& pool,
+                        bool needs_vector_conversion);

Review Comment:
   Could you please move the newly added parameter to come before `pool`?



##########
src/paimon/core/io/vector_file_batch_reader.cpp:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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/io/vector_file_batch_reader.h"
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array.h"
+#include "arrow/array/array_nested.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/compute/api.h"
+#include "arrow/type.h"
+#include "fmt/format.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/status.h"
+
+namespace paimon {
+namespace {
+
+bool ContainsVectorType(const std::shared_ptr<arrow::DataType>& type) {
+    if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        return true;
+    }
+    for (const auto& field : type->fields()) {
+        if (ContainsVectorType(field->type())) {
+            return true;
+        }
+    }
+    return false;
+}
+
+std::shared_ptr<arrow::Field> FindField(const std::shared_ptr<arrow::DataType>& type,
+                                        const std::string& name) {
+    for (const auto& field : type->fields()) {
+        if (field->name() == name) {
+            return field;
+        }
+    }
+    return nullptr;
+}
+
+std::shared_ptr<arrow::DataType> GetPhysicalReadType(
+    const std::shared_ptr<arrow::DataType>& logical_type,
+    const std::shared_ptr<arrow::DataType>& file_type) {
+    switch (logical_type->id()) {
+        case arrow::Type::FIXED_SIZE_LIST: {
+            if (!file_type || file_type->id() != arrow::Type::LIST) {
+                return logical_type;

Review Comment:
   `HasSameNestedProjectionShape` in `parquet_file_batch_reader.cpp` does not seem to handle this case yet. Would this cause issues when reading data like `List<FixedSizeList<Float32, 3>>`?
   
   Also, there seem to be several places in the Parquet code path that do not yet include branches for `fixed size list`.



##########
src/paimon/format/parquet/parquet_vector_converter.cpp:
##########
@@ -0,0 +1,126 @@
+/*
+ * 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/format/parquet/parquet_vector_converter.h"
+
+#include <cstdint>
+#include <memory>
+
+#include "arrow/array.h"
+#include "arrow/array/array_nested.h"
+#include "arrow/compute/api.h"
+#include "arrow/type.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/status.h"
+
+namespace paimon::parquet {
+namespace {
+
+bool ContainsVectorType(const std::shared_ptr<arrow::DataType>& type) {
+    if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        return true;
+    }
+    for (const auto& field : type->fields()) {
+        if (ContainsVectorType(field->type())) {
+            return true;
+        }
+    }
+    return false;
+}
+
+Status ValidateVectorElements(const std::shared_ptr<arrow::Array>& array) {

Review Comment:
   `ValidateVectorElements` and `ContainsVectorType` could go in either `arrow_utils` or a separate `vector_utils`, but right now there is too much duplicated implementation.



##########
test/test_data/parquet/vector_compatibility/README.md:
##########
@@ -0,0 +1,41 @@
+<!--
+  ~ 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.
+-->
+

Review Comment:
   The license for the test data can be omitted.



##########
src/paimon/core/schema/schema_validation.cpp:
##########
@@ -648,4 +673,26 @@ Status SchemaValidation::ValidateMapStorageLayout(const TableSchema& schema,
     return Status::OK();
 }
 
+Status SchemaValidation::ValidateVectorFields(const TableSchema& schema,
+                                              const CoreOptions& options) {
+    bool has_vector = false;
+    for (const auto& field : schema.Fields()) {
+        if (ContainsVectorField(field.ArrowField())) {

Review Comment:
   `ContainsVectorField` appears in many places. Please consolidate it into a single shared location and keep only one implementation.



##########
src/paimon/core/operation/abstract_split_read.cpp:
##########
@@ -208,6 +209,9 @@ Result<std::unique_ptr<FileBatchReader>> AbstractSplitRead::CreateFieldMappingRe
     PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<FileBatchReader> file_reader,
                            CreateFileBatchReader(file_format_identifier, data_file_path,
                                                  file_meta->file_size, reader_builder));
+    if (VectorFileBatchReader::ContainsVector(read_schema)) {
+        file_reader = std::make_unique<VectorFileBatchReader>(std::move(file_reader), pool_);

Review Comment:
   Does the nested-type cast exemption list in field_mapping.cpp (lines 186–192) need to include FIXED_SIZE_LIST as well?



##########
src/paimon/core/io/vector_file_batch_reader.cpp:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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/io/vector_file_batch_reader.h"
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/array.h"
+#include "arrow/array/array_nested.h"
+#include "arrow/c/abi.h"
+#include "arrow/c/bridge.h"
+#include "arrow/compute/api.h"
+#include "arrow/type.h"
+#include "fmt/format.h"
+#include "paimon/common/utils/arrow/mem_utils.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/status.h"
+
+namespace paimon {
+namespace {
+
+bool ContainsVectorType(const std::shared_ptr<arrow::DataType>& type) {
+    if (type->id() == arrow::Type::FIXED_SIZE_LIST) {
+        return true;
+    }
+    for (const auto& field : type->fields()) {
+        if (ContainsVectorType(field->type())) {
+            return true;
+        }
+    }
+    return false;
+}
+
+std::shared_ptr<arrow::Field> FindField(const std::shared_ptr<arrow::DataType>& type,
+                                        const std::string& name) {
+    for (const auto& field : type->fields()) {
+        if (field->name() == name) {
+            return field;
+        }
+    }
+    return nullptr;
+}
+
+std::shared_ptr<arrow::DataType> GetPhysicalReadType(
+    const std::shared_ptr<arrow::DataType>& logical_type,
+    const std::shared_ptr<arrow::DataType>& file_type) {
+    switch (logical_type->id()) {
+        case arrow::Type::FIXED_SIZE_LIST: {
+            if (!file_type || file_type->id() != arrow::Type::LIST) {
+                return logical_type;
+            }
+            const auto& vector_type = checked_cast<const arrow::FixedSizeListType&>(*logical_type);
+            const auto& list_type = checked_cast<const arrow::ListType&>(*file_type);
+            return arrow::list(vector_type.value_field()->WithType(
+                GetPhysicalReadType(vector_type.value_type(), list_type.value_type())));
+        }
+        case arrow::Type::STRUCT: {
+            if (!file_type || file_type->id() != arrow::Type::STRUCT) {
+                return logical_type;
+            }
+            arrow::FieldVector fields;
+            fields.reserve(logical_type->num_fields());
+            for (const auto& field : logical_type->fields()) {
+                std::shared_ptr<arrow::Field> file_field = FindField(file_type, field->name());
+                fields.push_back(field->WithType(
+                    GetPhysicalReadType(field->type(), file_field ? file_field->type() : nullptr)));
+            }
+            return arrow::struct_(fields);
+        }
+        case arrow::Type::LIST: {
+            if (!file_type || file_type->id() != arrow::Type::LIST) {
+                return logical_type;
+            }
+            return arrow::list(logical_type->field(0)->WithType(
+                GetPhysicalReadType(logical_type->field(0)->type(), file_type->field(0)->type())));
+        }
+        case arrow::Type::MAP: {
+            if (!file_type || file_type->id() != arrow::Type::MAP) {
+                return logical_type;
+            }
+            const auto& map_type = checked_cast<const arrow::MapType&>(*logical_type);
+            const auto& file_map_type = checked_cast<const arrow::MapType&>(*file_type);
+            return std::make_shared<arrow::MapType>(
+                map_type.key_field()->WithType(
+                    GetPhysicalReadType(map_type.key_type(), file_map_type.key_type())),
+                map_type.item_field()->WithType(
+                    GetPhysicalReadType(map_type.item_type(), file_map_type.item_type())),
+                map_type.keys_sorted());
+        }
+        default:
+            return logical_type;
+    }
+}
+
+Status ValidateVectorElements(const arrow::ListArray& array) {
+    for (int64_t i = 0; i < array.length(); ++i) {
+        if (array.IsNull(i)) {
+            continue;
+        }
+        int64_t value_offset = array.value_offset(i);
+        int64_t value_length = array.value_length(i);
+        for (int64_t j = 0; j < value_length; ++j) {
+            if (array.values()->IsNull(value_offset + j)) {
+                return Status::Invalid(fmt::format(
+                    "VECTOR cannot contain null elements, found one at row {} position {}", i, j));
+            }
+        }
+    }
+    return Status::OK();
+}
+
+Status ValidateVectorElements(const arrow::FixedSizeListArray& array) {
+    const auto& vector_type = checked_cast<const arrow::FixedSizeListType&>(*array.type());
+    for (int64_t i = 0; i < array.length(); ++i) {
+        if (array.IsNull(i)) {
+            continue;
+        }
+        int64_t value_offset = (array.offset() + i) * vector_type.list_size();
+        for (int32_t j = 0; j < vector_type.list_size(); ++j) {
+            if (array.values()->IsNull(value_offset + j)) {
+                return Status::Invalid(fmt::format(
+                    "VECTOR cannot contain null elements, found one at row {} position {}", i, j));
+            }
+        }
+    }
+    return Status::OK();
+}
+
+Result<std::shared_ptr<arrow::Array>> CastListToVector(
+    const std::shared_ptr<arrow::Array>& array,
+    const std::shared_ptr<arrow::FixedSizeListType>& read_type, arrow::MemoryPool* pool) {
+    if (array->type_id() != arrow::Type::LIST) {
+        return Status::Invalid(
+            fmt::format("Cannot restore VECTOR from type {}", array->type()->ToString()));
+    }
+    PAIMON_RETURN_NOT_OK(ValidateVectorElements(checked_cast<const arrow::ListArray&>(*array)));
+    arrow::compute::ExecContext exec_context(pool);
+    arrow::TypeHolder type_holder(read_type.get());
+    arrow::compute::CastOptions options = arrow::compute::CastOptions::Safe();
+    PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(
+        std::shared_ptr<arrow::Array> result,
+        arrow::compute::Cast(*array, type_holder, options, &exec_context));
+    return result;
+}
+
+std::shared_ptr<arrow::DataType> RebuildNestedType(
+    const std::shared_ptr<arrow::DataType>& read_type,
+    const std::vector<std::shared_ptr<arrow::ArrayData>>& children) {
+    if (read_type->id() == arrow::Type::STRUCT) {
+        arrow::FieldVector fields;
+        fields.reserve(children.size());
+        for (int32_t i = 0; i < static_cast<int32_t>(children.size()); ++i) {
+            fields.push_back(read_type->field(i)->WithType(children[i]->type));
+        }
+        return arrow::struct_(fields);
+    }
+    if (read_type->id() == arrow::Type::LIST) {
+        return arrow::list(read_type->field(0)->WithType(children[0]->type));
+    }
+
+    const auto& entries_type = checked_cast<const arrow::StructType&>(*children[0]->type);
+    const auto& map_type = checked_cast<const arrow::MapType&>(*read_type);
+    return std::make_shared<arrow::MapType>(entries_type.field(0), entries_type.field(1),
+                                            map_type.keys_sorted());

Review Comment:
   Why do both the list and struct branches preserve the original field, while only the MAP branch does not? This drops the original entries field name and metadata.



##########
src/paimon/common/utils/arrow/arrow_utils.cpp:
##########


Review Comment:
   It looks like there is no zero-copy branch for `FIXED_SIZE_LIST` here. Should we add one? Also, please add an end-to-end test with predicate pushdown to verify that `FIXED_SIZE_LIST` still works correctly when predicates are pushed down on other fields.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@paimon.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org