Coverage Report

Created: 2026-06-12 08:09

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