Coverage Report

Created: 2026-06-10 18:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/segment.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 "storage/segment/segment.h"
19
20
#include <crc32c/crc32c.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/PlanNodes_types.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <gen_cpp/segment_v2.pb.h>
25
26
#include <algorithm>
27
#include <cstring>
28
#include <memory>
29
#include <sstream>
30
#include <utility>
31
32
#include "cloud/config.h"
33
#include "common/config.h"
34
#include "common/exception.h"
35
#include "common/logging.h"
36
#include "common/status.h"
37
#include "core/column/column.h"
38
#include "core/data_type/data_type.h"
39
#include "core/data_type/data_type_factory.hpp"
40
#include "core/data_type/data_type_nullable.h"
41
#include "core/data_type/data_type_variant.h"
42
#include "core/field.h"
43
#include "core/string_ref.h"
44
#include "cpp/sync_point.h"
45
#include "io/cache/block_file_cache.h"
46
#include "io/cache/block_file_cache_factory.h"
47
#include "io/cache/cached_remote_file_reader.h"
48
#include "io/fs/file_reader.h"
49
#include "io/fs/file_system.h"
50
#include "io/io_common.h"
51
#include "runtime/exec_env.h"
52
#include "runtime/query_context.h"
53
#include "runtime/runtime_predicate.h"
54
#include "runtime/runtime_state.h"
55
#include "storage/index/index_file_reader.h"
56
#include "storage/index/indexed_column_reader.h"
57
#include "storage/index/primary_key_index.h"
58
#include "storage/index/short_key_index.h"
59
#include "storage/iterator/vgeneric_iterators.h"
60
#include "storage/iterators.h"
61
#include "storage/key_coder.h"
62
#include "storage/olap_common.h"
63
#include "storage/predicate/block_column_predicate.h"
64
#include "storage/predicate/column_predicate.h"
65
#include "storage/rowset/rowset_reader_context.h"
66
#include "storage/schema.h"
67
#include "storage/segment/column_meta_accessor.h"
68
#include "storage/segment/column_reader.h"
69
#include "storage/segment/column_reader_cache.h"
70
#include "storage/segment/empty_segment_iterator.h"
71
#include "storage/segment/page_io.h"
72
#include "storage/segment/page_pointer.h"
73
#include "storage/segment/segment_iterator.h"
74
#include "storage/segment/segment_writer.h" // k_segment_magic_length
75
#include "storage/segment/stream_reader.h"
76
#include "storage/segment/variant/variant_column_reader.h"
77
#include "storage/tablet/tablet_schema.h"
78
#include "storage/types.h"
79
#include "storage/utils.h"
80
#include "util/coding.h"
81
#include "util/json/path_in_data.h"
82
#include "util/slice.h" // Slice
83
84
namespace doris::segment_v2 {
85
86
class InvertedIndexIterator;
87
88
Status Segment::open(io::FileSystemSPtr fs, const std::string& path, int64_t tablet_id,
89
                     uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
90
                     const io::FileReaderOptions& reader_options, std::shared_ptr<Segment>* output,
91
956k
                     InvertedIndexFileInfo idx_file_info, OlapReaderStatistics* stats) {
92
    // Ensure tablet_id is available in reader_options for CachedRemoteFileReader peer read.
93
956k
    io::FileReaderOptions opts_with_tablet = reader_options;
94
956k
    opts_with_tablet.tablet_id = tablet_id;
95
96
956k
    auto s = _open(fs, path, segment_id, rowset_id, tablet_schema, opts_with_tablet, output,
97
956k
                   idx_file_info, stats);
98
960k
    if (s.ok() && output && *output) {
99
960k
        (*output)->_tablet_id = tablet_id;
100
960k
    }
101
956k
    if (!s.ok()) {
102
5
        if (!config::is_cloud_mode()) {
103
5
            auto res = ExecEnv::get_tablet(tablet_id);
104
5
            TabletSharedPtr tablet =
105
5
                    res.has_value() ? std::dynamic_pointer_cast<Tablet>(res.value()) : nullptr;
106
5
            if (tablet) {
107
0
                tablet->report_error(s);
108
0
            }
109
5
        }
110
5
    }
111
112
956k
    return s;
113
956k
}
114
115
Status Segment::_open(io::FileSystemSPtr fs, const std::string& path, uint32_t segment_id,
116
                      RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
117
                      const io::FileReaderOptions& reader_options, std::shared_ptr<Segment>* output,
118
958k
                      InvertedIndexFileInfo idx_file_info, OlapReaderStatistics* stats) {
119
958k
    io::FileReaderSPtr file_reader;
120
958k
    auto st = fs->open_file(path, &file_reader, &reader_options);
121
958k
    TEST_INJECTION_POINT_CALLBACK("Segment::open:corruption", &st);
122
958k
    std::shared_ptr<Segment> segment(
123
958k
            new Segment(segment_id, rowset_id, std::move(tablet_schema), idx_file_info));
124
958k
    segment->_seg_path = path;
125
960k
    if (st) {
126
960k
        segment->_fs = fs;
127
960k
        segment->_file_reader = std::move(file_reader);
128
960k
        st = segment->_open(stats);
129
960k
    }
130
131
    // Three-tier retry for CORRUPTION errors when file cache is enabled.
132
    // This handles CORRUPTION from both open_file() and _parse_footer() (via _open()).
133
958k
    if (st.is<ErrorCode::CORRUPTION>() &&
134
958k
        reader_options.cache_type == io::FileCachePolicy::FILE_BLOCK_CACHE) {
135
        // Tier 1: Clear file cache and retry with cache support (re-downloads from remote).
136
2
        LOG(WARNING) << "bad segment file may be read from file cache, try to read remote source "
137
2
                        "file directly, file path: "
138
2
                     << path << " cache_key: " << file_cache_key_str(path);
139
2
        auto file_key = file_cache_key_from_path(path);
140
2
        auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
141
2
        file_cache->remove_if_cached(file_key);
142
143
2
        st = fs->open_file(path, &file_reader, &reader_options);
144
2
        if (st) {
145
2
            segment->_fs = fs;
146
2
            segment->_file_reader = std::move(file_reader);
147
2
            st = segment->_open(stats);
148
2
        }
149
2
        TEST_INJECTION_POINT_CALLBACK("Segment::open:corruption1", &st);
150
2
        if (st.is<ErrorCode::CORRUPTION>()) { // corrupt again
151
            // Tier 2: Bypass cache entirely and read directly from remote storage.
152
0
            LOG(WARNING) << "failed to try to read remote source file again with cache support,"
153
0
                         << " try to read from remote directly, "
154
0
                         << " file path: " << path << " cache_key: " << file_cache_key_str(path);
155
0
            file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
156
0
            file_cache->remove_if_cached(file_key);
157
158
0
            io::FileReaderOptions opt = reader_options;
159
0
            opt.cache_type = io::FileCachePolicy::NO_CACHE; // skip cache
160
0
            RETURN_IF_ERROR(fs->open_file(path, &file_reader, &opt));
161
0
            segment->_fs = fs;
162
0
            segment->_file_reader = std::move(file_reader);
163
0
            st = segment->_open(stats);
164
0
            if (!st.ok()) {
165
                // Tier 3: Remote source itself is corrupt.
166
0
                LOG(WARNING) << "failed to try to read remote source file directly,"
167
0
                             << " file path: " << path
168
0
                             << " cache_key: " << file_cache_key_str(path);
169
0
            }
170
0
        }
171
2
    }
172
958k
    RETURN_IF_ERROR(st);
173
18.4E
    DCHECK(segment->_fs != nullptr) << "file system is nullptr after segment open";
174
958k
    *output = std::move(segment);
175
958k
    return Status::OK();
176
958k
}
177
178
Segment::Segment(uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
179
                 InvertedIndexFileInfo idx_file_info)
180
959k
        : _segment_id(segment_id),
181
959k
          _meta_mem_usage(0),
182
959k
          _rowset_id(rowset_id),
183
959k
          _tablet_schema(std::move(tablet_schema)),
184
959k
          _idx_file_info(std::move(idx_file_info)) {}
185
186
926k
Segment::~Segment() {
187
926k
    g_segment_estimate_mem_bytes << -_tracked_meta_mem_usage;
188
    // if failed, fix `_tracked_meta_mem_usage` accuracy
189
926k
    DCHECK(_tracked_meta_mem_usage == meta_mem_usage());
190
926k
}
191
192
87.0k
io::UInt128Wrapper Segment::file_cache_key(std::string_view rowset_id, uint32_t seg_id) {
193
87.0k
    return io::BlockFileCache::hash(fmt::format("{}_{}.dat", rowset_id, seg_id));
194
87.0k
}
195
196
954k
int64_t Segment::get_metadata_size() const {
197
954k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared = _footer_pb.lock();
198
954k
    return sizeof(Segment) + (_pk_index_meta ? _pk_index_meta->ByteSizeLong() : 0) +
199
18.4E
           (footer_pb_shared ? footer_pb_shared->ByteSizeLong() : 0);
200
954k
}
201
202
955k
void Segment::update_metadata_size() {
203
955k
    MetadataAdder::update_metadata_size();
204
955k
    g_segment_estimate_mem_bytes << _meta_mem_usage - _tracked_meta_mem_usage;
205
955k
    _tracked_meta_mem_usage = _meta_mem_usage;
206
955k
}
207
208
957k
Status Segment::_open(OlapReaderStatistics* stats) {
209
957k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared;
210
957k
    RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, stats));
211
212
957k
    _pk_index_meta.reset(
213
957k
            footer_pb_shared->has_primary_key_index_meta()
214
957k
                    ? new PrimaryKeyIndexMetaPB(footer_pb_shared->primary_key_index_meta())
215
957k
                    : nullptr);
216
    // delete_bitmap_calculator_test.cpp
217
    // DCHECK(footer.has_short_key_index_page());
218
957k
    _sk_index_page = footer_pb_shared->short_key_index_page();
219
957k
    _num_rows = footer_pb_shared->num_rows();
220
221
    // An estimated memory usage of a segment
222
    // Footer is seperated to StoragePageCache so we don't need to add it to _meta_mem_usage
223
    // _meta_mem_usage += footer_pb_shared->ByteSizeLong();
224
957k
    if (_pk_index_meta != nullptr) {
225
857k
        _meta_mem_usage += _pk_index_meta->ByteSizeLong();
226
857k
    }
227
228
957k
    _meta_mem_usage += sizeof(*this);
229
957k
    _meta_mem_usage += std::min(static_cast<int>(_tablet_schema->num_columns()),
230
957k
                                config::max_segment_partial_column_cache_size) *
231
957k
                       config::estimated_mem_per_column_reader;
232
233
    // 1024 comes from SegmentWriterOptions
234
957k
    _meta_mem_usage += (_num_rows + 1023) / 1024 * (36 + 4);
235
    // 0.01 comes from PrimaryKeyIndexBuilder::init
236
957k
    _meta_mem_usage += BloomFilter::optimal_bit_num(_num_rows, 0.01) / 8;
237
238
957k
    update_metadata_size();
239
240
957k
    return Status::OK();
241
957k
}
242
243
5.37k
Status Segment::_open_index_file_reader() {
244
    // Use `_seg_path` (the path passed to `open`) rather than `_file_reader->path()` to derive the
245
    // index file path prefix. `_file_reader->path()` may be normalized to an absolute path, which
246
    // would not match the relative keys recorded in PackedFileSystem's index map and cause the
247
    // inverted index file (packed into a shared file) to be read as a standalone object (404).
248
5.37k
    _index_file_reader = std::make_shared<IndexFileReader>(
249
5.37k
            _fs, std::string {InvertedIndexDescriptor::get_index_file_path_prefix(_seg_path)},
250
5.37k
            _tablet_schema->get_inverted_index_storage_format(), _idx_file_info, _tablet_id);
251
5.37k
    return Status::OK();
252
5.37k
}
253
254
Status Segment::new_iterator(SchemaSPtr schema, const StorageReadOptions& read_options,
255
2.29M
                             std::unique_ptr<RowwiseIterator>* iter) {
256
2.29M
    if (read_options.runtime_state != nullptr) {
257
2.18M
        _be_exec_version = read_options.runtime_state->be_exec_version();
258
2.18M
    }
259
2.29M
    RETURN_IF_ERROR(_create_column_meta_once(read_options.stats));
260
261
2.29M
    read_options.stats->total_segment_number++;
262
    // trying to prune the current segment by segment-level zone map
263
2.29M
    for (const auto& entry : read_options.col_id_to_predicates) {
264
2.00M
        int32_t column_id = entry.first;
265
        // schema change
266
2.00M
        if (_tablet_schema->num_columns() <= column_id) {
267
1.39k
            continue;
268
1.39k
        }
269
2.00M
        const TabletColumn& col = read_options.tablet_schema->column(column_id);
270
2.00M
        std::shared_ptr<ColumnReader> reader;
271
2.00M
        Status st = get_column_reader(col, &reader, read_options.stats);
272
        // not found in this segment, skip
273
2.00M
        if (st.is<ErrorCode::NOT_FOUND>()) {
274
41
            continue;
275
41
        }
276
2.00M
        RETURN_IF_ERROR(st);
277
        // should be OK
278
2.00M
        DCHECK(reader != nullptr);
279
2.00M
        if (!reader->has_zone_map()) {
280
0
            continue;
281
0
        }
282
2.00M
        if (read_options.col_id_to_predicates.contains(column_id) &&
283
2.00M
            can_apply_predicate_safely(column_id, *schema,
284
2.00M
                                       read_options.target_cast_type_for_variants, read_options)) {
285
2.00M
            bool matched = true;
286
2.00M
            RETURN_IF_ERROR(reader->match_condition(entry.second.get(), &matched));
287
2.00M
            if (!matched) {
288
                // any condition not satisfied, return.
289
114k
                *iter = std::make_unique<EmptySegmentIterator>(*schema);
290
114k
                read_options.stats->filtered_segment_number++;
291
114k
                return Status::OK();
292
114k
            }
293
2.00M
        }
294
2.00M
    }
295
296
2.18M
    {
297
2.18M
        SCOPED_RAW_TIMER(&read_options.stats->segment_load_index_timer_ns);
298
2.18M
        RETURN_IF_ERROR(load_index(read_options.stats));
299
2.18M
    }
300
301
2.18M
    if (read_options.delete_condition_predicates->num_of_column_predicate() == 0 &&
302
2.18M
        read_options.push_down_agg_type_opt != TPushAggOp::NONE &&
303
2.18M
        read_options.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
304
32.2k
        iter->reset(new_vstatistics_iterator(this->shared_from_this(), *schema));
305
2.14M
    } else {
306
2.14M
        *iter = std::make_unique<SegmentIterator>(this->shared_from_this(), schema);
307
2.14M
    }
308
309
    // TODO: Valid the opt not only in ReaderType::READER_QUERY
310
2.18M
    if (read_options.io_ctx.reader_type == ReaderType::READER_QUERY &&
311
2.18M
        !read_options.column_predicates.empty()) {
312
1.84M
        auto pruned_predicates = read_options.column_predicates;
313
1.84M
        auto pruned = false;
314
18.8M
        for (auto& it : _column_reader_cache->get_available_readers(false)) {
315
18.8M
            const auto uid = it.first;
316
18.8M
            const auto column_id = read_options.tablet_schema->field_index(uid);
317
18.8M
            bool tmp_pruned = false;
318
18.8M
            RETURN_IF_ERROR(it.second->prune_predicates_by_zone_map(pruned_predicates, column_id,
319
18.8M
                                                                    &tmp_pruned));
320
18.8M
            pruned |= tmp_pruned;
321
18.8M
        }
322
323
1.84M
        if (pruned) {
324
8.30k
            auto options_with_pruned_predicates = read_options;
325
8.30k
            options_with_pruned_predicates.column_predicates = pruned_predicates;
326
            //because column_predicates is changed, we need to rebuild col_id_to_predicates so that inverted index will not go through it.
327
8.30k
            options_with_pruned_predicates.col_id_to_predicates.clear();
328
14.4k
            for (auto pred : options_with_pruned_predicates.column_predicates) {
329
14.4k
                if (!options_with_pruned_predicates.col_id_to_predicates.contains(
330
14.4k
                            pred->column_id())) {
331
10.0k
                    options_with_pruned_predicates.col_id_to_predicates.insert(
332
10.0k
                            {pred->column_id(), AndBlockColumnPredicate::create_shared()});
333
10.0k
                }
334
14.4k
                options_with_pruned_predicates.col_id_to_predicates[pred->column_id()]
335
14.4k
                        ->add_column_predicate(SingleColumnBlockPredicate::create_unique(pred));
336
14.4k
            }
337
8.30k
            return iter->get()->init(options_with_pruned_predicates);
338
8.30k
        }
339
1.84M
    }
340
2.17M
    return iter->get()->init(read_options);
341
2.18M
}
342
343
Status Segment::_write_error_file(size_t file_size, size_t offset, size_t bytes_read, char* data,
344
1
                                  io::IOContext& io_ctx) {
345
1
    if (!config::enbale_dump_error_file || !doris::config::is_cloud_mode()) {
346
1
        return Status::OK();
347
1
    }
348
349
0
    std::string file_name = _rowset_id.to_string() + "_" + std::to_string(_segment_id) + ".dat";
350
0
    std::string dir_path = io::FileCacheFactory::instance()->get_base_paths()[0] + "/error_file/";
351
0
    Status create_st = io::global_local_filesystem()->create_directory(dir_path, true);
352
0
    if (!create_st.ok() && !create_st.is<ErrorCode::ALREADY_EXIST>()) {
353
0
        LOG(WARNING) << "failed to create error file dir: " << create_st.to_string();
354
0
        return create_st;
355
0
    }
356
0
    size_t dir_size = 0;
357
0
    RETURN_IF_ERROR(io::global_local_filesystem()->directory_size(dir_path, &dir_size));
358
0
    if (dir_size > config::file_cache_error_log_limit_bytes) {
359
0
        LOG(WARNING) << "error file dir size is too large: " << dir_size;
360
0
        return Status::OK();
361
0
    }
362
363
0
    std::string error_part;
364
0
    error_part.resize(bytes_read);
365
0
    std::string part_path = dir_path + file_name + ".part_offset_" + std::to_string(offset);
366
0
    LOG(WARNING) << "writer error part to " << part_path;
367
0
    bool is_part_exist = false;
368
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(part_path, &is_part_exist));
369
0
    if (is_part_exist) {
370
0
        LOG(WARNING) << "error part already exists: " << part_path;
371
0
    } else {
372
0
        std::unique_ptr<io::FileWriter> part_writer;
373
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_file(part_path, &part_writer));
374
0
        RETURN_IF_ERROR(part_writer->append(Slice(data, bytes_read)));
375
0
        RETURN_IF_ERROR(part_writer->close());
376
0
    }
377
378
0
    std::string error_file;
379
0
    error_file.resize(file_size);
380
0
    auto* cached_reader = dynamic_cast<io::CachedRemoteFileReader*>(_file_reader.get());
381
0
    if (cached_reader == nullptr) {
382
0
        return Status::InternalError("file reader is not CachedRemoteFileReader");
383
0
    }
384
0
    size_t error_file_bytes_read = 0;
385
0
    RETURN_IF_ERROR(cached_reader->get_remote_reader()->read_at(
386
0
            0, Slice(error_file.data(), file_size), &error_file_bytes_read, &io_ctx));
387
0
    DCHECK(error_file_bytes_read == file_size);
388
    //std::string file_path = dir_path + std::to_string(cur_time) + "_" + ss.str();
389
0
    std::string file_path = dir_path + file_name;
390
0
    LOG(WARNING) << "writer error file to " << file_path;
391
0
    bool is_file_exist = false;
392
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(file_path, &is_file_exist));
393
0
    if (is_file_exist) {
394
0
        LOG(WARNING) << "error file already exists: " << part_path;
395
0
    } else {
396
0
        std::unique_ptr<io::FileWriter> writer;
397
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_file(file_path, &writer));
398
0
        RETURN_IF_ERROR(writer->append(Slice(error_file.data(), file_size)));
399
0
        RETURN_IF_ERROR(writer->close());
400
0
    }
401
0
    return Status::OK(); // already exists
402
0
};
403
404
Status Segment::_parse_footer(std::shared_ptr<SegmentFooterPB>& footer,
405
93.9k
                              OlapReaderStatistics* stats) {
406
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
407
93.9k
    auto file_size = _file_reader->size();
408
93.9k
    if (file_size < 12) {
409
0
        return Status::Corruption("Bad segment file {}: file size {} < 12, cache_key: {}",
410
0
                                  _file_reader->path().native(), file_size,
411
0
                                  file_cache_key_str(_file_reader->path().native()));
412
0
    }
413
414
93.9k
    uint8_t fixed_buf[12];
415
93.9k
    size_t bytes_read = 0;
416
    // TODO(plat1ko): Support session variable `enable_file_cache`
417
93.9k
    io::IOContext io_ctx {.is_index_data = true,
418
93.9k
                          .file_cache_stats = stats ? &stats->file_cache_stats : nullptr};
419
93.9k
    RETURN_IF_ERROR(
420
93.9k
            _file_reader->read_at(file_size - 12, Slice(fixed_buf, 12), &bytes_read, &io_ctx));
421
93.9k
    DCHECK_EQ(bytes_read, 12);
422
93.9k
    TEST_SYNC_POINT_CALLBACK("Segment::parse_footer:magic_number_corruption", fixed_buf);
423
93.9k
    TEST_INJECTION_POINT_CALLBACK("Segment::parse_footer:magic_number_corruption_inj", fixed_buf);
424
93.9k
    if (memcmp(fixed_buf + 8, k_segment_magic, k_segment_magic_length) != 0) {
425
1
        Status st =
426
1
                _write_error_file(file_size, file_size - 12, bytes_read, (char*)fixed_buf, io_ctx);
427
1
        if (!st.ok()) {
428
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
429
0
        }
430
1
        return Status::Corruption(
431
1
                "Bad segment file {}: file_size: {}, magic number not match, cache_key: {}",
432
1
                _file_reader->path().native(), file_size,
433
1
                file_cache_key_str(_file_reader->path().native()));
434
1
    }
435
436
    // read footer PB
437
93.9k
    uint32_t footer_length = decode_fixed32_le(fixed_buf);
438
93.9k
    if (file_size < 12 + footer_length) {
439
0
        Status st =
440
0
                _write_error_file(file_size, file_size - 12, bytes_read, (char*)fixed_buf, io_ctx);
441
0
        if (!st.ok()) {
442
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
443
0
        }
444
0
        return Status::Corruption("Bad segment file {}: file size {} < {}, cache_key: {}",
445
0
                                  _file_reader->path().native(), file_size, 12 + footer_length,
446
0
                                  file_cache_key_str(_file_reader->path().native()));
447
0
    }
448
449
93.9k
    std::string footer_buf;
450
93.9k
    footer_buf.resize(footer_length);
451
93.9k
    RETURN_IF_ERROR(_file_reader->read_at(file_size - 12 - footer_length, footer_buf, &bytes_read,
452
93.9k
                                          &io_ctx));
453
93.9k
    DCHECK_EQ(bytes_read, footer_length);
454
455
    // validate footer PB's checksum
456
93.9k
    uint32_t expect_checksum = decode_fixed32_le(fixed_buf + 4);
457
93.9k
    uint32_t actual_checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
458
93.9k
    if (actual_checksum != expect_checksum) {
459
0
        Status st = _write_error_file(file_size, file_size - 12 - footer_length, bytes_read,
460
0
                                      footer_buf.data(), io_ctx);
461
0
        if (!st.ok()) {
462
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
463
0
        }
464
0
        return Status::Corruption(
465
0
                "Bad segment file {}: file_size = {}, footer checksum not match, actual={} "
466
0
                "vs expect={}, cache_key: {}",
467
0
                _file_reader->path().native(), file_size, actual_checksum, expect_checksum,
468
0
                file_cache_key_str(_file_reader->path().native()));
469
0
    }
470
471
    // deserialize footer PB
472
93.9k
    footer = std::make_shared<SegmentFooterPB>();
473
93.9k
    if (!footer->ParseFromString(footer_buf)) {
474
0
        Status st = _write_error_file(file_size, file_size - 12 - footer_length, bytes_read,
475
0
                                      footer_buf.data(), io_ctx);
476
0
        if (!st.ok()) {
477
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
478
0
        }
479
0
        return Status::Corruption(
480
0
                "Bad segment file {}: file_size = {}, failed to parse SegmentFooterPB, "
481
0
                "cache_key: ",
482
0
                _file_reader->path().native(), file_size,
483
0
                file_cache_key_str(_file_reader->path().native()));
484
0
    }
485
486
93.9k
    VLOG_DEBUG << fmt::format("Loading segment footer from {} finished",
487
123
                              _file_reader->path().native());
488
93.9k
    return Status::OK();
489
93.9k
}
490
491
4.22M
Status Segment::_load_pk_bloom_filter(OlapReaderStatistics* stats) {
492
#ifdef BE_TEST
493
    if (_pk_index_meta == nullptr) {
494
        // for BE UT "segment_cache_test"
495
        return _load_pk_bf_once.call([this] {
496
            _meta_mem_usage += 100;
497
            update_metadata_size();
498
            return Status::OK();
499
        });
500
    }
501
#endif
502
4.22M
    DCHECK(_tablet_schema->keys_type() == UNIQUE_KEYS);
503
4.22M
    DCHECK(_pk_index_meta != nullptr);
504
4.22M
    DCHECK(_pk_index_reader != nullptr);
505
506
4.22M
    return _load_pk_bf_once.call([this, stats] {
507
54.4k
        RETURN_IF_ERROR(_pk_index_reader->parse_bf(_file_reader, *_pk_index_meta, stats));
508
        // _meta_mem_usage += _pk_index_reader->get_bf_memory_size();
509
54.4k
        return Status::OK();
510
54.4k
    });
511
4.22M
}
512
513
4.22M
Status Segment::load_pk_index_and_bf(OlapReaderStatistics* index_load_stats) {
514
    // `DorisCallOnce` may catch exception in calling stack A and re-throw it in
515
    // a different calling stack B which doesn't have catch block. So we add catch block here
516
    // to prevent coreudmp
517
4.22M
    RETURN_IF_CATCH_EXCEPTION({
518
4.22M
        RETURN_IF_ERROR(load_index(index_load_stats));
519
4.22M
        RETURN_IF_ERROR(_load_pk_bloom_filter(index_load_stats));
520
4.22M
    });
521
4.23M
    return Status::OK();
522
4.22M
}
523
524
6.42M
Status Segment::load_index(OlapReaderStatistics* stats) {
525
6.42M
    return _load_index_once.call([this, stats] {
526
816k
        if (_tablet_schema->keys_type() == UNIQUE_KEYS && _pk_index_meta != nullptr) {
527
743k
            _pk_index_reader = std::make_unique<PrimaryKeyIndexReader>();
528
743k
            RETURN_IF_ERROR(_pk_index_reader->parse_index(_file_reader, *_pk_index_meta, stats));
529
            // _meta_mem_usage += _pk_index_reader->get_memory_size();
530
743k
            return Status::OK();
531
743k
        } else {
532
            // read and parse short key index page
533
73.1k
            OlapReaderStatistics tmp_stats;
534
73.1k
            OlapReaderStatistics* stats_ptr = stats != nullptr ? stats : &tmp_stats;
535
73.1k
            PageReadOptions opts(io::IOContext {.is_index_data = true,
536
73.1k
                                                .file_cache_stats = &stats_ptr->file_cache_stats});
537
73.1k
            opts.use_page_cache = true;
538
73.1k
            opts.type = INDEX_PAGE;
539
73.1k
            opts.file_reader = _file_reader.get();
540
73.1k
            opts.page_pointer = PagePointer(_sk_index_page);
541
            // short key index page uses NO_COMPRESSION for now
542
73.1k
            opts.codec = nullptr;
543
73.1k
            opts.stats = &tmp_stats;
544
545
73.1k
            Slice body;
546
73.1k
            PageFooterPB footer;
547
73.1k
            RETURN_IF_ERROR(
548
73.1k
                    PageIO::read_and_decompress_page(opts, &_sk_index_handle, &body, &footer));
549
73.1k
            DCHECK_EQ(footer.type(), SHORT_KEY_PAGE);
550
73.1k
            DCHECK(footer.has_short_key_page_footer());
551
552
            // _meta_mem_usage += body.get_size();
553
73.1k
            _sk_index_decoder = std::make_unique<ShortKeyIndexDecoder>();
554
73.1k
            return _sk_index_decoder->parse(body, footer.short_key_page_footer());
555
73.1k
        }
556
816k
    });
557
6.42M
}
558
559
1.61M
Status Segment::healthy_status() {
560
1.61M
    try {
561
1.61M
        if (_load_index_once.has_called()) {
562
1.56M
            RETURN_IF_ERROR(_load_index_once.stored_result());
563
1.56M
        }
564
1.61M
        if (_load_pk_bf_once.has_called()) {
565
947k
            RETURN_IF_ERROR(_load_pk_bf_once.stored_result());
566
947k
        }
567
1.61M
        if (_create_column_meta_once_call.has_called()) {
568
1.55M
            RETURN_IF_ERROR(_create_column_meta_once_call.stored_result());
569
1.55M
        }
570
1.61M
        if (_index_file_reader_open.has_called()) {
571
22.5k
            RETURN_IF_ERROR(_index_file_reader_open.stored_result());
572
22.5k
        }
573
        // This status is set by running time, for example, if there is something wrong during read segment iterator.
574
1.61M
        return _healthy_status.status();
575
1.61M
    } catch (const doris::Exception& e) {
576
        // If there is an exception during load_xxx, should not throw exception directly because
577
        // the caller may not exception safe.
578
0
        return e.to_status();
579
0
    } catch (const std::exception& e) {
580
        // The exception is not thrown by doris code.
581
0
        return Status::InternalError("Unexcepted error during load segment: {}", e.what());
582
0
    }
583
1.61M
}
584
585
// Return the storage datatype of related column to field.
586
DataTypePtr Segment::get_data_type_of(const TabletColumn& column,
587
33.0M
                                      const StorageReadOptions& read_options) {
588
33.0M
    const PathInDataPtr path = column.path_info_ptr();
589
590
    // none variant column
591
33.1M
    if (path == nullptr || path->empty()) {
592
33.1M
        return DataTypeFactory::instance().create_data_type(column);
593
33.1M
    }
594
595
    // Path exists, proceed with variant logic.
596
18.4E
    PathInData relative_path = path->copy_pop_front();
597
18.4E
    int32_t unique_id = column.unique_id() >= 0 ? column.unique_id() : column.parent_unique_id();
598
599
    // If this uid does not exist in segment meta, fallback to schema type.
600
18.4E
    if (!_column_meta_accessor->has_column_uid(unique_id)) {
601
368
        return DataTypeFactory::instance().create_data_type(column);
602
368
    }
603
604
18.4E
    std::shared_ptr<ColumnReader> v_reader;
605
606
    // Get the parent variant column reader
607
18.4E
    OlapReaderStatistics stats;
608
    // If status is not ok, it will throw exception(data corruption)
609
18.4E
    THROW_IF_ERROR(get_column_reader(unique_id, &v_reader, &stats));
610
18.4E
    DCHECK(v_reader != nullptr);
611
18.4E
    auto* variant_reader = static_cast<VariantColumnReader*>(v_reader.get());
612
    // Delegate type inference for variant paths to VariantColumnReader.
613
18.4E
    DataTypePtr type;
614
18.4E
    THROW_IF_ERROR(variant_reader->infer_data_type_for_path(&type, column, read_options,
615
18.4E
                                                            _column_reader_cache.get()));
616
18.4E
    return type;
617
18.4E
}
618
619
61.8M
Status Segment::_create_column_meta_once(OlapReaderStatistics* stats) {
620
61.8M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
621
61.8M
    return _create_column_meta_once_call.call([&] {
622
847k
        std::shared_ptr<SegmentFooterPB> footer_pb_shared;
623
847k
        RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, stats));
624
847k
        return _create_column_meta(*footer_pb_shared);
625
847k
    });
626
61.8M
}
627
628
846k
Status Segment::_create_column_meta(const SegmentFooterPB& footer) {
629
    // Initialize column meta accessor which internally maintains uid -> column_ordinal mapping.
630
846k
    _column_meta_accessor = std::make_unique<ColumnMetaAccessor>();
631
846k
    RETURN_IF_ERROR(_column_meta_accessor->init(footer, _file_reader));
632
633
846k
    if (config::enable_adaptive_batch_size) {
634
        // Cache raw_data_bytes per column uid for adaptive batch size prediction.
635
        // This runs under call_once, so no thread-safety concerns.
636
12.5M
        auto st = _column_meta_accessor->traverse_metas(footer, [this](const ColumnMetaPB& meta) {
637
12.5M
            if (meta.has_unique_id() && meta.unique_id() != -1 && meta.has_raw_data_bytes()) {
638
12.2M
                _column_uid_to_raw_bytes[meta.unique_id()] = meta.raw_data_bytes();
639
12.2M
            }
640
12.5M
        });
641
642
846k
        if (!st.ok()) {
643
0
            LOG(WARNING) << "Failed to traverse column metas to cache raw_data_bytes, error: "
644
0
                         << st.to_string();
645
0
        }
646
846k
    }
647
648
846k
    _column_reader_cache = std::make_unique<ColumnReaderCache>(
649
846k
            _column_meta_accessor.get(), _tablet_schema, _file_reader, _num_rows,
650
11.3M
            [this](std::shared_ptr<SegmentFooterPB>& footer_pb, OlapReaderStatistics* stats) {
651
11.3M
                return _get_segment_footer(footer_pb, stats);
652
11.3M
            });
653
846k
    return Status::OK();
654
846k
}
655
656
Status Segment::new_default_iterator(const TabletColumn& tablet_column,
657
11.8k
                                     std::unique_ptr<ColumnIterator>* iter) {
658
11.8k
    if (!tablet_column.has_default_value() && !tablet_column.is_nullable()) {
659
0
        return Status::InternalError(
660
0
                "invalid nonexistent column without default value. column_uid={}, "
661
0
                "column_name={}, "
662
0
                "column_type={}",
663
0
                tablet_column.unique_id(), tablet_column.name(), tablet_column.type());
664
0
    }
665
11.8k
    std::unique_ptr<DefaultValueColumnIterator> default_value_iter(new DefaultValueColumnIterator(
666
11.8k
            tablet_column.has_default_value(), tablet_column.default_value(),
667
11.8k
            tablet_column.is_nullable(), tablet_column.type(), tablet_column.precision(),
668
11.8k
            tablet_column.frac(), tablet_column.length()));
669
11.8k
    ColumnIteratorOptions iter_opts;
670
671
11.8k
    RETURN_IF_ERROR(default_value_iter->init(iter_opts));
672
11.8k
    *iter = std::move(default_value_iter);
673
11.8k
    return Status::OK();
674
11.8k
}
675
676
// Not use cid anymore, for example original table schema is colA int, then user do following actions
677
// 1.add column b
678
// 2. drop column b
679
// 3. add column c
680
// in the new schema column c's cid == 2
681
// but in the old schema column b's cid == 2
682
// but they are not the same column
683
Status Segment::new_column_iterator(const TabletColumn& tablet_column,
684
                                    std::unique_ptr<ColumnIterator>* iter,
685
                                    const StorageReadOptions* opt,
686
                                    const std::unordered_map<int32_t, PathToBinaryColumnCacheUPtr>*
687
28.7M
                                            variant_sparse_column_cache) {
688
28.7M
    if (opt->runtime_state != nullptr) {
689
28.2M
        _be_exec_version = opt->runtime_state->be_exec_version();
690
28.2M
    }
691
28.7M
    RETURN_IF_ERROR(_create_column_meta_once(opt->stats));
692
693
    // For compability reason unique_id may less than 0 for variant extracted column
694
28.8M
    int32_t unique_id = tablet_column.unique_id() >= 0 ? tablet_column.unique_id()
695
18.4E
                                                       : tablet_column.parent_unique_id();
696
697
    // If column meta for this uid is not found in this segment, use default iterator.
698
28.7M
    if (!_column_meta_accessor->has_column_uid(unique_id)) {
699
3.07k
        RETURN_IF_ERROR(new_default_iterator(tablet_column, iter));
700
3.07k
        return Status::OK();
701
3.07k
    }
702
703
    // init iterator by unique id
704
28.7M
    std::shared_ptr<ColumnReader> reader;
705
28.7M
    RETURN_IF_ERROR(get_column_reader(unique_id, &reader, opt->stats));
706
28.7M
    if (reader == nullptr) {
707
0
        return Status::InternalError("column reader is nullptr, unique_id={}", unique_id);
708
0
    }
709
28.7M
    if (reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT) {
710
        // if sparse_column_cache_ptr is nullptr, means the sparse column cache is not used
711
29.4k
        PathToBinaryColumnCache* sparse_column_cache_ptr = nullptr;
712
29.4k
        if (variant_sparse_column_cache) {
713
28.9k
            auto it = variant_sparse_column_cache->find(unique_id);
714
28.9k
            if (it != variant_sparse_column_cache->end()) {
715
28.9k
                sparse_column_cache_ptr = it->second.get();
716
18.4E
            } else {
717
18.4E
                DCHECK(false) << "sparse column cache is not found, unique_id=" << unique_id;
718
18.4E
            }
719
28.9k
        }
720
        // use _column_reader_cache to get variant subcolumn(path column) reader
721
29.4k
        RETURN_IF_ERROR(assert_cast<VariantColumnReader*>(reader.get())
722
29.4k
                                ->new_iterator(iter, &tablet_column, opt,
723
29.4k
                                               _column_reader_cache.get(),
724
29.4k
                                               sparse_column_cache_ptr));
725
28.7M
    } else {
726
28.7M
        RETURN_IF_ERROR(reader->new_iterator(iter, &tablet_column, opt));
727
28.7M
        if (opt->all_access_paths.contains(unique_id) ||
728
28.7M
            opt->predicate_access_paths.contains(unique_id)) {
729
72.5k
            const auto& all_access_paths = opt->all_access_paths.contains(unique_id)
730
72.6k
                                                   ? opt->all_access_paths.at(unique_id)
731
18.4E
                                                   : TColumnAccessPaths {};
732
72.5k
            const auto& predicate_access_paths = opt->predicate_access_paths.contains(unique_id)
733
72.5k
                                                         ? opt->predicate_access_paths.at(unique_id)
734
72.5k
                                                         : TColumnAccessPaths {};
735
736
            // set column name to apply access paths.
737
72.5k
            (*iter)->set_column_name(tablet_column.name());
738
72.5k
            RETURN_IF_ERROR((*iter)->set_access_paths(all_access_paths, predicate_access_paths));
739
72.5k
            (*iter)->remove_pruned_sub_iterators();
740
72.5k
        }
741
28.7M
    }
742
743
28.8M
    if (config::enable_column_type_check && !tablet_column.has_path_info() &&
744
28.8M
        !tablet_column.is_agg_state_type() && tablet_column.type() != reader->get_meta_type()) {
745
0
        LOG(WARNING) << "different type between schema and column reader,"
746
0
                     << " column schema name: " << tablet_column.name()
747
0
                     << " column schema type: " << int(tablet_column.type())
748
0
                     << " column reader meta type: " << int(reader->get_meta_type());
749
0
        return Status::InternalError("different type between schema and column reader");
750
0
    }
751
28.7M
    return Status::OK();
752
28.7M
}
753
754
Status Segment::get_column_reader(int32_t col_uid, std::shared_ptr<ColumnReader>* column_reader,
755
28.8M
                                  OlapReaderStatistics* stats) {
756
28.8M
    RETURN_IF_ERROR(_create_column_meta_once(stats));
757
28.8M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
758
    // The column is not in this segment, return nullptr
759
28.8M
    if (!_tablet_schema->has_column_unique_id(col_uid)) {
760
0
        *column_reader = nullptr;
761
0
        return Status::Error<ErrorCode::NOT_FOUND, false>("column not found in segment, col_uid={}",
762
0
                                                          col_uid);
763
0
    }
764
28.8M
    return _column_reader_cache->get_column_reader(col_uid, column_reader, stats);
765
28.8M
}
766
767
44.8k
Status Segment::traverse_column_meta_pbs(const std::function<void(const ColumnMetaPB&)>& visitor) {
768
    // Ensure column meta accessor and reader cache are initialized once.
769
44.8k
    OlapReaderStatistics dummy_stats;
770
44.8k
    RETURN_IF_ERROR(_create_column_meta_once(&dummy_stats));
771
44.8k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared;
772
44.8k
    RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, &dummy_stats));
773
44.8k
    return _column_meta_accessor->traverse_metas(*footer_pb_shared, visitor);
774
44.8k
}
775
776
Status Segment::get_column_reader(const TabletColumn& col,
777
                                  std::shared_ptr<ColumnReader>* column_reader,
778
2.07M
                                  OlapReaderStatistics* stats) {
779
2.07M
    RETURN_IF_ERROR(_create_column_meta_once(stats));
780
2.07M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
781
18.4E
    int col_uid = col.unique_id() >= 0 ? col.unique_id() : col.parent_unique_id();
782
    // The column is not in this segment, return nullptr
783
2.07M
    if (!_tablet_schema->has_column_unique_id(col_uid)) {
784
9
        *column_reader = nullptr;
785
9
        return Status::Error<ErrorCode::NOT_FOUND, false>("column not found in segment, col_uid={}",
786
9
                                                          col_uid);
787
9
    }
788
2.07M
    if (col.has_path_info()) {
789
1.45k
        PathInData relative_path = col.path_info_ptr()->copy_pop_front();
790
1.45k
        return _column_reader_cache->get_path_column_reader(col_uid, relative_path, column_reader,
791
1.45k
                                                            stats);
792
1.45k
    }
793
2.07M
    return _column_reader_cache->get_column_reader(col_uid, column_reader, stats);
794
2.07M
}
795
796
Status Segment::new_index_iterator(const TabletColumn& tablet_column, const TabletIndex* index_meta,
797
                                   const StorageReadOptions& read_options,
798
74.2k
                                   std::unique_ptr<IndexIterator>* iter) {
799
74.2k
    if (read_options.runtime_state != nullptr) {
800
65.4k
        _be_exec_version = read_options.runtime_state->be_exec_version();
801
65.4k
    }
802
74.2k
    RETURN_IF_ERROR(_create_column_meta_once(read_options.stats));
803
74.2k
    std::shared_ptr<ColumnReader> reader;
804
74.2k
    auto st = get_column_reader(tablet_column, &reader, read_options.stats);
805
74.2k
    if (st.is<ErrorCode::NOT_FOUND>()) {
806
462
        return Status::OK();
807
462
    }
808
73.7k
    RETURN_IF_ERROR(st);
809
73.7k
    DCHECK(reader != nullptr);
810
74.0k
    if (index_meta) {
811
        // call DorisCallOnce.call without check if _index_file_reader is nullptr
812
        // to avoid data race during parallel method calls
813
74.0k
        RETURN_IF_ERROR(_index_file_reader_open.call([&] { return _open_index_file_reader(); }));
814
        // after DorisCallOnce.call, _index_file_reader is guaranteed to be not nullptr
815
74.0k
        const std::string rowset_id =
816
74.0k
                index_meta->index_type() == IndexType::ANN ? _rowset_id.to_string() : "";
817
74.0k
        const bool need_binding_diagnostic = tablet_column.is_variant_type() ||
818
74.0k
                                             tablet_column.is_extracted_column() ||
819
74.0k
                                             !index_meta->get_index_suffix().empty();
820
74.0k
        bool index_file_exists = false;
821
74.0k
        Status probe_status;
822
74.0k
        if (need_binding_diagnostic) {
823
869
            probe_status = _index_file_reader->init(config::inverted_index_read_buffer_size,
824
869
                                                    &read_options.io_ctx);
825
871
            if (probe_status.ok()) {
826
871
                probe_status = _index_file_reader->index_file_exist(index_meta, &index_file_exists);
827
871
            }
828
869
            const auto diagnostic = fmt::format(
829
869
                    "[VariantSearchBinding] phase=index_file_probe tablet_id={} rowset_id={} "
830
869
                    "segment_id={} column={} logical_path={} index_id={} suffix={} exists={} "
831
869
                    "status={}",
832
869
                    read_options.tablet_id, _rowset_id.to_string(), _segment_id,
833
869
                    tablet_column.name(),
834
870
                    tablet_column.has_path_info() ? tablet_column.path_info_ptr()->get_path()
835
18.4E
                                                  : tablet_column.name(),
836
869
                    index_meta->index_id(), index_meta->get_index_suffix(), index_file_exists,
837
18.4E
                    probe_status.ok() ? "OK" : probe_status.to_string());
838
18.4E
            VLOG_DEBUG << diagnostic;
839
871
            if (read_options.stats != nullptr) {
840
871
                read_options.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
841
871
            }
842
869
        }
843
74.0k
        Status iter_status = reader->new_index_iterator(_index_file_reader, index_meta, rowset_id,
844
74.0k
                                                        _segment_id, _num_rows, iter);
845
74.0k
        if (!iter_status.ok()) {
846
0
            if (need_binding_diagnostic) {
847
0
                const auto diagnostic = fmt::format(
848
0
                        "[VariantSearchBinding] phase=index_iterator_create result=reject "
849
0
                        "tablet_id={} rowset_id={} segment_id={} column={} logical_path={} "
850
0
                        "index_id={} suffix={} reason={}",
851
0
                        read_options.tablet_id, _rowset_id.to_string(), _segment_id,
852
0
                        tablet_column.name(),
853
0
                        tablet_column.has_path_info() ? tablet_column.path_info_ptr()->get_path()
854
0
                                                      : tablet_column.name(),
855
0
                        index_meta->index_id(), index_meta->get_index_suffix(),
856
0
                        iter_status.to_string());
857
0
                VLOG_DEBUG << diagnostic;
858
0
                if (read_options.stats != nullptr) {
859
0
                    read_options.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
860
0
                }
861
0
            }
862
0
            return iter_status;
863
0
        }
864
74.0k
        return Status::OK();
865
74.0k
    }
866
18.4E
    return Status::OK();
867
73.7k
}
868
869
Status Segment::lookup_row_key(const Slice& key, const TabletSchema* latest_schema,
870
                               bool with_seq_col, bool with_rowid, RowLocation* row_location,
871
4.18M
                               OlapReaderStatistics* stats, std::string* encoded_seq_value) {
872
4.18M
    RETURN_IF_ERROR(load_pk_index_and_bf(stats));
873
4.18M
    bool has_seq_col = latest_schema->has_sequence_col();
874
4.18M
    bool has_rowid = !latest_schema->cluster_key_uids().empty();
875
4.18M
    size_t seq_col_length = 0;
876
4.18M
    if (has_seq_col) {
877
25.3k
        seq_col_length = latest_schema->column(latest_schema->sequence_col_idx()).length() + 1;
878
25.3k
    }
879
4.18M
    size_t rowid_length = has_rowid ? PrimaryKeyIndexReader::ROW_ID_LENGTH : 0;
880
881
4.18M
    Slice key_without_seq =
882
4.18M
            Slice(key.get_data(), key.get_size() - (with_seq_col ? seq_col_length : 0) -
883
4.18M
                                          (with_rowid ? rowid_length : 0));
884
885
4.18M
    DCHECK(_pk_index_reader != nullptr);
886
4.18M
    if (!_pk_index_reader->check_present(key_without_seq)) {
887
165k
        return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
888
165k
    }
889
4.01M
    bool exact_match = false;
890
4.01M
    std::unique_ptr<segment_v2::IndexedColumnIterator> index_iterator;
891
4.01M
    RETURN_IF_ERROR(_pk_index_reader->new_iterator(&index_iterator, stats));
892
4.01M
    auto st = index_iterator->seek_at_or_after(&key_without_seq, &exact_match);
893
4.01M
    if (!st.ok() && !st.is<ErrorCode::ENTRY_NOT_FOUND>()) {
894
0
        return st;
895
0
    }
896
4.03M
    if (st.is<ErrorCode::ENTRY_NOT_FOUND>() || (!has_seq_col && !has_rowid && !exact_match)) {
897
74
        return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
898
74
    }
899
4.01M
    row_location->row_id = cast_set<uint32_t>(index_iterator->get_current_ordinal());
900
4.01M
    row_location->segment_id = _segment_id;
901
4.01M
    row_location->rowset_id = _rowset_id;
902
903
4.01M
    size_t num_to_read = 1;
904
4.01M
    auto index_type = DataTypeFactory::instance().create_data_type(_pk_index_reader->type(), 1, 0);
905
4.01M
    auto index_column = index_type->create_column();
906
4.01M
    size_t num_read = num_to_read;
907
4.01M
    RETURN_IF_ERROR(index_iterator->next_batch(&num_read, index_column));
908
4.01M
    DCHECK(num_to_read == num_read);
909
910
4.01M
    Slice sought_key = Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
911
912
    // user may use "ALTER TABLE tbl ENABLE FEATURE "SEQUENCE_LOAD" WITH ..." to add a hidden sequence column
913
    // for a merge-on-write table which doesn't have sequence column, so `has_seq_col ==  true` doesn't mean
914
    // data in segment has sequence column value
915
4.01M
    bool segment_has_seq_col = _tablet_schema->has_sequence_col();
916
4.01M
    Slice sought_key_without_seq = Slice(
917
4.01M
            sought_key.get_data(),
918
4.01M
            sought_key.get_size() - (segment_has_seq_col ? seq_col_length : 0) - rowid_length);
919
920
4.01M
    if (has_seq_col) {
921
        // compare key
922
25.2k
        if (key_without_seq.compare(sought_key_without_seq) != 0) {
923
0
            return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
924
0
        }
925
926
25.2k
        if (with_seq_col && segment_has_seq_col) {
927
            // compare sequence id
928
23.3k
            Slice sequence_id =
929
23.3k
                    Slice(key.get_data() + key_without_seq.get_size() + 1, seq_col_length - 1);
930
23.3k
            Slice previous_sequence_id =
931
23.3k
                    Slice(sought_key.get_data() + sought_key_without_seq.get_size() + 1,
932
23.3k
                          seq_col_length - 1);
933
23.3k
            if (sequence_id.compare(previous_sequence_id) < 0) {
934
333
                return Status::Error<ErrorCode::KEY_ALREADY_EXISTS>(
935
333
                        "key with higher sequence id exists");
936
333
            }
937
23.3k
        }
938
3.99M
    } else if (has_rowid) {
939
59.0k
        Slice sought_key_without_rowid =
940
59.0k
                Slice(sought_key.get_data(), sought_key.get_size() - rowid_length);
941
        // compare key
942
59.0k
        if (key_without_seq.compare(sought_key_without_rowid) != 0) {
943
0
            return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
944
0
        }
945
59.0k
    }
946
    // found the key, use rowid in pk index if necessary.
947
4.01M
    if (has_rowid) {
948
71.0k
        Slice rowid_slice = Slice(sought_key.get_data() + sought_key_without_seq.get_size() +
949
71.0k
                                          (segment_has_seq_col ? seq_col_length : 0) + 1,
950
71.0k
                                  rowid_length - 1);
951
71.0k
        const auto* rowid_coder = get_key_coder(FieldType::OLAP_FIELD_TYPE_UNSIGNED_INT);
952
71.0k
        RETURN_IF_ERROR(rowid_coder->decode_ascending(&rowid_slice, rowid_length,
953
71.0k
                                                      (uint8_t*)&row_location->row_id));
954
71.0k
    }
955
956
4.01M
    if (encoded_seq_value) {
957
78
        if (!segment_has_seq_col) {
958
0
            *encoded_seq_value = std::string {};
959
78
        } else {
960
            // include marker
961
78
            *encoded_seq_value =
962
78
                    Slice(sought_key.get_data() + sought_key_without_seq.get_size(), seq_col_length)
963
78
                            .to_string();
964
78
        }
965
78
    }
966
4.01M
    return Status::OK();
967
4.01M
}
968
969
0
Status Segment::read_key_by_rowid(uint32_t row_id, std::string* key) {
970
0
    OlapReaderStatistics* null_stat = nullptr;
971
0
    RETURN_IF_ERROR(load_pk_index_and_bf(null_stat));
972
0
    std::unique_ptr<segment_v2::IndexedColumnIterator> iter;
973
0
    RETURN_IF_ERROR(_pk_index_reader->new_iterator(&iter, null_stat));
974
975
0
    auto index_type = DataTypeFactory::instance().create_data_type(_pk_index_reader->type(), 1, 0);
976
0
    auto index_column = index_type->create_column();
977
0
    RETURN_IF_ERROR(iter->seek_to_ordinal(row_id));
978
0
    size_t num_read = 1;
979
0
    RETURN_IF_ERROR(iter->next_batch(&num_read, index_column));
980
0
    CHECK(num_read == 1);
981
    // trim row id
982
0
    if (_tablet_schema->cluster_key_uids().empty()) {
983
0
        *key = index_column->get_data_at(0).to_string();
984
0
    } else {
985
0
        Slice sought_key =
986
0
                Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
987
0
        Slice sought_key_without_rowid =
988
0
                Slice(sought_key.get_data(),
989
0
                      sought_key.get_size() - PrimaryKeyIndexReader::ROW_ID_LENGTH);
990
0
        *key = sought_key_without_rowid.to_string();
991
0
    }
992
0
    return Status::OK();
993
0
}
994
995
Status Segment::seek_and_read_by_rowid(const TabletSchema& schema, SlotDescriptor* slot,
996
                                       const std::vector<uint32_t>& row_ids,
997
                                       MutableColumnPtr& result,
998
                                       StorageReadOptions& storage_read_options,
999
12.3k
                                       std::unique_ptr<ColumnIterator>& iterator_hint) {
1000
12.3k
    if (row_ids.empty()) {
1001
0
        return Status::OK();
1002
0
    }
1003
12.3k
    DORIS_CHECK(std::is_sorted(row_ids.begin(), row_ids.end()));
1004
12.3k
    DORIS_CHECK(std::adjacent_find(row_ids.begin(), row_ids.end()) == row_ids.end());
1005
    // ColumnIterator::seek_and_read expects monotonically increasing row_ids without
1006
    // duplicates for correct ordinal scanning. Enforce this contract at the entry point.
1007
12.3k
    segment_v2::ColumnIteratorOptions opt {
1008
12.3k
            .use_page_cache = !config::disable_storage_page_cache,
1009
12.3k
            .file_reader = file_reader().get(),
1010
12.3k
            .stats = storage_read_options.stats,
1011
12.3k
            .io_ctx = io::IOContext {.reader_type = ReaderType::READER_QUERY,
1012
12.3k
                                     .file_cache_stats =
1013
12.3k
                                             &storage_read_options.stats->file_cache_stats},
1014
12.3k
    };
1015
1016
12.3k
    if (!slot->column_paths().empty()) {
1017
        // here need create column readers to make sure column reader is created before seek_and_read_by_rowid
1018
        // if segment cache miss, column reader will be created to make sure the variant column result not coredump
1019
304
        RETURN_IF_ERROR(_create_column_meta_once(storage_read_options.stats));
1020
1021
304
        const auto& dt_variant =
1022
304
                assert_cast<const DataTypeVariant&>(*remove_nullable(slot->type()));
1023
304
        TabletColumn column = TabletColumn::create_materialized_variant_column(
1024
304
                schema.column_by_uid(slot->col_unique_id()).name_lower_case(), slot->column_paths(),
1025
304
                slot->col_unique_id(), dt_variant.variant_max_subcolumns_count(),
1026
304
                dt_variant.enable_doc_mode());
1027
304
        auto storage_type = get_data_type_of(column, storage_read_options);
1028
304
        MutableColumnPtr file_storage_column = storage_type->create_column();
1029
304
        DCHECK(storage_type != nullptr);
1030
1031
304
        if (iterator_hint == nullptr) {
1032
304
            RETURN_IF_ERROR(new_column_iterator(column, &iterator_hint, &storage_read_options));
1033
304
            RETURN_IF_ERROR(iterator_hint->init(opt));
1034
304
        }
1035
304
        RETURN_IF_ERROR(
1036
304
                iterator_hint->read_by_rowids(row_ids.data(), row_ids.size(), file_storage_column));
1037
304
        ColumnPtr source_ptr;
1038
        // storage may have different type with schema, so we need to cast the column
1039
304
        RETURN_IF_ERROR(variant_util::cast_column(
1040
304
                ColumnWithTypeAndName(file_storage_column->get_ptr(), storage_type, column.name()),
1041
304
                slot->type(), &source_ptr));
1042
304
        RETURN_IF_CATCH_EXCEPTION(result->insert_range_from(*source_ptr, 0, row_ids.size()));
1043
12.0k
    } else {
1044
12.0k
        int index = (slot->col_unique_id() >= 0) ? schema.field_index(slot->col_unique_id())
1045
12.0k
                                                 : schema.field_index(slot->col_name());
1046
12.0k
        if (index < 0) {
1047
0
            std::stringstream ss;
1048
0
            ss << "field name is invalid. field=" << slot->col_name()
1049
0
               << ", field_name_to_index=" << schema.get_all_field_names();
1050
0
            return Status::InternalError(ss.str());
1051
0
        }
1052
12.0k
        if (iterator_hint == nullptr) {
1053
12.0k
            RETURN_IF_ERROR(new_column_iterator(schema.column(index), &iterator_hint,
1054
12.0k
                                                &storage_read_options));
1055
12.0k
            RETURN_IF_ERROR(iterator_hint->init(opt));
1056
12.0k
        }
1057
12.0k
        RETURN_IF_ERROR(iterator_hint->read_by_rowids(row_ids.data(), row_ids.size(), result));
1058
12.0k
    }
1059
12.3k
    return Status::OK();
1060
12.3k
}
1061
1062
Status Segment::_get_segment_footer(std::shared_ptr<SegmentFooterPB>& footer_pb,
1063
13.1M
                                    OlapReaderStatistics* stats) {
1064
13.1M
    std::shared_ptr<SegmentFooterPB> footer_pb_shared = _footer_pb.lock();
1065
13.1M
    if (footer_pb_shared != nullptr) {
1066
12.2M
        footer_pb = footer_pb_shared;
1067
12.2M
        return Status::OK();
1068
12.2M
    }
1069
1070
18.4E
    VLOG_DEBUG << fmt::format("Segment footer of {}:{}:{} is missing, try to load it",
1071
18.4E
                              _file_reader->path().native(), _file_reader->size(),
1072
18.4E
                              _file_reader->size() - 12);
1073
1074
926k
    StoragePageCache* segment_footer_cache = ExecEnv::GetInstance()->get_storage_page_cache();
1075
926k
    DCHECK(segment_footer_cache != nullptr);
1076
1077
926k
    auto cache_key = get_segment_footer_cache_key();
1078
1079
926k
    PageCacheHandle cache_handle;
1080
1081
    // Put segment footer into index page cache.
1082
    // Rationale:
1083
    // - Footer is metadata (small, parsed with indexes), not data page payload.
1084
    // - Using PageTypePB::INDEX_PAGE keeps it under the same eviction policy/shards
1085
    //   as other index/metadata pages and avoids competing with DATA_PAGE budget.
1086
926k
    if (!segment_footer_cache->lookup(cache_key, &cache_handle,
1087
926k
                                      segment_v2::PageTypePB::INDEX_PAGE)) {
1088
93.7k
        RETURN_IF_ERROR(_parse_footer(footer_pb_shared, stats));
1089
93.7k
        segment_footer_cache->insert(cache_key, footer_pb_shared, footer_pb_shared->ByteSizeLong(),
1090
93.7k
                                     &cache_handle, segment_v2::PageTypePB::INDEX_PAGE);
1091
832k
    } else {
1092
18.4E
        VLOG_DEBUG << fmt::format("Segment footer of {}:{}:{} is found in cache",
1093
18.4E
                                  _file_reader->path().native(), _file_reader->size(),
1094
18.4E
                                  _file_reader->size() - 12);
1095
832k
    }
1096
926k
    footer_pb_shared = cache_handle.get<std::shared_ptr<SegmentFooterPB>>();
1097
926k
    _footer_pb = footer_pb_shared;
1098
926k
    footer_pb = footer_pb_shared;
1099
926k
    return Status::OK();
1100
926k
}
1101
1102
964k
StoragePageCache::CacheKey Segment::get_segment_footer_cache_key() const {
1103
964k
    DCHECK(_file_reader != nullptr);
1104
    // The footer is always at the end of the segment file.
1105
    // The size of footer is 12.
1106
    // So we use the size of file minus 12 as the cache key, which is unique for each segment file.
1107
964k
    return get_segment_footer_cache_key(_file_reader);
1108
964k
}
1109
1110
StoragePageCache::CacheKey Segment::get_segment_footer_cache_key(
1111
964k
        const io::FileReaderSPtr& file_reader) {
1112
964k
    return {file_reader->path().native(), file_reader->size(),
1113
964k
            static_cast<int64_t>(file_reader->size() - 12)};
1114
964k
}
1115
1116
} // namespace doris::segment_v2