Coverage Report

Created: 2026-05-25 21:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/table/paimon_cpp_reader.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "format/table/paimon_cpp_reader.h"
19
20
#include <algorithm>
21
#include <mutex>
22
#include <utility>
23
24
#include "arrow/c/bridge.h"
25
#include "arrow/record_batch.h"
26
#include "arrow/result.h"
27
#include "core/block/block.h"
28
#include "core/block/column_with_type_and_name.h"
29
#include "format/table/paimon_doris_file_system.h"
30
#include "paimon/defs.h"
31
#include "paimon/memory/memory_pool.h"
32
#include "paimon/read_context.h"
33
#include "paimon/table/source/table_read.h"
34
#include "runtime/descriptors.h"
35
#include "runtime/runtime_state.h"
36
#include "util/url_coding.h"
37
38
namespace doris {
39
40
namespace {
41
constexpr const char* VALUE_KIND_FIELD = "_VALUE_KIND";
42
43
} // namespace
44
45
PaimonCppReader::PaimonCppReader(const std::vector<SlotDescriptor*>& file_slot_descs,
46
                                 RuntimeState* state, RuntimeProfile* profile,
47
                                 const TFileRangeDesc& range,
48
                                 const TFileScanRangeParams* range_params)
49
2
        : _file_slot_descs(file_slot_descs),
50
2
          _state(state),
51
2
          _profile(profile),
52
2
          _range(range),
53
2
          _range_params(range_params) {
54
2
    TimezoneUtils::find_cctz_time_zone(TimezoneUtils::default_time_zone, _ctzz);
55
2
    if (range.__isset.table_format_params &&
56
2
        range.table_format_params.__isset.table_level_row_count) {
57
2
        _remaining_table_level_row_count = range.table_format_params.table_level_row_count;
58
2
    } else {
59
0
        _remaining_table_level_row_count = -1;
60
0
    }
61
2
}
62
63
2
PaimonCppReader::~PaimonCppReader() = default;
64
65
2
Status PaimonCppReader::init_reader() {
66
2
    if (_push_down_agg_type == TPushAggOp::type::COUNT && _remaining_table_level_row_count >= 0) {
67
1
        return Status::OK();
68
1
    }
69
1
    return _init_paimon_reader();
70
2
}
71
72
3
Status PaimonCppReader::_do_get_next_block(Block* block, size_t* read_rows, bool* eof) {
73
3
    if (_push_down_agg_type == TPushAggOp::type::COUNT && _remaining_table_level_row_count >= 0) {
74
3
        auto rows = std::min(_remaining_table_level_row_count,
75
3
                             (int64_t)_state->query_options().batch_size);
76
3
        _remaining_table_level_row_count -= rows;
77
3
        auto mutable_columns_guard = block->mutate_columns_scoped();
78
3
        auto& mutate_columns = mutable_columns_guard.mutable_columns();
79
3
        for (auto& col : mutate_columns) {
80
0
            col->resize(rows);
81
0
        }
82
3
        *read_rows = rows;
83
3
        *eof = false;
84
3
        if (_remaining_table_level_row_count == 0) {
85
2
            *eof = true;
86
2
        }
87
3
        return Status::OK();
88
3
    }
89
90
0
    if (!_batch_reader) {
91
0
        return Status::InternalError("paimon-cpp reader is not initialized");
92
0
    }
93
94
0
    if (_col_name_to_block_idx.empty()) {
95
0
        _col_name_to_block_idx = block->get_name_to_pos_map();
96
0
    }
97
98
0
    auto batch_result = _batch_reader->NextBatch();
99
0
    if (!batch_result.ok()) {
100
0
        return Status::InternalError("paimon-cpp read batch failed: {}",
101
0
                                     batch_result.status().ToString());
102
0
    }
103
0
    auto batch = std::move(batch_result).value();
104
0
    if (paimon::BatchReader::IsEofBatch(batch)) {
105
0
        *read_rows = 0;
106
0
        *eof = true;
107
0
        return Status::OK();
108
0
    }
109
110
0
    arrow::Result<std::shared_ptr<arrow::RecordBatch>> import_result =
111
0
            arrow::ImportRecordBatch(batch.first.get(), batch.second.get());
112
0
    if (!import_result.ok()) {
113
0
        return Status::InternalError("failed to import paimon-cpp arrow batch: {}",
114
0
                                     import_result.status().message());
115
0
    }
116
117
0
    auto record_batch = std::move(import_result).ValueUnsafe();
118
0
    const auto num_rows = static_cast<size_t>(record_batch->num_rows());
119
0
    const auto num_columns = record_batch->num_columns();
120
0
    auto columns_guard = block->mutate_columns_scoped();
121
0
    auto& columns = columns_guard.mutable_columns();
122
0
    for (int c = 0; c < num_columns; ++c) {
123
0
        const auto& field = record_batch->schema()->field(c);
124
0
        if (field->name() == VALUE_KIND_FIELD) {
125
0
            continue;
126
0
        }
127
128
0
        auto it = _col_name_to_block_idx.find(field->name());
129
0
        if (it == _col_name_to_block_idx.end()) {
130
            // Skip columns that are not in the block (e.g., partition columns handled elsewhere)
131
0
            continue;
132
0
        }
133
0
        const auto block_pos = it->second;
134
0
        try {
135
0
            RETURN_IF_ERROR(columns_guard.get_datatype_by_position(block_pos)
136
0
                                    ->get_serde()
137
0
                                    ->read_column_from_arrow(*columns[block_pos],
138
0
                                                             record_batch->column(c).get(), 0,
139
0
                                                             num_rows, _ctzz));
140
0
        } catch (Exception& e) {
141
0
            return Status::InternalError("Failed to convert from arrow to block: {}", e.what());
142
0
        }
143
0
    }
144
145
0
    *read_rows = num_rows;
146
0
    *eof = false;
147
0
    return Status::OK();
148
0
}
149
150
Status PaimonCppReader::_get_columns_impl(
151
0
        std::unordered_map<std::string, DataTypePtr>* name_to_type) {
152
0
    for (const auto& slot : _file_slot_descs) {
153
0
        name_to_type->emplace(slot->col_name(), slot->type());
154
0
    }
155
0
    return Status::OK();
156
0
}
157
158
0
Status PaimonCppReader::close() {
159
0
    if (_batch_reader) {
160
0
        _batch_reader->Close();
161
0
    }
162
0
    return Status::OK();
163
0
}
164
165
1
Status PaimonCppReader::_init_paimon_reader() {
166
1
    register_paimon_doris_file_system();
167
1
    RETURN_IF_ERROR(_decode_split(&_split));
168
169
0
    auto table_path_opt = _resolve_table_path();
170
0
    if (!table_path_opt.has_value()) {
171
0
        return Status::InternalError(
172
0
                "paimon-cpp missing paimon_table; cannot resolve paimon table root path");
173
0
    }
174
0
    auto options = _build_options();
175
0
    auto read_columns = _build_read_columns();
176
177
    // Avoid moving strings across module boundaries to prevent allocator mismatches in ASAN builds.
178
0
    std::string table_path = table_path_opt.value();
179
0
    static std::once_flag options_log_once;
180
0
    std::call_once(options_log_once, [&]() {
181
0
        auto has_key = [&](const char* key) {
182
0
            auto it = options.find(key);
183
0
            return (it != options.end() && !it->second.empty()) ? "set" : "empty";
184
0
        };
185
0
        auto value_or = [&](const char* key) {
186
0
            auto it = options.find(key);
187
0
            return it != options.end() ? it->second : std::string("<unset>");
188
0
        };
189
0
        LOG(INFO) << "paimon-cpp options summary: table_path=" << table_path
190
0
                  << " AWS_ACCESS_KEY=" << has_key("AWS_ACCESS_KEY")
191
0
                  << " AWS_SECRET_KEY=" << has_key("AWS_SECRET_KEY")
192
0
                  << " AWS_TOKEN=" << has_key("AWS_TOKEN")
193
0
                  << " AWS_ENDPOINT=" << value_or("AWS_ENDPOINT")
194
0
                  << " AWS_REGION=" << value_or("AWS_REGION")
195
0
                  << " use_path_style=" << value_or("use_path_style")
196
0
                  << " fs.oss.endpoint=" << value_or("fs.oss.endpoint")
197
0
                  << " fs.s3a.endpoint=" << value_or("fs.s3a.endpoint");
198
0
    });
199
0
    paimon::ReadContextBuilder builder(table_path);
200
0
    if (!read_columns.empty()) {
201
0
        builder.SetReadSchema(read_columns);
202
0
    }
203
0
    if (!options.empty()) {
204
0
        builder.SetOptions(options);
205
0
    }
206
0
    if (_predicate) {
207
0
        builder.SetPredicate(_predicate);
208
0
        builder.EnablePredicateFilter(true);
209
0
    }
210
211
0
    auto context_result = builder.Finish();
212
0
    if (!context_result.ok()) {
213
0
        return Status::InternalError("paimon-cpp build read context failed: {}",
214
0
                                     context_result.status().ToString());
215
0
    }
216
0
    auto context = std::move(context_result).value();
217
218
0
    auto table_read_result = paimon::TableRead::Create(std::move(context));
219
0
    if (!table_read_result.ok()) {
220
0
        return Status::InternalError("paimon-cpp create table read failed: {}",
221
0
                                     table_read_result.status().ToString());
222
0
    }
223
0
    auto table_read = std::move(table_read_result).value();
224
0
    auto reader_result = table_read->CreateReader(_split);
225
0
    if (!reader_result.ok()) {
226
0
        return Status::InternalError("paimon-cpp create reader failed: {}",
227
0
                                     reader_result.status().ToString());
228
0
    }
229
0
    _table_read = std::move(table_read);
230
0
    _batch_reader = std::move(reader_result).value();
231
0
    return Status::OK();
232
0
}
233
234
1
Status PaimonCppReader::_decode_split(std::shared_ptr<paimon::Split>* split) {
235
1
    if (!_range.__isset.table_format_params || !_range.table_format_params.__isset.paimon_params ||
236
1
        !_range.table_format_params.paimon_params.__isset.paimon_split) {
237
1
        return Status::InternalError("paimon-cpp missing paimon_split in scan range");
238
1
    }
239
0
    const auto& encoded_split = _range.table_format_params.paimon_params.paimon_split;
240
0
    std::string decoded_split;
241
0
    if (!base64_decode(encoded_split, &decoded_split)) {
242
0
        return Status::InternalError("paimon-cpp base64 decode paimon_split failed");
243
0
    }
244
0
    auto pool = paimon::GetDefaultPool();
245
0
    auto split_result =
246
0
            paimon::Split::Deserialize(decoded_split.data(), decoded_split.size(), pool);
247
0
    if (!split_result.ok()) {
248
0
        return Status::InternalError("paimon-cpp deserialize split failed: {}",
249
0
                                     split_result.status().ToString());
250
0
    }
251
0
    *split = std::move(split_result).value();
252
0
    return Status::OK();
253
0
}
254
255
0
std::optional<std::string> PaimonCppReader::_resolve_table_path() const {
256
0
    if (_range.__isset.table_format_params && _range.table_format_params.__isset.paimon_params &&
257
0
        _range.table_format_params.paimon_params.__isset.paimon_table &&
258
0
        !_range.table_format_params.paimon_params.paimon_table.empty()) {
259
0
        return _range.table_format_params.paimon_params.paimon_table;
260
0
    }
261
0
    return std::nullopt;
262
0
}
263
264
0
std::vector<std::string> PaimonCppReader::_build_read_columns() const {
265
0
    std::vector<std::string> columns;
266
0
    columns.reserve(_file_slot_descs.size());
267
0
    for (const auto& slot : _file_slot_descs) {
268
0
        columns.emplace_back(slot->col_name());
269
0
    }
270
0
    return columns;
271
0
}
272
273
0
std::map<std::string, std::string> PaimonCppReader::_build_options() const {
274
0
    std::map<std::string, std::string> options;
275
0
    if (_range_params && _range_params->__isset.paimon_options &&
276
0
        !_range_params->paimon_options.empty()) {
277
0
        options.insert(_range_params->paimon_options.begin(), _range_params->paimon_options.end());
278
0
    } else if (_range.__isset.table_format_params &&
279
0
               _range.table_format_params.__isset.paimon_params &&
280
0
               _range.table_format_params.paimon_params.__isset.paimon_options) {
281
0
        options.insert(_range.table_format_params.paimon_params.paimon_options.begin(),
282
0
                       _range.table_format_params.paimon_params.paimon_options.end());
283
0
    }
284
285
0
    if (_range_params && _range_params->__isset.properties && !_range_params->properties.empty()) {
286
0
        for (const auto& kv : _range_params->properties) {
287
0
            options[kv.first] = kv.second;
288
0
        }
289
0
    } else if (_range.__isset.table_format_params &&
290
0
               _range.table_format_params.__isset.paimon_params &&
291
0
               _range.table_format_params.paimon_params.__isset.hadoop_conf) {
292
0
        for (const auto& kv : _range.table_format_params.paimon_params.hadoop_conf) {
293
0
            options[kv.first] = kv.second;
294
0
        }
295
0
    }
296
297
0
    auto copy_if_missing = [&](const char* from_key, const char* to_key) {
298
0
        if (options.find(to_key) != options.end()) {
299
0
            return;
300
0
        }
301
0
        auto it = options.find(from_key);
302
0
        if (it != options.end() && !it->second.empty()) {
303
0
            options[to_key] = it->second;
304
0
        }
305
0
    };
306
307
    // Map common OSS/S3 Hadoop configs to Doris S3 property keys.
308
0
    copy_if_missing("fs.oss.accessKeyId", "AWS_ACCESS_KEY");
309
0
    copy_if_missing("fs.oss.accessKeySecret", "AWS_SECRET_KEY");
310
0
    copy_if_missing("fs.oss.sessionToken", "AWS_TOKEN");
311
0
    copy_if_missing("fs.oss.endpoint", "AWS_ENDPOINT");
312
0
    copy_if_missing("fs.oss.region", "AWS_REGION");
313
0
    copy_if_missing("fs.s3a.access.key", "AWS_ACCESS_KEY");
314
0
    copy_if_missing("fs.s3a.secret.key", "AWS_SECRET_KEY");
315
0
    copy_if_missing("fs.s3a.session.token", "AWS_TOKEN");
316
0
    copy_if_missing("fs.s3a.endpoint", "AWS_ENDPOINT");
317
0
    copy_if_missing("fs.s3a.region", "AWS_REGION");
318
0
    copy_if_missing("fs.s3a.path.style.access", "use_path_style");
319
320
    // Backfill file.format/manifest.format from split file_format to avoid
321
    // paimon-cpp falling back to default manifest.format=avro.
322
0
    if (_range.__isset.table_format_params && _range.table_format_params.__isset.paimon_params &&
323
0
        _range.table_format_params.paimon_params.__isset.file_format &&
324
0
        !_range.table_format_params.paimon_params.file_format.empty()) {
325
0
        const auto& split_file_format = _range.table_format_params.paimon_params.file_format;
326
0
        auto file_format_it = options.find(paimon::Options::FILE_FORMAT);
327
0
        if (file_format_it == options.end() || file_format_it->second.empty()) {
328
0
            options[paimon::Options::FILE_FORMAT] = split_file_format;
329
0
        }
330
0
        auto manifest_format_it = options.find(paimon::Options::MANIFEST_FORMAT);
331
0
        if (manifest_format_it == options.end() || manifest_format_it->second.empty()) {
332
0
            options[paimon::Options::MANIFEST_FORMAT] = split_file_format;
333
0
        }
334
0
    }
335
336
0
    options[paimon::Options::FILE_SYSTEM] = "doris";
337
0
    return options;
338
0
}
339
340
} // namespace doris