Coverage Report

Created: 2026-04-22 10:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/native/native_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/native/native_reader.h"
19
20
#include <gen_cpp/data.pb.h>
21
22
#include "core/block/block.h"
23
#include "format/native/native_format.h"
24
#include "io/file_factory.h"
25
#include "io/fs/buffered_reader.h"
26
#include "io/fs/file_reader.h"
27
#include "io/fs/tracing_file_reader.h"
28
#include "runtime/runtime_profile.h"
29
#include "runtime/runtime_state.h"
30
31
namespace doris {
32
33
NativeReader::NativeReader(RuntimeProfile* profile, const TFileScanRangeParams& params,
34
                           const TFileRangeDesc& range, io::IOContext* io_ctx, RuntimeState* state)
35
14
        : _profile(profile),
36
14
          _scan_params(params),
37
14
          _scan_range(range),
38
14
          _io_ctx(io_ctx),
39
14
          _state(state) {}
40
41
14
NativeReader::~NativeReader() {
42
14
    (void)close();
43
14
}
44
45
namespace {
46
47
Status validate_and_consume_header(io::FileReaderSPtr file_reader, const TFileRangeDesc& range,
48
14
                                   int64_t* file_size, int64_t* current_offset, bool* eof) {
49
14
    *file_size = file_reader->size();
50
14
    *current_offset = 0;
51
14
    *eof = (*file_size == 0);
52
53
    // Validate and consume Doris Native file header.
54
    // Expected layout:
55
    // [magic bytes "DORISN1\0"][uint32_t format_version][uint64_t block_size]...
56
14
    static constexpr size_t HEADER_SIZE = sizeof(DORIS_NATIVE_MAGIC) + sizeof(uint32_t);
57
14
    if (*eof || *file_size < static_cast<int64_t>(HEADER_SIZE)) {
58
0
        return Status::InternalError(
59
0
                "invalid Doris Native file {}, file size {} is smaller than header size {}",
60
0
                range.path, *file_size, HEADER_SIZE);
61
0
    }
62
63
14
    char header[HEADER_SIZE];
64
14
    Slice header_slice(header, sizeof(header));
65
14
    size_t bytes_read = 0;
66
14
    RETURN_IF_ERROR(file_reader->read_at(0, header_slice, &bytes_read));
67
14
    if (bytes_read != sizeof(header)) {
68
0
        return Status::InternalError(
69
0
                "failed to read Doris Native header from file {}, expect {} bytes, got {} bytes",
70
0
                range.path, sizeof(header), bytes_read);
71
0
    }
72
73
14
    if (memcmp(header, DORIS_NATIVE_MAGIC, sizeof(DORIS_NATIVE_MAGIC)) != 0) {
74
0
        return Status::InternalError("invalid Doris Native magic header in file {}", range.path);
75
0
    }
76
77
14
    uint32_t version = 0;
78
14
    memcpy(&version, header + sizeof(DORIS_NATIVE_MAGIC), sizeof(uint32_t));
79
14
    if (version != DORIS_NATIVE_FORMAT_VERSION) {
80
0
        return Status::InternalError(
81
0
                "unsupported Doris Native format version {} in file {}, expect {}", version,
82
0
                range.path, DORIS_NATIVE_FORMAT_VERSION);
83
0
    }
84
85
14
    *current_offset = sizeof(header);
86
14
    *eof = (*file_size == *current_offset);
87
14
    return Status::OK();
88
14
}
89
90
} // namespace
91
92
120
Status NativeReader::init_reader() {
93
120
    if (_file_reader != nullptr) {
94
106
        return Status::OK();
95
106
    }
96
97
    // Create underlying file reader. For now we always use random access mode.
98
14
    io::FileSystemProperties system_properties;
99
14
    io::FileDescription file_description;
100
14
    file_description.file_size = -1;
101
14
    if (_scan_range.__isset.file_size) {
102
14
        file_description.file_size = _scan_range.file_size;
103
14
    }
104
14
    file_description.path = _scan_range.path;
105
14
    if (_scan_range.__isset.fs_name) {
106
0
        file_description.fs_name = _scan_range.fs_name;
107
0
    }
108
14
    if (_scan_range.__isset.modification_time) {
109
5
        file_description.mtime = _scan_range.modification_time;
110
9
    } else {
111
9
        file_description.mtime = 0;
112
9
    }
113
114
14
    if (_scan_range.__isset.file_type) {
115
        // For compatibility with older FE.
116
13
        system_properties.system_type = _scan_range.file_type;
117
13
    } else {
118
1
        system_properties.system_type = _scan_params.file_type;
119
1
    }
120
14
    system_properties.properties = _scan_params.properties;
121
14
    system_properties.hdfs_params = _scan_params.hdfs_params;
122
14
    if (_scan_params.__isset.broker_addresses) {
123
1
        system_properties.broker_addresses.assign(_scan_params.broker_addresses.begin(),
124
1
                                                  _scan_params.broker_addresses.end());
125
1
    }
126
127
14
    io::FileReaderOptions reader_options =
128
14
            FileFactory::get_reader_options(_state, file_description);
129
14
    auto reader_res = io::DelegateReader::create_file_reader(
130
14
            _profile, system_properties, file_description, reader_options,
131
14
            io::DelegateReader::AccessMode::RANDOM, _io_ctx);
132
14
    if (!reader_res.has_value()) {
133
0
        return reader_res.error();
134
0
    }
135
14
    _file_reader = reader_res.value();
136
137
14
    if (_io_ctx) {
138
5
        _file_reader =
139
5
                std::make_shared<io::TracingFileReader>(_file_reader, _io_ctx->file_reader_stats);
140
5
    }
141
142
14
    RETURN_IF_ERROR(validate_and_consume_header(_file_reader, _scan_range, &_file_size,
143
14
                                                &_current_offset, &_eof));
144
14
    return Status::OK();
145
14
}
146
147
116
Status NativeReader::_do_get_next_block(Block* block, size_t* read_rows, bool* eof) {
148
116
    if (_eof) {
149
8
        *read_rows = 0;
150
8
        *eof = true;
151
8
        return Status::OK();
152
8
    }
153
154
108
    RETURN_IF_ERROR(init_reader());
155
156
108
    std::string buff;
157
108
    bool local_eof = false;
158
159
    // If we have already loaded the first block for schema probing, use it first.
160
108
    if (_first_block_loaded && !_first_block_consumed) {
161
3
        buff = _first_block_buf;
162
3
        local_eof = false;
163
105
    } else {
164
105
        RETURN_IF_ERROR(_read_next_pblock(&buff, &local_eof));
165
105
    }
166
167
    // If we reach EOF and also read no data for this call, the whole file is considered finished.
168
108
    if (local_eof && buff.empty()) {
169
1
        *read_rows = 0;
170
1
        *eof = true;
171
1
        _eof = true;
172
1
        return Status::OK();
173
1
    }
174
    // If buffer is empty but we have not reached EOF yet, treat this as an error.
175
107
    if (buff.empty()) {
176
0
        return Status::InternalError("read empty native block from file {}", _scan_range.path);
177
0
    }
178
179
107
    PBlock pblock;
180
107
    if (!pblock.ParseFromArray(buff.data(), static_cast<int>(buff.size()))) {
181
0
        return Status::InternalError("Failed to parse native PBlock from file {}",
182
0
                                     _scan_range.path);
183
0
    }
184
185
    // Initialize schema from first block if not done yet.
186
107
    if (!_schema_inited) {
187
7
        RETURN_IF_ERROR(_init_schema_from_pblock(pblock));
188
7
    }
189
190
107
    size_t uncompressed_bytes = 0;
191
107
    int64_t decompress_time = 0;
192
107
    RETURN_IF_ERROR(block->deserialize(pblock, &uncompressed_bytes, &decompress_time));
193
194
    // For external file scan / TVF scenarios, unify all columns as nullable to match
195
    // GenericReader/SlotDescriptor convention. This ensures schema consistency when
196
    // some writers emit non-nullable columns.
197
713
    for (size_t i = 0; i < block->columns(); ++i) {
198
606
        auto& col_with_type = block->get_by_position(i);
199
606
        if (!col_with_type.type->is_nullable()) {
200
28
            col_with_type.column = make_nullable(col_with_type.column);
201
28
            col_with_type.type = make_nullable(col_with_type.type);
202
28
        }
203
606
    }
204
205
107
    *read_rows = block->rows();
206
107
    *eof = false;
207
208
107
    if (_first_block_loaded && !_first_block_consumed) {
209
3
        _first_block_consumed = true;
210
3
    }
211
212
    // If we reached the physical end of file, mark eof for subsequent calls.
213
107
    if (_current_offset >= _file_size) {
214
10
        _eof = true;
215
10
    }
216
217
107
    return Status::OK();
218
107
}
219
220
4
Status NativeReader::_get_columns_impl(std::unordered_map<std::string, DataTypePtr>* name_to_type) {
221
4
    RETURN_IF_ERROR(init_reader());
222
223
4
    if (!_schema_inited) {
224
        // Load first block lazily to initialize schema.
225
4
        if (!_first_block_loaded) {
226
4
            bool local_eof = false;
227
4
            RETURN_IF_ERROR(_read_next_pblock(&_first_block_buf, &local_eof));
228
            // Treat file as empty only if we reach EOF and there is no block data at all.
229
4
            if (local_eof && _first_block_buf.empty()) {
230
0
                return Status::EndOfFile("empty native file {}", _scan_range.path);
231
0
            }
232
            // Non-EOF but empty buffer means corrupted native file.
233
4
            if (_first_block_buf.empty()) {
234
0
                return Status::InternalError("first native block is empty {}", _scan_range.path);
235
0
            }
236
4
            _first_block_loaded = true;
237
4
        }
238
239
4
        PBlock pblock;
240
4
        if (!pblock.ParseFromArray(_first_block_buf.data(),
241
4
                                   static_cast<int>(_first_block_buf.size()))) {
242
0
            return Status::InternalError("Failed to parse native PBlock for schema from file {}",
243
0
                                         _scan_range.path);
244
0
        }
245
4
        RETURN_IF_ERROR(_init_schema_from_pblock(pblock));
246
4
    }
247
248
22
    for (size_t i = 0; i < _schema_col_names.size(); ++i) {
249
18
        name_to_type->emplace(_schema_col_names[i], _schema_col_types[i]);
250
18
    }
251
4
    return Status::OK();
252
4
}
253
254
2
Status NativeReader::init_schema_reader() {
255
2
    RETURN_IF_ERROR(init_reader());
256
2
    return Status::OK();
257
2
}
258
259
Status NativeReader::get_parsed_schema(std::vector<std::string>* col_names,
260
3
                                       std::vector<DataTypePtr>* col_types) {
261
3
    RETURN_IF_ERROR(init_reader());
262
263
3
    if (!_schema_inited) {
264
2
        if (!_first_block_loaded) {
265
2
            bool local_eof = false;
266
2
            RETURN_IF_ERROR(_read_next_pblock(&_first_block_buf, &local_eof));
267
            // Treat file as empty only if we reach EOF and there is no block data at all.
268
2
            if (local_eof && _first_block_buf.empty()) {
269
0
                return Status::EndOfFile("empty native file {}", _scan_range.path);
270
0
            }
271
            // Non-EOF but empty buffer means corrupted native file.
272
2
            if (_first_block_buf.empty()) {
273
0
                return Status::InternalError("first native block is empty {}", _scan_range.path);
274
0
            }
275
2
            _first_block_loaded = true;
276
2
        }
277
278
2
        PBlock pblock;
279
2
        if (!pblock.ParseFromArray(_first_block_buf.data(),
280
2
                                   static_cast<int>(_first_block_buf.size()))) {
281
0
            return Status::InternalError("Failed to parse native PBlock for schema from file {}",
282
0
                                         _scan_range.path);
283
0
        }
284
2
        RETURN_IF_ERROR(_init_schema_from_pblock(pblock));
285
2
    }
286
287
3
    *col_names = _schema_col_names;
288
3
    *col_types = _schema_col_types;
289
3
    return Status::OK();
290
3
}
291
292
17
Status NativeReader::close() {
293
17
    _file_reader.reset();
294
17
    return Status::OK();
295
17
}
296
297
111
Status NativeReader::_read_next_pblock(std::string* buff, bool* eof) {
298
111
    *eof = false;
299
111
    buff->clear();
300
301
111
    if (_file_reader == nullptr) {
302
0
        RETURN_IF_ERROR(init_reader());
303
0
    }
304
305
111
    if (_current_offset >= _file_size) {
306
1
        *eof = true;
307
1
        return Status::OK();
308
1
    }
309
310
110
    uint64_t len = 0;
311
110
    Slice len_slice(reinterpret_cast<char*>(&len), sizeof(len));
312
110
    size_t bytes_read = 0;
313
110
    RETURN_IF_ERROR(_file_reader->read_at(_current_offset, len_slice, &bytes_read));
314
110
    if (bytes_read == 0) {
315
0
        *eof = true;
316
0
        return Status::OK();
317
0
    }
318
110
    if (bytes_read != sizeof(len)) {
319
0
        return Status::InternalError(
320
0
                "Failed to read native block length from file {}, expect {}, "
321
0
                "actual {}",
322
0
                _scan_range.path, sizeof(len), bytes_read);
323
0
    }
324
325
110
    _current_offset += sizeof(len);
326
110
    if (len == 0) {
327
        // Empty block, nothing to read.
328
0
        *eof = (_current_offset >= _file_size);
329
0
        return Status::OK();
330
0
    }
331
332
110
    buff->assign(len, '\0');
333
110
    Slice data_slice(buff->data(), len);
334
110
    bytes_read = 0;
335
110
    RETURN_IF_ERROR(_file_reader->read_at(_current_offset, data_slice, &bytes_read));
336
110
    if (bytes_read != len) {
337
0
        return Status::InternalError(
338
0
                "Failed to read native block body from file {}, expect {}, "
339
0
                "actual {}",
340
0
                _scan_range.path, len, bytes_read);
341
0
    }
342
343
110
    _current_offset += len;
344
110
    *eof = (_current_offset >= _file_size);
345
110
    return Status::OK();
346
110
}
347
348
13
Status NativeReader::_init_schema_from_pblock(const PBlock& pblock) {
349
13
    _schema_col_names.clear();
350
13
    _schema_col_types.clear();
351
352
110
    for (const auto& pcol_meta : pblock.column_metas()) {
353
110
        DataTypePtr type = make_nullable(DataTypeFactory::instance().create_data_type(pcol_meta));
354
110
        VLOG_DEBUG << "init_schema_from_pblock, name=" << pcol_meta.name()
355
0
                   << ", type=" << type->get_name();
356
110
        _schema_col_names.emplace_back(pcol_meta.name());
357
110
        _schema_col_types.emplace_back(type);
358
110
    }
359
13
    _schema_inited = true;
360
13
    return Status::OK();
361
13
}
362
363
} // namespace doris