Coverage Report

Created: 2026-03-19 09:50

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