Coverage Report

Created: 2026-04-02 14:31

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