Coverage Report

Created: 2026-05-17 09:00

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