Coverage Report

Created: 2026-05-22 14:16

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