github-actions[bot] commented on code in PR #62182:
URL: https://github.com/apache/doris/pull/62182#discussion_r3098618915


##########
fe/fe-core/src/main/java/org/apache/doris/qe/SessionVariable.java:
##########
@@ -5436,6 +5444,7 @@ public TQueryOptions toThrift() {
         tResult.setEnableOrcFilterByMinMax(enableOrcFilterByMinMax);
         tResult.setEnablePaimonCppReader(enablePaimonCppReader);

Review Comment:
   We add a session variable and serialize it to BE, but none of the Lance 
reader selection paths actually consult it. `FileScanner` / 
`fetch_table_schema` choose `LanceRustReader` purely from `FORMAT_LANCE`, 
unlike the Paimon path which checks `enable_paimon_cpp_reader`. As written, 
`set enable_rust_lance_reader = false` has no effect, so this rollout/fallback 
knob is dead.



##########
fe/fe-core/src/main/java/org/apache/doris/datasource/property/fileformat/FileFormatProperties.java:
##########
@@ -105,6 +106,8 @@ public static FileFormatProperties 
createFileFormatProperties(String formatStrin
                 return new ArrowFileFormatProperties();
             case FORMAT_NATIVE:
                 return new NativeFileFormatProperties();
+            case FORMAT_LANCE:

Review Comment:
   FE now accepts `format='lance'` unconditionally, but BE support is still 
behind `#ifdef BUILD_RUST_READERS` in both `fetch_table_schema` and 
`FileScanner`. `ExternalFileTableValuedFunction#getBackend()` also just picks 
an arbitrary alive BE for schema inference. On a default build or a mixed-build 
cluster, the same query can succeed or fail depending on which BE FE happens to 
hit. We need a FE-side capability check (or a cluster-wide guard) before 
exposing Lance here.



##########
be/src/format/lance/lance_rust_reader.cpp:
##########
@@ -0,0 +1,395 @@
+// 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.
+
+#ifdef BUILD_RUST_READERS
+
+#include "format/lance/lance_rust_reader.h"
+
+#include <arrow/c/bridge.h>
+#include <arrow/record_batch.h>
+#include <arrow/result.h>
+#include <arrow/type.h>
+#include <rapidjson/document.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+
+#include "core/block/block.h"
+#include "core/block/column_with_type_and_name.h"
+#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_date_or_datetime_v2.h"
+#include "core/data_type/data_type_decimal.h"
+#include "core/data_type/data_type_nullable.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "core/data_type/primitive_type.h"
+#include "format/lance/lance_ffi.h"
+#include "runtime/descriptors.h"
+#include "runtime/runtime_state.h"
+#include "util/timezone_utils.h"
+
+namespace doris {
+#include "common/compile_check_avoid_begin.h"
+
+const std::vector<SlotDescriptor*> LanceRustReader::_empty_slot_descs;
+
+LanceRustReader::LanceRustReader(const std::vector<SlotDescriptor*>& 
file_slot_descs,
+                                 RuntimeState* state, RuntimeProfile* 
/*profile*/,
+                                 const TFileRangeDesc& range,
+                                 const TFileScanRangeParams* range_params)
+        : _file_slot_descs(file_slot_descs), _state(state), _range(range), 
_params(range_params) {
+    TimezoneUtils::find_cctz_time_zone(TimezoneUtils::default_time_zone, 
_ctzz);
+}
+
+LanceRustReader::LanceRustReader(const TFileScanRangeParams& params, const 
TFileRangeDesc& range,
+                                 io::IOContext* /*io_ctx*/)
+        : _file_slot_descs(_empty_slot_descs),
+          _state(nullptr),
+          _range(range),
+          _params(&params),
+          _schema_only(true) {
+    TimezoneUtils::find_cctz_time_zone(TimezoneUtils::default_time_zone, 
_ctzz);
+}
+
+LanceRustReader::~LanceRustReader() {
+    static_cast<void>(close());
+}
+
+Status LanceRustReader::init_reader() {
+    return _open_with_json(false);
+}
+
+Status LanceRustReader::init_schema_reader() {
+    return _open_with_json(true);
+}
+
+Status LanceRustReader::_open_with_json(bool schema_only) {
+    std::string uri = _range.path;
+    if (uri.empty()) {
+        return Status::InvalidArgument("Lance reader: dataset URI is empty");
+    }
+
+    // Lance datasets are directories (e.g., data.lance/).
+    // The TVF local() path may point to a file inside the dataset (e.g., 
data.lance/data/xxx.lance).
+    // Strip back to the .lance dataset root directory.
+    // Find the first .lance in the path (the dataset root), not the last
+    auto lance_pos = uri.find(".lance");
+    if (lance_pos != std::string::npos) {
+        auto end = lance_pos + 6; // ".lance" is 6 chars
+        if (end < uri.size() && uri[end] == '/') {
+            uri = uri.substr(0, end);

Review Comment:
   This drops the specific file/split FE planned and reopens the dataset root 
for every scan range. TVF still creates one `TFileRangeDesc` per matched 
`*.lance` file (and may further split large files), while 
`TLanceFileDesc.fragment_ids` is never populated or serialized into the JSON 
config. On a multi-fragment dataset, each range will re-read all fragments, so 
plain `SELECT *` / `COUNT(*)` duplicates rows. The reader needs fragment-aware 
ranges, or FE needs to stop splitting Lance datasets this way.



##########
be/src/format/lance/lance_rust_reader.cpp:
##########
@@ -0,0 +1,395 @@
+// 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.
+
+#ifdef BUILD_RUST_READERS
+
+#include "format/lance/lance_rust_reader.h"
+
+#include <arrow/c/bridge.h>
+#include <arrow/record_batch.h>
+#include <arrow/result.h>
+#include <arrow/type.h>
+#include <rapidjson/document.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+
+#include "core/block/block.h"
+#include "core/block/column_with_type_and_name.h"
+#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_date_or_datetime_v2.h"
+#include "core/data_type/data_type_decimal.h"
+#include "core/data_type/data_type_nullable.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "core/data_type/primitive_type.h"
+#include "format/lance/lance_ffi.h"
+#include "runtime/descriptors.h"
+#include "runtime/runtime_state.h"
+#include "util/timezone_utils.h"
+
+namespace doris {
+#include "common/compile_check_avoid_begin.h"
+
+const std::vector<SlotDescriptor*> LanceRustReader::_empty_slot_descs;
+
+LanceRustReader::LanceRustReader(const std::vector<SlotDescriptor*>& 
file_slot_descs,
+                                 RuntimeState* state, RuntimeProfile* 
/*profile*/,
+                                 const TFileRangeDesc& range,
+                                 const TFileScanRangeParams* range_params)
+        : _file_slot_descs(file_slot_descs), _state(state), _range(range), 
_params(range_params) {
+    TimezoneUtils::find_cctz_time_zone(TimezoneUtils::default_time_zone, 
_ctzz);
+}
+
+LanceRustReader::LanceRustReader(const TFileScanRangeParams& params, const 
TFileRangeDesc& range,
+                                 io::IOContext* /*io_ctx*/)
+        : _file_slot_descs(_empty_slot_descs),
+          _state(nullptr),
+          _range(range),
+          _params(&params),
+          _schema_only(true) {
+    TimezoneUtils::find_cctz_time_zone(TimezoneUtils::default_time_zone, 
_ctzz);
+}
+
+LanceRustReader::~LanceRustReader() {
+    static_cast<void>(close());
+}
+
+Status LanceRustReader::init_reader() {
+    return _open_with_json(false);
+}
+
+Status LanceRustReader::init_schema_reader() {
+    return _open_with_json(true);
+}
+
+Status LanceRustReader::_open_with_json(bool schema_only) {
+    std::string uri = _range.path;
+    if (uri.empty()) {
+        return Status::InvalidArgument("Lance reader: dataset URI is empty");
+    }
+
+    // Lance datasets are directories (e.g., data.lance/).
+    // The TVF local() path may point to a file inside the dataset (e.g., 
data.lance/data/xxx.lance).
+    // Strip back to the .lance dataset root directory.
+    // Find the first .lance in the path (the dataset root), not the last
+    auto lance_pos = uri.find(".lance");
+    if (lance_pos != std::string::npos) {
+        auto end = lance_pos + 6; // ".lance" is 6 chars
+        if (end < uri.size() && uri[end] == '/') {
+            uri = uri.substr(0, end);
+        }
+    }
+
+    // Build JSON config for the Rust FFI
+    rapidjson::Document doc(rapidjson::kObjectType);
+    auto& alloc = doc.GetAllocator();
+
+    doc.AddMember("uri", rapidjson::Value(uri.c_str(), alloc), alloc);
+
+    // Columns (only for data reads, not schema-only)
+    rapidjson::Value cols(rapidjson::kArrayType);
+    if (!schema_only) {
+        for (const auto* slot : _file_slot_descs) {

Review Comment:
   FE lowercases fetched TVF column names in 
`ExternalFileTableValuedFunction.fillColumns()`, but scan-time projection uses 
those lowercased slot names verbatim here. Lance field lookup / the later 
`field->name()` to block-name match are case-sensitive, so a dataset with 
column `Foo` will infer successfully and then fail at scan time when we request 
`foo`. This path needs the same lower-case-to-native-name mapping that 
Parquet/ORC readers keep.



##########
regression-test/suites/external_table_p0/tvf/lance/test_lance_tvf.groovy:
##########
@@ -0,0 +1,121 @@
+// 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.
+
+suite("test_lance_tvf", "p0,external,lance") {
+
+    List<List<Object>> backends = sql """ show backends """
+    assertTrue(backends.size() > 0)
+    def be_id = backends[0][0]
+
+    // Copy lance test datasets to all BE nodes (fromDst=false means upload TO 
BE)
+    def dataFilePath = context.config.dataPath + "/external_table_p0/tvf/lance"
+    def outFilePath = "/"
+    for (List<Object> backend : backends) {
+        def be_host = backend[1]
+        scpFiles("root", be_host, dataFilePath + "/single.lance", outFilePath, 
false)
+        scpFiles("root", be_host, dataFilePath + "/multi.lance", outFilePath, 
false)
+    }
+
+    def single_path = "single.lance/data/*.lance"
+    def multi_path = "multi.lance/data/*.lance"
+
+    // --- Test 1: SELECT * (single fragment, 5 rows) ---
+    order_qt_select_all """
+        select * from local(
+            "file_path" = "${single_path}",
+            "backend_id" = "${be_id}",
+            "format" = "lance"
+        ) order by id
+    """
+
+    // --- Test 2: Column projection ---
+    order_qt_projection """
+        select name, score from local(
+            "file_path" = "${single_path}",
+            "backend_id" = "${be_id}",
+            "format" = "lance"
+        ) order by name
+    """
+
+    // --- Test 3: COUNT(*) ---
+    qt_count """
+        select count(*) as cnt from local(
+            "file_path" = "${single_path}",
+            "backend_id" = "${be_id}",
+            "format" = "lance"
+        )
+    """
+
+    // --- Test 4: WHERE filter ---
+    order_qt_filter """
+        select * from local(
+            "file_path" = "${single_path}",
+            "backend_id" = "${be_id}",
+            "format" = "lance"
+        ) where score > 88 order by id
+    """
+
+    // --- Test 5: LIMIT ---
+    qt_limit """
+        select * from local(
+            "file_path" = "${single_path}",
+            "backend_id" = "${be_id}",
+            "format" = "lance"
+        ) order by id limit 2
+    """
+
+    // --- Test 6: Multi-fragment DISTINCT count ---
+    qt_multi_count """
+        select count(distinct id) as cnt, min(id) as min_id, max(id) as max_id 
from local(

Review Comment:
   These multi-fragment assertions only pass because `DISTINCT` cancels out the 
duplicate reads described above. The suite still doesn't cover the normal path 
(`SELECT *` / `COUNT(*)`) on a multi-fragment Lance dataset, so it won't catch 
the current end-to-end bug. Please add at least one non-`DISTINCT` 
multi-fragment case.



##########
.github/workflows/code-checks.yml:
##########
@@ -98,6 +98,10 @@ jobs:
 
             sudo DEBIAN_FRONTEND=noninteractive apt install --yes tzdata byacc
 
+            # Install Rust toolchain for Lance format reader 
(BUILD_RUST_READERS)

Review Comment:
   This now installs Rust for every C++-touching PR, but the build command 
below still does not pass `BUILD_RUST_READERS=ON`. So the job pays the extra 
network/setup cost without actually compiling the Lance path unless a prebuilt 
archive already exists. Either force the option on here or keep Rust setup out 
of the generic clang-tidy preparation job.



##########
be/src/format/lance/lance_rust_reader.cpp:
##########
@@ -0,0 +1,395 @@
+// 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.
+
+#ifdef BUILD_RUST_READERS
+
+#include "format/lance/lance_rust_reader.h"
+
+#include <arrow/c/bridge.h>
+#include <arrow/record_batch.h>
+#include <arrow/result.h>
+#include <arrow/type.h>
+#include <rapidjson/document.h>
+#include <rapidjson/stringbuffer.h>
+#include <rapidjson/writer.h>
+
+#include "core/block/block.h"
+#include "core/block/column_with_type_and_name.h"
+#include "core/data_type/data_type_array.h"
+#include "core/data_type/data_type_date_or_datetime_v2.h"
+#include "core/data_type/data_type_decimal.h"
+#include "core/data_type/data_type_nullable.h"
+#include "core/data_type/data_type_number.h"
+#include "core/data_type/data_type_string.h"
+#include "core/data_type/primitive_type.h"
+#include "format/lance/lance_ffi.h"
+#include "runtime/descriptors.h"
+#include "runtime/runtime_state.h"
+#include "util/timezone_utils.h"
+
+namespace doris {
+#include "common/compile_check_avoid_begin.h"
+
+const std::vector<SlotDescriptor*> LanceRustReader::_empty_slot_descs;
+
+LanceRustReader::LanceRustReader(const std::vector<SlotDescriptor*>& 
file_slot_descs,
+                                 RuntimeState* state, RuntimeProfile* 
/*profile*/,
+                                 const TFileRangeDesc& range,
+                                 const TFileScanRangeParams* range_params)
+        : _file_slot_descs(file_slot_descs), _state(state), _range(range), 
_params(range_params) {
+    TimezoneUtils::find_cctz_time_zone(TimezoneUtils::default_time_zone, 
_ctzz);
+}
+
+LanceRustReader::LanceRustReader(const TFileScanRangeParams& params, const 
TFileRangeDesc& range,
+                                 io::IOContext* /*io_ctx*/)
+        : _file_slot_descs(_empty_slot_descs),
+          _state(nullptr),
+          _range(range),
+          _params(&params),
+          _schema_only(true) {
+    TimezoneUtils::find_cctz_time_zone(TimezoneUtils::default_time_zone, 
_ctzz);
+}
+
+LanceRustReader::~LanceRustReader() {
+    static_cast<void>(close());
+}
+
+Status LanceRustReader::init_reader() {
+    return _open_with_json(false);
+}
+
+Status LanceRustReader::init_schema_reader() {
+    return _open_with_json(true);
+}
+
+Status LanceRustReader::_open_with_json(bool schema_only) {
+    std::string uri = _range.path;
+    if (uri.empty()) {
+        return Status::InvalidArgument("Lance reader: dataset URI is empty");
+    }
+
+    // Lance datasets are directories (e.g., data.lance/).
+    // The TVF local() path may point to a file inside the dataset (e.g., 
data.lance/data/xxx.lance).
+    // Strip back to the .lance dataset root directory.
+    // Find the first .lance in the path (the dataset root), not the last
+    auto lance_pos = uri.find(".lance");
+    if (lance_pos != std::string::npos) {
+        auto end = lance_pos + 6; // ".lance" is 6 chars
+        if (end < uri.size() && uri[end] == '/') {
+            uri = uri.substr(0, end);
+        }
+    }
+
+    // Build JSON config for the Rust FFI
+    rapidjson::Document doc(rapidjson::kObjectType);
+    auto& alloc = doc.GetAllocator();
+
+    doc.AddMember("uri", rapidjson::Value(uri.c_str(), alloc), alloc);
+
+    // Columns (only for data reads, not schema-only)
+    rapidjson::Value cols(rapidjson::kArrayType);
+    if (!schema_only) {
+        for (const auto* slot : _file_slot_descs) {
+            cols.PushBack(rapidjson::Value(slot->col_name().c_str(), alloc), 
alloc);
+        }
+    }
+    doc.AddMember("columns", cols, alloc);
+
+    // Batch size
+    size_t batch_size = schema_only ? 1 : 4096;
+    if (!schema_only && _state) {
+        size_t bs = static_cast<size_t>(_state->query_options().batch_size);
+        if (bs > 0) batch_size = bs;
+    }
+    doc.AddMember("batch_size", static_cast<uint64_t>(batch_size), alloc);
+
+    // Version (time travel) from TLanceFileDesc
+    uint64_t version = 0;
+    if (_range.__isset.table_format_params && 
_range.table_format_params.__isset.lance_params &&
+        _range.table_format_params.lance_params.__isset.version) {
+        version = 
static_cast<uint64_t>(_range.table_format_params.lance_params.version);
+    }
+    doc.AddMember("version", version, alloc);
+
+    // Storage options (S3 credentials from scan range params properties)
+    rapidjson::Value storage_opts(rapidjson::kObjectType);
+    if (_range.__isset.table_format_params && 
_range.table_format_params.__isset.lance_params &&
+        _range.table_format_params.lance_params.__isset.dataset_uri) {
+        // If a specific dataset_uri is set in lance_params, use it instead
+        const auto& lance_uri = 
_range.table_format_params.lance_params.dataset_uri;
+        if (!lance_uri.empty()) {
+            doc.RemoveMember("uri");
+            doc.AddMember("uri", rapidjson::Value(lance_uri.c_str(), alloc), 
alloc);
+        }
+    }
+    // Map Doris S3 property keys to lance/object_store standard keys
+    static const std::vector<std::pair<std::string, std::string>> 
s3_key_mapping = {
+            {"AWS_ACCESS_KEY", "aws_access_key_id"},
+            {"AWS_SECRET_KEY", "aws_secret_access_key"},
+            {"AWS_TOKEN", "aws_session_token"},
+            {"AWS_ENDPOINT", "aws_endpoint"},
+            {"AWS_REGION", "aws_region"},
+    };
+    // Read S3 properties from TFileScanRangeParams.properties
+    if (_params && _params->__isset.properties) {
+        for (const auto& [k, v] : _params->properties) {
+            // Map Doris key names to object_store key names
+            bool mapped = false;
+            for (const auto& [doris_key, lance_key] : s3_key_mapping) {
+                if (k == doris_key) {
+                    storage_opts.AddMember(rapidjson::Value(lance_key.c_str(), 
alloc),
+                                           rapidjson::Value(v.c_str(), alloc), 
alloc);
+                    mapped = true;
+                    break;
+                }
+            }
+            // Pass through any unrecognized keys as-is
+            if (!mapped && !v.empty()) {
+                storage_opts.AddMember(rapidjson::Value(k.c_str(), alloc),
+                                       rapidjson::Value(v.c_str(), alloc), 
alloc);
+            }
+        }
+    }
+    doc.AddMember("storage_options", storage_opts, alloc);
+
+    // Serialize to JSON string
+    rapidjson::StringBuffer buffer;
+    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
+    doc.Accept(writer);
+    std::string config_json = buffer.GetString();
+
+    LanceReaderHandle handle = nullptr;
+    int32_t rc = lance_reader_open_json(reinterpret_cast<const 
uint8_t*>(config_json.data()),
+                                        config_json.size(), &handle);
+    if (rc != lance_ffi::LANCE_FFI_OK) {
+        return _get_ffi_error(rc);
+    }
+
+    _reader_handle = handle;
+    return Status::OK();
+}
+
+Status LanceRustReader::get_next_block(Block* block, size_t* read_rows, bool* 
eof) {
+    if (!_reader_handle) {
+        return Status::InternalError("Lance reader is not initialized");
+    }
+
+    if (_col_name_to_block_idx.empty()) {
+        _col_name_to_block_idx = block->get_name_to_pos_map();
+    }
+
+    ArrowSchema c_schema {};
+    ArrowArray c_array {};
+    bool is_eof = false;
+    int64_t batch_bytes = 0;
+
+    int32_t rc =
+            lance_reader_next_batch(_reader_handle, &c_schema, &c_array, 
&is_eof, &batch_bytes);
+
+    if (rc == lance_ffi::LANCE_FFI_EOF || is_eof) {
+        *read_rows = 0;
+        *eof = true;
+        return Status::OK();
+    }
+    if (rc != lance_ffi::LANCE_FFI_OK) {
+        return _get_ffi_error(rc);
+    }
+
+    // Import Arrow C Data Interface into C++ RecordBatch
+    arrow::Result<std::shared_ptr<arrow::RecordBatch>> import_result =
+            arrow::ImportRecordBatch(&c_array, &c_schema);
+    if (!import_result.ok()) {
+        return Status::InternalError("Failed to import Lance arrow batch: {}",
+                                     import_result.status().message());
+    }
+
+    auto record_batch = std::move(import_result).ValueUnsafe();
+    const auto num_rows = static_cast<size_t>(record_batch->num_rows());
+    const auto num_columns = record_batch->num_columns();
+
+    // Convert Arrow columns to Doris Block columns (same pattern as 
PaimonCppReader)
+    for (int c = 0; c < num_columns; ++c) {
+        const auto& field = record_batch->schema()->field(c);
+
+        auto it = _col_name_to_block_idx.find(field->name());
+        if (it == _col_name_to_block_idx.end()) {
+            continue;
+        }
+
+        const ColumnWithTypeAndName& column_with_name = 
block->get_by_position(it->second);
+        try {
+            
RETURN_IF_ERROR(column_with_name.type->get_serde()->read_column_from_arrow(
+                    column_with_name.column->assume_mutable_ref(), 
record_batch->column(c).get(), 0,
+                    num_rows, _ctzz));
+        } catch (Exception& e) {
+            return Status::InternalError("Failed to convert Lance arrow to 
block: {}", e.what());
+        }
+    }
+
+    *read_rows = num_rows;
+    *eof = false;
+    return Status::OK();
+}
+
+Status LanceRustReader::get_columns(std::unordered_map<std::string, 
DataTypePtr>* name_to_type,
+                                    std::unordered_set<std::string>* 
missing_cols) {
+    if (_schema_only && _reader_handle) {
+        // In schema-only mode, get columns from the Lance schema
+        ArrowSchema c_schema {};
+        int32_t rc = lance_reader_get_schema(_reader_handle, &c_schema);
+        if (rc != lance_ffi::LANCE_FFI_OK) {
+            return _get_ffi_error(rc);
+        }
+        auto import_result = arrow::ImportSchema(&c_schema);
+        if (!import_result.ok()) {
+            return Status::InternalError("Failed to import Lance schema: {}",
+                                         import_result.status().message());
+        }
+        auto schema = std::move(import_result).ValueUnsafe();
+        for (const auto& field : schema->fields()) {
+            auto doris_type = _arrow_type_to_doris_type(field->type());
+            if (doris_type) {
+                name_to_type->emplace(field->name(), 
make_nullable(doris_type));
+            }
+        }
+        return Status::OK();
+    }
+
+    for (const auto* slot : _file_slot_descs) {
+        name_to_type->emplace(slot->col_name(), slot->type());
+    }
+    return Status::OK();
+}
+
+Status LanceRustReader::get_parsed_schema(std::vector<std::string>* col_names,
+                                          std::vector<DataTypePtr>* col_types) 
{
+    if (!_reader_handle) {
+        return Status::InternalError("Lance reader is not initialized");
+    }
+
+    ArrowSchema c_schema {};
+    int32_t rc = lance_reader_get_schema(_reader_handle, &c_schema);
+    if (rc != lance_ffi::LANCE_FFI_OK) {
+        return _get_ffi_error(rc);
+    }
+
+    auto import_result = arrow::ImportSchema(&c_schema);
+    if (!import_result.ok()) {
+        return Status::InternalError("Failed to import Lance schema: {}",
+                                     import_result.status().message());
+    }
+
+    auto schema = std::move(import_result).ValueUnsafe();
+    for (const auto& field : schema->fields()) {
+        auto doris_type = _arrow_type_to_doris_type(field->type());
+        if (doris_type) {
+            col_names->push_back(field->name());
+            col_types->push_back(make_nullable(doris_type));
+        }
+    }
+    return Status::OK();
+}
+
+Status LanceRustReader::close() {
+    if (_reader_handle) {
+        lance_reader_close(_reader_handle);
+        _reader_handle = nullptr;
+    }
+    return Status::OK();
+}
+
+Status LanceRustReader::_get_ffi_error(int32_t status_code) const {
+    constexpr size_t kBufSize = 1024;
+    uint8_t buf[kBufSize];
+    size_t len = lance_reader_last_error(buf, kBufSize);
+
+    std::string msg;
+    if (len > 0) {
+        msg.assign(reinterpret_cast<const char*>(buf), len);
+    } else {
+        msg = fmt::format("Lance FFI error code: {}", status_code);
+    }
+    return Status::InternalError("Rust Lance reader: {}", msg);
+}
+
+DataTypePtr LanceRustReader::_arrow_type_to_doris_type(
+        const std::shared_ptr<arrow::DataType>& arrow_type) {
+    // Arrow type IDs: STRING and UTF8 are the same value in arrow-cpp.
+    // LARGE_STRING and LARGE_UTF8 are the same. Doris has no unsigned int 
types
+    // except UInt8 (used for BOOLEAN), so unsigned ints are widened to signed.
+    switch (arrow_type->id()) {
+    case arrow::Type::BOOL:
+        return std::make_shared<DataTypeUInt8>();
+    case arrow::Type::INT8:
+    case arrow::Type::UINT8:
+        return std::make_shared<DataTypeInt8>();
+    case arrow::Type::INT16:
+    case arrow::Type::UINT16:
+        return std::make_shared<DataTypeInt16>();
+    case arrow::Type::INT32:
+    case arrow::Type::UINT32:
+        return std::make_shared<DataTypeInt32>();
+    case arrow::Type::INT64:
+    case arrow::Type::UINT64:
+        return std::make_shared<DataTypeInt64>();
+    case arrow::Type::HALF_FLOAT:
+    case arrow::Type::FLOAT:
+        return std::make_shared<DataTypeFloat32>();
+    case arrow::Type::DOUBLE:
+        return std::make_shared<DataTypeFloat64>();
+    case arrow::Type::STRING:
+    case arrow::Type::LARGE_STRING:
+        return std::make_shared<DataTypeString>();
+    case arrow::Type::BINARY:
+    case arrow::Type::LARGE_BINARY:
+        return std::make_shared<DataTypeString>();
+    case arrow::Type::DATE32:
+    case arrow::Type::DATE64:
+        return std::make_shared<DataTypeDateV2>();
+    case arrow::Type::TIMESTAMP:
+        return std::make_shared<DataTypeDateTimeV2>();

Review Comment:
   Arrow timestamps still carry their original unit, but `DataTypeDateTimeV2()` 
defaults to scale 0. That means `get_parsed_schema()` will advertise every 
ms/us/ns Lance timestamp as `DATETIMEV2(0)`, even though 
`read_column_from_arrow()` can preserve fractional seconds when the target 
scale is set. We should derive the `DateTimeV2` scale from 
`arrow::TimestampType::unit()` here.



##########
be/CMakeLists.txt:
##########
@@ -165,6 +165,27 @@ if (DEFINED ENV{PAIMON_HOME} AND NOT PAIMON_HOME)
     set(PAIMON_HOME "$ENV{PAIMON_HOME}" CACHE PATH "" FORCE)
 endif()
 
+option(BUILD_RUST_READERS "Build Rust-based format readers (Lance, etc.)" OFF)
+if (DEFINED ENV{BUILD_RUST_READERS})
+    set(BUILD_RUST_READERS "$ENV{BUILD_RUST_READERS}" CACHE BOOL "" FORCE)
+endif()
+# Auto-enable if pre-built Rust library exists (from zigbuild or manylinux2014)
+if (NOT BUILD_RUST_READERS)

Review Comment:
   This auto-enable block also runs when the user/CI explicitly configured 
`-DBUILD_RUST_READERS=OFF`. If a stale prebuilt `libdoris_ffi.a` happens to 
exist, explicit `OFF` gets silently overridden and the feature is compiled 
anyway. We need to distinguish 'unset' from 'explicit OFF' (or add a separate 
AUTO flag), otherwise the option no longer does what it says.



##########
be/cmake/rust.cmake:
##########
@@ -0,0 +1,81 @@
+# 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.
+
+# Rust integration for doris-ffi static library.
+#
+# Two modes:
+#   1. Pre-built: If libdoris_ffi.a already exists (e.g., built by 
cargo-zigbuild
+#      on the CI host), use it directly. No Rust toolchain needed inside the
+#      build container.
+#   2. Corrosion: If no pre-built .a found and cargo is available, build via
+#      Corrosion (FetchContent). Used on developer machines.
+
+# Check for pre-built .a (from zigbuild, manylinux2014, or manual build)
+set(PREBUILT_RUST_PATHS
+    
"${SRC_DIR}/rust/doris-native/target/x86_64-unknown-linux-gnu/release/libdoris_ffi.a"
+    "${SRC_DIR}/rust/doris-native/target/release/libdoris_ffi.a"
+    "${CMAKE_BINARY_DIR}/libdoris_ffi.a"
+)
+
+set(RUST_LIB_PATH "")
+foreach(p ${PREBUILT_RUST_PATHS})
+    if (EXISTS "${p}")
+        set(RUST_LIB_PATH "${p}")
+        message(STATUS "Rust readers: using pre-built library at ${p}")
+        break()
+    endif()
+endforeach()
+
+if (RUST_LIB_PATH)
+    # Mode 1: Pre-built .a found — no Corrosion needed
+    add_library(doris_ffi_lib STATIC IMPORTED GLOBAL)
+    set_target_properties(doris_ffi_lib PROPERTIES
+        IMPORTED_LOCATION "${RUST_LIB_PATH}"
+        IMPORTED_LINK_INTERFACE_LIBRARIES "m;dl;pthread"
+    )
+    message(STATUS "Rust readers enabled (pre-built)")
+else()
+    # Mode 2: Build via Corrosion (developer machines with cargo)
+    find_program(CARGO_EXECUTABLE cargo)
+    if (NOT CARGO_EXECUTABLE)
+        message(WARNING "BUILD_RUST_READERS=ON but no pre-built libdoris_ffi.a 
and no cargo in PATH. Disabling.")
+        set(BUILD_RUST_READERS OFF PARENT_SCOPE)

Review Comment:
   Because this file is brought in via `include()`, `set(BUILD_RUST_READERS OFF 
PARENT_SCOPE)` does not update the top-level variable here. If cargo/prebuilt 
artifacts are missing, later `if (BUILD_RUST_READERS)` blocks in 
`be/CMakeLists.txt` still run and try to add `-DBUILD_RUST_READERS` / 
`doris_ffi_lib`, so the 'clean disable' path can still fail configure/build. 
Please set the variable in the current scope or return a dedicated status 
variable.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to