Coverage Report

Created: 2026-07-14 09:15

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 <set>
30
#include <sstream>
31
#include <utility>
32
33
#include "cloud/config.h"
34
#include "common/config.h"
35
#include "common/exception.h"
36
#include "common/logging.h"
37
#include "common/status.h"
38
#include "core/column/column.h"
39
#include "core/data_type/data_type.h"
40
#include "core/data_type/data_type_factory.hpp"
41
#include "core/data_type/data_type_nullable.h"
42
#include "core/data_type/data_type_variant.h"
43
#include "core/field.h"
44
#include "core/string_ref.h"
45
#include "cpp/sync_point.h"
46
#include "exprs/expr_zonemap_filter.h"
47
#include "exprs/vexpr_context.h"
48
#include "io/cache/block_file_cache.h"
49
#include "io/cache/block_file_cache_factory.h"
50
#include "io/cache/cached_remote_file_reader.h"
51
#include "io/fs/file_reader.h"
52
#include "io/fs/file_system.h"
53
#include "io/io_common.h"
54
#include "runtime/exec_env.h"
55
#include "runtime/query_context.h"
56
#include "runtime/runtime_predicate.h"
57
#include "runtime/runtime_state.h"
58
#include "storage/index/index_file_reader.h"
59
#include "storage/index/indexed_column_reader.h"
60
#include "storage/index/primary_key_index.h"
61
#include "storage/index/short_key_index.h"
62
#include "storage/index/zone_map/zonemap_eval_context.h"
63
#include "storage/iterator/vgeneric_iterators.h"
64
#include "storage/iterators.h"
65
#include "storage/key_coder.h"
66
#include "storage/olap_common.h"
67
#include "storage/predicate/block_column_predicate.h"
68
#include "storage/predicate/column_predicate.h"
69
#include "storage/rowset/rowset_reader_context.h"
70
#include "storage/schema.h"
71
#include "storage/segment/column_meta_accessor.h"
72
#include "storage/segment/column_reader.h"
73
#include "storage/segment/column_reader_cache.h"
74
#include "storage/segment/empty_segment_iterator.h"
75
#include "storage/segment/page_io.h"
76
#include "storage/segment/page_pointer.h"
77
#include "storage/segment/segment_iterator.h"
78
#include "storage/segment/segment_writer.h" // k_segment_magic_length
79
#include "storage/segment/stream_reader.h"
80
#include "storage/segment/variant/variant_column_reader.h"
81
#include "storage/tablet/tablet_schema.h"
82
#include "storage/types.h"
83
#include "storage/utils.h"
84
#include "util/coding.h"
85
#include "util/json/path_in_data.h"
86
#include "util/slice.h" // Slice
87
88
namespace doris::segment_v2 {
89
90
class InvertedIndexIterator;
91
92
namespace {
93
94
Status build_segment_zonemap_context(Segment* segment, const Schema& schema,
95
                                     const StorageReadOptions& read_options,
96
17.0k
                                     const VExprContextSPtrs& conjuncts, ZoneMapEvalContext* ctx) {
97
17.0k
    DORIS_CHECK(segment != nullptr);
98
17.0k
    DORIS_CHECK(ctx != nullptr);
99
17.0k
    std::set<int> slot_indexes;
100
19.2k
    for (const auto& conjunct : conjuncts) {
101
19.2k
        DORIS_CHECK(conjunct != nullptr);
102
19.2k
        const auto& root = conjunct->root();
103
19.2k
        DORIS_CHECK(root != nullptr);
104
19.2k
        if (!root->can_evaluate_zonemap_filter()) {
105
17.4k
            continue;
106
17.4k
        }
107
        // Segment zone maps have one min/max/null summary per column for the whole segment, so a
108
        // segment-level context can safely hold every slot referenced by a compound expression.
109
        // Page zone maps are page-aligned per column and still use single-slot filtering in
110
        // SegmentIterator.
111
1.85k
        root->collect_slot_column_ids(slot_indexes);
112
1.85k
    }
113
17.0k
    for (const int slot_index : slot_indexes) {
114
3.02k
        if (slot_index < 0 || cast_set<size_t>(slot_index) >= schema.num_column_ids()) {
115
0
            continue;
116
0
        }
117
3.02k
        const auto column_id = schema.column_id(cast_set<size_t>(slot_index));
118
3.02k
        const auto* tablet_column = schema.column(column_id);
119
3.02k
        DORIS_CHECK(tablet_column != nullptr);
120
3.02k
        if (!segment->can_apply_predicate_safely(
121
3.02k
                    column_id, schema, read_options.target_cast_type_for_variants, read_options)) {
122
12
            continue;
123
12
        }
124
3.01k
        auto data_type = segment->get_data_type_of(*tablet_column, read_options);
125
3.01k
        if (data_type == nullptr) {
126
0
            continue;
127
0
        }
128
3.01k
        ZoneMapEvalContext::SlotZoneMap slot_zone_map;
129
3.01k
        slot_zone_map.data_type = data_type;
130
3.01k
        std::shared_ptr<ColumnReader> reader;
131
3.01k
        Status st = segment->get_column_reader(*tablet_column, &reader, read_options.stats);
132
3.01k
        if (st.is<ErrorCode::NOT_FOUND>()) {
133
26
            ctx->slots.emplace(slot_index, std::move(slot_zone_map));
134
26
            continue;
135
26
        }
136
2.98k
        RETURN_IF_ERROR(st);
137
2.98k
        if (reader != nullptr && reader->has_zone_map()) {
138
2.74k
            ZoneMap zone_map;
139
2.74k
            RETURN_IF_ERROR(reader->get_segment_zone_map(&zone_map));
140
2.74k
            slot_zone_map.zone_map = std::make_shared<ZoneMap>(std::move(zone_map));
141
2.74k
        }
142
2.98k
        ctx->slots.emplace(slot_index, std::move(slot_zone_map));
143
2.98k
    }
144
17.0k
    return Status::OK();
145
17.0k
}
146
147
726k
void fill_missing_decimal_precision(const TabletColumn& column, ColumnMetaPB* meta) {
148
726k
    auto meta_type = static_cast<FieldType>(meta->type());
149
726k
    if (meta_type != column.type()) {
150
0
        return;
151
0
    }
152
153
726k
    if (field_is_decimal_type(meta_type)) {
154
30.7k
        if ((!meta->has_precision() || meta->precision() <= 0) && column.precision() > 0) {
155
4
            meta->set_precision(column.precision());
156
4
        }
157
30.7k
        if ((!meta->has_frac() || meta->frac() < 0) && column.frac() >= 0) {
158
4
            meta->set_frac(column.frac());
159
4
        }
160
30.7k
    }
161
162
    // Complex column meta may also include storage helper children, such as
163
    // array offsets. Only schema children have matching TabletColumn subtypes.
164
726k
    int child_count =
165
726k
            std::min(meta->children_columns_size(), static_cast<int>(column.get_subtype_count()));
166
812k
    for (int i = 0; i < child_count; ++i) {
167
85.8k
        fill_missing_decimal_precision(column.get_sub_column(i), meta->mutable_children_columns(i));
168
85.8k
    }
169
726k
}
170
171
void fill_missing_decimal_precision_from_schema(const TabletSchemaSPtr& tablet_schema,
172
721k
                                                ColumnMetaPB* meta) {
173
721k
    if (!meta->has_unique_id()) {
174
0
        return;
175
0
    }
176
721k
    int32_t col_idx = tablet_schema->field_index(static_cast<int32_t>(meta->unique_id()));
177
721k
    if (col_idx < 0) {
178
80.0k
        return;
179
80.0k
    }
180
640k
    fill_missing_decimal_precision(tablet_schema->column(col_idx), meta);
181
640k
}
182
183
void fill_footer_missing_decimal_precision(const TabletSchemaSPtr& tablet_schema,
184
95.8k
                                           SegmentFooterPB* footer) {
185
817k
    for (int i = 0; i < footer->columns_size(); ++i) {
186
721k
        fill_missing_decimal_precision_from_schema(tablet_schema, footer->mutable_columns(i));
187
721k
    }
188
95.8k
}
189
190
} // namespace
191
192
Status Segment::open(io::FileSystemSPtr fs, const std::string& path, int64_t tablet_id,
193
                     uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
194
                     const io::FileReaderOptions& reader_options, std::shared_ptr<Segment>* output,
195
872k
                     InvertedIndexFileInfo idx_file_info, OlapReaderStatistics* stats) {
196
    // Ensure tablet_id is available in reader_options for CachedRemoteFileReader peer read.
197
872k
    io::FileReaderOptions opts_with_tablet = reader_options;
198
872k
    opts_with_tablet.tablet_id = tablet_id;
199
200
872k
    auto s = _open(fs, path, segment_id, rowset_id, tablet_schema, opts_with_tablet, output,
201
872k
                   idx_file_info, stats);
202
874k
    if (s.ok() && output && *output) {
203
874k
        (*output)->_tablet_id = tablet_id;
204
874k
    }
205
872k
    if (!s.ok()) {
206
5
        if (!config::is_cloud_mode()) {
207
5
            auto res = ExecEnv::get_tablet(tablet_id);
208
5
            TabletSharedPtr tablet =
209
5
                    res.has_value() ? std::dynamic_pointer_cast<Tablet>(res.value()) : nullptr;
210
5
            if (tablet) {
211
0
                tablet->report_error(s);
212
0
            }
213
5
        }
214
5
    }
215
216
872k
    return s;
217
872k
}
218
219
Status Segment::_open(io::FileSystemSPtr fs, const std::string& path, uint32_t segment_id,
220
                      RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
221
                      const io::FileReaderOptions& reader_options, std::shared_ptr<Segment>* output,
222
872k
                      InvertedIndexFileInfo idx_file_info, OlapReaderStatistics* stats) {
223
872k
    io::FileReaderSPtr file_reader;
224
872k
    auto st = fs->open_file(path, &file_reader, &reader_options);
225
872k
    TEST_INJECTION_POINT_CALLBACK("Segment::open:corruption", &st);
226
872k
    std::shared_ptr<Segment> segment(
227
872k
            new Segment(segment_id, rowset_id, std::move(tablet_schema), idx_file_info));
228
872k
    segment->_seg_path = path;
229
874k
    if (st) {
230
874k
        segment->_fs = fs;
231
874k
        segment->_file_reader = std::move(file_reader);
232
874k
        st = segment->_open(stats);
233
874k
    }
234
235
    // Three-tier retry for CORRUPTION errors when file cache is enabled.
236
    // This handles CORRUPTION from both open_file() and _parse_footer() (via _open()).
237
872k
    if (st.is<ErrorCode::CORRUPTION>() &&
238
872k
        reader_options.cache_type == io::FileCachePolicy::FILE_BLOCK_CACHE) {
239
        // Tier 1: Clear file cache and retry with cache support (re-downloads from remote).
240
2
        LOG(WARNING) << "bad segment file may be read from file cache, try to read remote source "
241
2
                        "file directly, file path: "
242
2
                     << path << " cache_key: " << file_cache_key_str(path);
243
2
        auto file_key = file_cache_key_from_path(path);
244
2
        auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
245
2
        file_cache->remove_if_cached(file_key);
246
247
2
        st = fs->open_file(path, &file_reader, &reader_options);
248
2
        if (st) {
249
2
            segment->_fs = fs;
250
2
            segment->_file_reader = std::move(file_reader);
251
2
            st = segment->_open(stats);
252
2
        }
253
2
        TEST_INJECTION_POINT_CALLBACK("Segment::open:corruption1", &st);
254
2
        if (st.is<ErrorCode::CORRUPTION>()) { // corrupt again
255
            // Tier 2: Bypass cache entirely and read directly from remote storage.
256
0
            LOG(WARNING) << "failed to try to read remote source file again with cache support,"
257
0
                         << " try to read from remote directly, "
258
0
                         << " file path: " << path << " cache_key: " << file_cache_key_str(path);
259
0
            file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
260
0
            file_cache->remove_if_cached(file_key);
261
262
0
            io::FileReaderOptions opt = reader_options;
263
0
            opt.cache_type = io::FileCachePolicy::NO_CACHE; // skip cache
264
0
            RETURN_IF_ERROR(fs->open_file(path, &file_reader, &opt));
265
0
            segment->_fs = fs;
266
0
            segment->_file_reader = std::move(file_reader);
267
0
            st = segment->_open(stats);
268
0
            if (!st.ok()) {
269
                // Tier 3: Remote source itself is corrupt.
270
0
                LOG(WARNING) << "failed to try to read remote source file directly,"
271
0
                             << " file path: " << path
272
0
                             << " cache_key: " << file_cache_key_str(path);
273
0
            }
274
0
        }
275
2
    }
276
872k
    RETURN_IF_ERROR(st);
277
18.4E
    DCHECK(segment->_fs != nullptr) << "file system is nullptr after segment open";
278
872k
    *output = std::move(segment);
279
872k
    return Status::OK();
280
872k
}
281
282
Segment::Segment(uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
283
                 InvertedIndexFileInfo idx_file_info)
284
874k
        : _segment_id(segment_id),
285
874k
          _meta_mem_usage(0),
286
874k
          _rowset_id(rowset_id),
287
874k
          _tablet_schema(std::move(tablet_schema)),
288
874k
          _idx_file_info(std::move(idx_file_info)) {}
289
290
840k
Segment::~Segment() {
291
840k
    g_segment_estimate_mem_bytes << -_tracked_meta_mem_usage;
292
    // if failed, fix `_tracked_meta_mem_usage` accuracy
293
840k
    DCHECK(_tracked_meta_mem_usage == meta_mem_usage());
294
840k
}
295
296
94.5k
io::UInt128Wrapper Segment::file_cache_key(std::string_view rowset_id, uint32_t seg_id) {
297
94.5k
    return io::BlockFileCache::hash(fmt::format("{}_{}.dat", rowset_id, seg_id));
298
94.5k
}
299
300
870k
int64_t Segment::get_metadata_size() const {
301
870k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared = _footer_pb.lock();
302
870k
    return sizeof(Segment) + (_pk_index_meta ? _pk_index_meta->ByteSizeLong() : 0) +
303
18.4E
           (footer_pb_shared ? footer_pb_shared->ByteSizeLong() : 0);
304
870k
}
305
306
871k
void Segment::update_metadata_size() {
307
871k
    MetadataAdder::update_metadata_size();
308
871k
    g_segment_estimate_mem_bytes << _meta_mem_usage - _tracked_meta_mem_usage;
309
871k
    _tracked_meta_mem_usage = _meta_mem_usage;
310
871k
}
311
312
873k
Status Segment::_open(OlapReaderStatistics* stats) {
313
873k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared;
314
873k
    RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, stats));
315
316
873k
    _pk_index_meta.reset(
317
873k
            footer_pb_shared->has_primary_key_index_meta()
318
873k
                    ? new PrimaryKeyIndexMetaPB(footer_pb_shared->primary_key_index_meta())
319
873k
                    : nullptr);
320
    // delete_bitmap_calculator_test.cpp
321
    // DCHECK(footer.has_short_key_index_page());
322
873k
    _sk_index_page = footer_pb_shared->short_key_index_page();
323
873k
    _num_rows = footer_pb_shared->num_rows();
324
325
    // An estimated memory usage of a segment
326
    // Footer is seperated to StoragePageCache so we don't need to add it to _meta_mem_usage
327
    // _meta_mem_usage += footer_pb_shared->ByteSizeLong();
328
873k
    if (_pk_index_meta != nullptr) {
329
770k
        _meta_mem_usage += _pk_index_meta->ByteSizeLong();
330
770k
    }
331
332
873k
    _meta_mem_usage += sizeof(*this);
333
873k
    _meta_mem_usage += std::min(static_cast<int>(_tablet_schema->num_columns()),
334
873k
                                config::max_segment_partial_column_cache_size) *
335
873k
                       config::estimated_mem_per_column_reader;
336
337
    // 1024 comes from SegmentWriterOptions
338
873k
    _meta_mem_usage += (_num_rows + 1023) / 1024 * (36 + 4);
339
    // 0.01 comes from PrimaryKeyIndexBuilder::init
340
873k
    _meta_mem_usage += BloomFilter::optimal_bit_num(_num_rows, 0.01) / 8;
341
342
873k
    update_metadata_size();
343
344
873k
    return Status::OK();
345
873k
}
346
347
5.64k
Status Segment::_open_index_file_reader() {
348
    // Derive the index path from `_seg_path`, not `_file_reader->path()`: remote FS normalizes the
349
    // latter to an absolute path that won't match the relative keys in PackedFileSystem's index map.
350
5.64k
    _index_file_reader = std::make_shared<IndexFileReader>(
351
5.64k
            _fs, std::string {InvertedIndexDescriptor::get_index_file_path_prefix(_seg_path)},
352
5.64k
            _tablet_schema->get_inverted_index_storage_format(), _idx_file_info, _tablet_id);
353
5.64k
    return Status::OK();
354
5.64k
}
355
356
bool Segment::is_tso_placeholder_col(int cid, const Schema& schema,
357
1.99M
                                     const StorageReadOptions& read_options) const {
358
1.99M
    if (read_options.version.first != read_options.version.second) {
359
1.10M
        return false;
360
1.10M
    }
361
891k
    if (read_options.io_ctx.reader_type != ReaderType::READER_BINLOG &&
362
893k
        read_options.io_ctx.reader_type != ReaderType::READER_BINLOG_COMPACTION) {
363
893k
        return false;
364
893k
    }
365
    // tso_col_idx() is -1 for non-binlog schemas, so this returns false there.
366
18.4E
    return cid == schema.tso_col_idx();
367
891k
}
368
369
Status Segment::new_iterator(SchemaSPtr schema, const StorageReadOptions& read_options,
370
2.16M
                             std::unique_ptr<RowwiseIterator>* iter) {
371
2.16M
    if (read_options.runtime_state != nullptr) {
372
2.04M
        _be_exec_version = read_options.runtime_state->be_exec_version();
373
2.04M
    }
374
2.16M
    RETURN_IF_ERROR(_create_column_meta_once(read_options.stats));
375
376
2.16M
    read_options.stats->total_segment_number++;
377
    // trying to prune the current segment by segment-level zone map
378
2.16M
    for (const auto& entry : read_options.col_id_to_predicates) {
379
1.86M
        int32_t column_id = entry.first;
380
        // schema change
381
1.86M
        if (_tablet_schema->num_columns() <= column_id) {
382
1.33k
            continue;
383
1.33k
        }
384
1.86M
        const TabletColumn& col = read_options.tablet_schema->column(column_id);
385
1.86M
        std::shared_ptr<ColumnReader> reader;
386
        // __DORIS_COMMIT_TSO_COL__ on a single-version segment stores a 0 placeholder on disk
387
        // (replaced with the rowset's real commit_tso at read time). Its on-disk zonemap [0,0]
388
        // must not drive segment-level pruning, so build a ConstantColumnReader carrying the real
389
        // commit_tso to prune against the real value instead.
390
1.86M
        std::optional<Field> const_value;
391
1.86M
        if (read_options.version.first == read_options.version.second &&
392
1.86M
            column_id == schema->commit_tso_col_idx() && read_options.commit_tso.end_tso() != -1) {
393
1
            const_value = Field::create_field<TYPE_BIGINT>(read_options.commit_tso.end_tso());
394
1
        }
395
1.86M
        Status st = get_column_reader(col, &reader, read_options.stats, std::move(const_value));
396
        // not found in this segment, skip
397
1.86M
        if (st.is<ErrorCode::NOT_FOUND>()) {
398
146
            continue;
399
146
        }
400
1.86M
        RETURN_IF_ERROR(st);
401
        // should be OK
402
1.86M
        DCHECK(reader != nullptr);
403
1.86M
        if (!reader->has_zone_map()) {
404
0
            continue;
405
0
        }
406
        // Placeholder tso column on a single-version binlog segment: its zonemap reflects the
407
        // NULL placeholder (replaced with commit_tso at read time), so skip pruning by
408
        // zonemap (min == max == commit_tso) and reuse the predicate's own zonemap matching:
409
        // evaluate_and() returns false iff no value in [min, max] can satisfy the predicates,
410
        // i.e. commit_tso fails them and the whole segment can be pruned. Predicates that don't
411
        // support zonemap return true (conservative: not pruned, row-level eval handles them).
412
1.86M
        if (read_options.col_id_to_predicates.contains(column_id) &&
413
1.86M
            is_tso_placeholder_col(column_id, *schema, read_options)) {
414
0
            const Int64 commit_tso =
415
0
                    read_options.commit_tso.end_tso() == -1 ? 0 : read_options.commit_tso.end_tso();
416
0
            ZoneMap zone_map;
417
0
            zone_map.min_value = Field::create_field<TYPE_BIGINT>(commit_tso);
418
0
            zone_map.max_value = Field::create_field<TYPE_BIGINT>(commit_tso);
419
0
            zone_map.has_not_null = true;
420
0
            if (!entry.second->evaluate_and(zone_map)) {
421
                // any condition not satisfied, return.
422
0
                *iter = std::make_unique<EmptySegmentIterator>(*schema);
423
0
                read_options.stats->filtered_segment_number++;
424
0
                return Status::OK();
425
0
            }
426
0
            continue;
427
0
        }
428
1.86M
        if (read_options.col_id_to_predicates.contains(column_id) &&
429
1.86M
            can_apply_predicate_safely(column_id, *schema,
430
1.85M
                                       read_options.target_cast_type_for_variants, read_options)) {
431
1.85M
            bool matched = true;
432
1.85M
            RETURN_IF_ERROR(reader->match_condition(entry.second.get(), &matched));
433
1.85M
            if (!matched) {
434
                // any condition not satisfied, return.
435
116k
                *iter = std::make_unique<EmptySegmentIterator>(*schema);
436
116k
                read_options.stats->filtered_segment_number++;
437
116k
                read_options.stats->rows_stats_filtered += num_rows();
438
116k
                return Status::OK();
439
116k
            }
440
1.85M
        }
441
1.86M
    }
442
443
    // Segment-level expr-zonemap runs before SegmentIterator can rebind storage expressions to
444
    // the reader schema. Only apply it when scan tuple slot ordinals already match this schema.
445
2.05M
    if (expr_zonemap::is_expr_zonemap_filter_enabled(read_options.runtime_state) &&
446
2.05M
        !read_options.common_expr_ctxs_push_down.empty()) {
447
17.0k
        ZoneMapEvalContext ctx;
448
17.0k
        RETURN_IF_ERROR(build_segment_zonemap_context(
449
17.0k
                this, *schema, read_options, read_options.common_expr_ctxs_push_down, &ctx));
450
17.0k
        const auto result =
451
17.0k
                VExprContext::evaluate_zonemap_filter(read_options.common_expr_ctxs_push_down, ctx);
452
17.0k
        ctx.stats.accumulate_to(read_options.stats);
453
17.0k
        if (result == ZoneMapFilterResult::kNoMatch) {
454
356
            *iter = std::make_unique<EmptySegmentIterator>(*schema);
455
356
            read_options.stats->filtered_segment_number++;
456
356
            read_options.stats->expr_zonemap_filtered_segments++;
457
356
            return Status::OK();
458
356
        }
459
17.0k
    }
460
461
2.05M
    {
462
2.05M
        SCOPED_RAW_TIMER(&read_options.stats->segment_load_index_timer_ns);
463
2.05M
        RETURN_IF_ERROR(load_index(read_options.stats));
464
2.05M
    }
465
466
2.05M
    if (read_options.delete_condition_predicates->num_of_column_predicate() == 0 &&
467
2.05M
        read_options.push_down_agg_type_opt != TPushAggOp::NONE &&
468
2.05M
        read_options.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
469
34.2k
        iter->reset(new_vstatistics_iterator(this->shared_from_this(), *schema));
470
2.01M
    } else {
471
2.01M
        *iter = std::make_unique<SegmentIterator>(this->shared_from_this(), schema);
472
2.01M
    }
473
474
    // TODO: Valid the opt not only in ReaderType::READER_QUERY
475
2.05M
    if (read_options.io_ctx.reader_type == ReaderType::READER_QUERY &&
476
2.05M
        !read_options.column_predicates.empty()) {
477
1.70M
        auto pruned_predicates = read_options.column_predicates;
478
1.70M
        auto pruned = false;
479
17.1M
        for (auto& it : _column_reader_cache->get_available_readers(false)) {
480
17.1M
            const auto uid = it.first;
481
17.1M
            const auto column_id = read_options.tablet_schema->field_index(uid);
482
17.1M
            bool tmp_pruned = false;
483
17.1M
            RETURN_IF_ERROR(it.second->prune_predicates_by_zone_map(pruned_predicates, column_id,
484
17.1M
                                                                    &tmp_pruned));
485
17.1M
            pruned |= tmp_pruned;
486
17.1M
        }
487
488
1.70M
        if (pruned) {
489
7.99k
            auto options_with_pruned_predicates = read_options;
490
7.99k
            options_with_pruned_predicates.column_predicates = pruned_predicates;
491
            //because column_predicates is changed, we need to rebuild col_id_to_predicates so that inverted index will not go through it.
492
7.99k
            options_with_pruned_predicates.col_id_to_predicates.clear();
493
13.6k
            for (auto pred : options_with_pruned_predicates.column_predicates) {
494
13.6k
                if (!options_with_pruned_predicates.col_id_to_predicates.contains(
495
13.6k
                            pred->column_id())) {
496
8.78k
                    options_with_pruned_predicates.col_id_to_predicates.insert(
497
8.78k
                            {pred->column_id(), AndBlockColumnPredicate::create_shared()});
498
8.78k
                }
499
13.6k
                options_with_pruned_predicates.col_id_to_predicates[pred->column_id()]
500
13.6k
                        ->add_column_predicate(SingleColumnBlockPredicate::create_unique(pred));
501
13.6k
            }
502
27.4k
            for (const auto& pred : read_options.column_predicates) {
503
27.4k
                const auto pred_cid = pred->column_id();
504
                // Key columns may still be required by key range seeks even if the segment zone
505
                // map proves their predicates always true. Only mark non-key columns as safe for
506
                // the no-need-read path.
507
27.4k
                if (!read_options.tablet_schema->column(pred_cid).is_key() &&
508
27.4k
                    !options_with_pruned_predicates.col_id_to_predicates.contains(pred_cid)) {
509
5.68k
                    options_with_pruned_predicates.zonemap_always_true_pred_cols.insert(pred_cid);
510
5.68k
                }
511
27.4k
            }
512
7.99k
            return iter->get()->init(options_with_pruned_predicates);
513
7.99k
        }
514
1.70M
    }
515
2.04M
    return iter->get()->init(read_options);
516
2.05M
}
517
518
Status Segment::_write_error_file(size_t file_size, size_t offset, size_t bytes_read, char* data,
519
1
                                  io::IOContext& io_ctx) {
520
1
    if (!config::enbale_dump_error_file || !doris::config::is_cloud_mode()) {
521
1
        return Status::OK();
522
1
    }
523
524
0
    std::string file_name = _rowset_id.to_string() + "_" + std::to_string(_segment_id) + ".dat";
525
0
    std::string dir_path = io::FileCacheFactory::instance()->get_base_paths()[0] + "/error_file/";
526
0
    Status create_st = io::global_local_filesystem()->create_directory(dir_path, true);
527
0
    if (!create_st.ok() && !create_st.is<ErrorCode::ALREADY_EXIST>()) {
528
0
        LOG(WARNING) << "failed to create error file dir: " << create_st.to_string();
529
0
        return create_st;
530
0
    }
531
0
    size_t dir_size = 0;
532
0
    RETURN_IF_ERROR(io::global_local_filesystem()->directory_size(dir_path, &dir_size));
533
0
    if (dir_size > config::file_cache_error_log_limit_bytes) {
534
0
        LOG(WARNING) << "error file dir size is too large: " << dir_size;
535
0
        return Status::OK();
536
0
    }
537
538
0
    std::string error_part;
539
0
    error_part.resize(bytes_read);
540
0
    std::string part_path = dir_path + file_name + ".part_offset_" + std::to_string(offset);
541
0
    LOG(WARNING) << "writer error part to " << part_path;
542
0
    bool is_part_exist = false;
543
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(part_path, &is_part_exist));
544
0
    if (is_part_exist) {
545
0
        LOG(WARNING) << "error part already exists: " << part_path;
546
0
    } else {
547
0
        std::unique_ptr<io::FileWriter> part_writer;
548
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_file(part_path, &part_writer));
549
0
        RETURN_IF_ERROR(part_writer->append(Slice(data, bytes_read)));
550
0
        RETURN_IF_ERROR(part_writer->close());
551
0
    }
552
553
0
    std::string error_file;
554
0
    error_file.resize(file_size);
555
0
    auto* cached_reader = dynamic_cast<io::CachedRemoteFileReader*>(_file_reader.get());
556
0
    if (cached_reader == nullptr) {
557
0
        return Status::InternalError("file reader is not CachedRemoteFileReader");
558
0
    }
559
0
    size_t error_file_bytes_read = 0;
560
0
    RETURN_IF_ERROR(cached_reader->get_remote_reader()->read_at(
561
0
            0, Slice(error_file.data(), file_size), &error_file_bytes_read, &io_ctx));
562
0
    DCHECK(error_file_bytes_read == file_size);
563
    //std::string file_path = dir_path + std::to_string(cur_time) + "_" + ss.str();
564
0
    std::string file_path = dir_path + file_name;
565
0
    LOG(WARNING) << "writer error file to " << file_path;
566
0
    bool is_file_exist = false;
567
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(file_path, &is_file_exist));
568
0
    if (is_file_exist) {
569
0
        LOG(WARNING) << "error file already exists: " << part_path;
570
0
    } else {
571
0
        std::unique_ptr<io::FileWriter> writer;
572
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_file(file_path, &writer));
573
0
        RETURN_IF_ERROR(writer->append(Slice(error_file.data(), file_size)));
574
0
        RETURN_IF_ERROR(writer->close());
575
0
    }
576
0
    return Status::OK(); // already exists
577
0
};
578
579
Status Segment::_parse_footer(std::shared_ptr<SegmentFooterPB>& footer,
580
95.8k
                              OlapReaderStatistics* stats) {
581
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
582
95.8k
    auto file_size = _file_reader->size();
583
95.8k
    if (file_size < 12) {
584
0
        return Status::Corruption("Bad segment file {}: file size {} < 12, cache_key: {}",
585
0
                                  _file_reader->path().native(), file_size,
586
0
                                  file_cache_key_str(_file_reader->path().native()));
587
0
    }
588
589
95.8k
    uint8_t fixed_buf[12];
590
95.8k
    size_t bytes_read = 0;
591
    // TODO(plat1ko): Support session variable `enable_file_cache`
592
95.8k
    io::IOContext io_ctx {.is_index_data = true,
593
95.8k
                          .file_cache_stats = stats ? &stats->file_cache_stats : nullptr};
594
95.8k
    RETURN_IF_ERROR(
595
95.8k
            _file_reader->read_at(file_size - 12, Slice(fixed_buf, 12), &bytes_read, &io_ctx));
596
95.8k
    DCHECK_EQ(bytes_read, 12);
597
95.8k
    TEST_SYNC_POINT_CALLBACK("Segment::parse_footer:magic_number_corruption", fixed_buf);
598
95.8k
    TEST_INJECTION_POINT_CALLBACK("Segment::parse_footer:magic_number_corruption_inj", fixed_buf);
599
95.8k
    if (memcmp(fixed_buf + 8, k_segment_magic, k_segment_magic_length) != 0) {
600
1
        Status st =
601
1
                _write_error_file(file_size, file_size - 12, bytes_read, (char*)fixed_buf, io_ctx);
602
1
        if (!st.ok()) {
603
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
604
0
        }
605
1
        return Status::Corruption(
606
1
                "Bad segment file {}: file_size: {}, magic number not match, cache_key: {}",
607
1
                _file_reader->path().native(), file_size,
608
1
                file_cache_key_str(_file_reader->path().native()));
609
1
    }
610
611
    // read footer PB
612
95.8k
    uint32_t footer_length = decode_fixed32_le(fixed_buf);
613
95.8k
    if (file_size < 12 + footer_length) {
614
0
        Status st =
615
0
                _write_error_file(file_size, file_size - 12, bytes_read, (char*)fixed_buf, io_ctx);
616
0
        if (!st.ok()) {
617
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
618
0
        }
619
0
        return Status::Corruption("Bad segment file {}: file size {} < {}, cache_key: {}",
620
0
                                  _file_reader->path().native(), file_size, 12 + footer_length,
621
0
                                  file_cache_key_str(_file_reader->path().native()));
622
0
    }
623
624
95.8k
    std::string footer_buf;
625
95.8k
    footer_buf.resize(footer_length);
626
95.8k
    RETURN_IF_ERROR(_file_reader->read_at(file_size - 12 - footer_length, footer_buf, &bytes_read,
627
95.8k
                                          &io_ctx));
628
95.8k
    DCHECK_EQ(bytes_read, footer_length);
629
630
    // validate footer PB's checksum
631
95.8k
    uint32_t expect_checksum = decode_fixed32_le(fixed_buf + 4);
632
95.8k
    uint32_t actual_checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
633
95.8k
    if (actual_checksum != expect_checksum) {
634
0
        Status st = _write_error_file(file_size, file_size - 12 - footer_length, bytes_read,
635
0
                                      footer_buf.data(), io_ctx);
636
0
        if (!st.ok()) {
637
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
638
0
        }
639
0
        return Status::Corruption(
640
0
                "Bad segment file {}: file_size = {}, footer checksum not match, actual={} "
641
0
                "vs expect={}, cache_key: {}",
642
0
                _file_reader->path().native(), file_size, actual_checksum, expect_checksum,
643
0
                file_cache_key_str(_file_reader->path().native()));
644
0
    }
645
646
    // deserialize footer PB
647
95.8k
    footer = std::make_shared<SegmentFooterPB>();
648
95.8k
    if (!footer->ParseFromString(footer_buf)) {
649
0
        Status st = _write_error_file(file_size, file_size - 12 - footer_length, bytes_read,
650
0
                                      footer_buf.data(), io_ctx);
651
0
        if (!st.ok()) {
652
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
653
0
        }
654
0
        return Status::Corruption(
655
0
                "Bad segment file {}: file_size = {}, failed to parse SegmentFooterPB, "
656
0
                "cache_key: ",
657
0
                _file_reader->path().native(), file_size,
658
0
                file_cache_key_str(_file_reader->path().native()));
659
0
    }
660
    // Segments written before #26572 do not persist decimal precision/frac in
661
    // ColumnMetaPB, so recover the logical p/s from TabletSchema before
662
    // ColumnReader builds DataTypeDecimal.
663
95.8k
    fill_footer_missing_decimal_precision(_tablet_schema, footer.get());
664
665
18.4E
    VLOG_DEBUG << fmt::format("Loading segment footer from {} finished",
666
18.4E
                              _file_reader->path().native());
667
95.8k
    return Status::OK();
668
95.8k
}
669
670
3.77M
Status Segment::_load_pk_bloom_filter(OlapReaderStatistics* stats) {
671
#ifdef BE_TEST
672
    if (_pk_index_meta == nullptr) {
673
        // for BE UT "segment_cache_test"
674
        return _load_pk_bf_once.call([this] {
675
            _meta_mem_usage += 100;
676
            update_metadata_size();
677
            return Status::OK();
678
        });
679
    }
680
#endif
681
3.77M
    DCHECK(_tablet_schema->keys_type() == UNIQUE_KEYS);
682
3.77M
    DCHECK(_pk_index_meta != nullptr);
683
3.77M
    DCHECK(_pk_index_reader != nullptr);
684
685
3.77M
    return _load_pk_bf_once.call([this, stats] {
686
56.4k
        RETURN_IF_ERROR(_pk_index_reader->parse_bf(_file_reader, *_pk_index_meta, stats));
687
        // _meta_mem_usage += _pk_index_reader->get_bf_memory_size();
688
56.4k
        return Status::OK();
689
56.4k
    });
690
3.77M
}
691
692
3.79M
Status Segment::load_pk_index_and_bf(OlapReaderStatistics* index_load_stats) {
693
    // `DorisCallOnce` may catch exception in calling stack A and re-throw it in
694
    // a different calling stack B which doesn't have catch block. So we add catch block here
695
    // to prevent coreudmp
696
3.79M
    RETURN_IF_CATCH_EXCEPTION({
697
3.79M
        RETURN_IF_ERROR(load_index(index_load_stats));
698
3.79M
        RETURN_IF_ERROR(_load_pk_bloom_filter(index_load_stats));
699
3.79M
    });
700
3.79M
    return Status::OK();
701
3.79M
}
702
703
5.86M
Status Segment::load_index(OlapReaderStatistics* stats) {
704
5.86M
    return _load_index_once.call([this, stats] {
705
716k
        if (_tablet_schema->keys_type() == UNIQUE_KEYS && _pk_index_meta != nullptr) {
706
641k
            _pk_index_reader = std::make_unique<PrimaryKeyIndexReader>();
707
641k
            RETURN_IF_ERROR(_pk_index_reader->parse_index(_file_reader, *_pk_index_meta, stats));
708
            // _meta_mem_usage += _pk_index_reader->get_memory_size();
709
641k
            return Status::OK();
710
641k
        } else {
711
            // read and parse short key index page
712
74.4k
            OlapReaderStatistics tmp_stats;
713
74.4k
            OlapReaderStatistics* stats_ptr = stats != nullptr ? stats : &tmp_stats;
714
74.4k
            PageReadOptions opts(io::IOContext {.is_index_data = true,
715
74.4k
                                                .file_cache_stats = &stats_ptr->file_cache_stats});
716
74.4k
            opts.use_page_cache = true;
717
74.4k
            opts.type = INDEX_PAGE;
718
74.4k
            opts.file_reader = _file_reader.get();
719
74.4k
            opts.page_pointer = PagePointer(_sk_index_page);
720
            // short key index page uses NO_COMPRESSION for now
721
74.4k
            opts.codec = nullptr;
722
74.4k
            opts.stats = &tmp_stats;
723
724
74.4k
            Slice body;
725
74.4k
            PageFooterPB footer;
726
74.4k
            RETURN_IF_ERROR(
727
74.4k
                    PageIO::read_and_decompress_page(opts, &_sk_index_handle, &body, &footer));
728
74.4k
            DCHECK_EQ(footer.type(), SHORT_KEY_PAGE);
729
74.4k
            DCHECK(footer.has_short_key_page_footer());
730
731
            // _meta_mem_usage += body.get_size();
732
74.4k
            _sk_index_decoder = std::make_unique<ShortKeyIndexDecoder>();
733
74.4k
            return _sk_index_decoder->parse(body, footer.short_key_page_footer());
734
74.4k
        }
735
716k
    });
736
5.86M
}
737
738
1.56M
Status Segment::healthy_status() {
739
1.56M
    try {
740
1.56M
        if (_load_index_once.has_called()) {
741
1.51M
            RETURN_IF_ERROR(_load_index_once.stored_result());
742
1.51M
        }
743
1.56M
        if (_load_pk_bf_once.has_called()) {
744
702k
            RETURN_IF_ERROR(_load_pk_bf_once.stored_result());
745
702k
        }
746
1.56M
        if (_create_column_meta_once_call.has_called()) {
747
1.50M
            RETURN_IF_ERROR(_create_column_meta_once_call.stored_result());
748
1.50M
        }
749
1.56M
        if (_index_file_reader_open.has_called()) {
750
25.3k
            RETURN_IF_ERROR(_index_file_reader_open.stored_result());
751
25.3k
        }
752
        // This status is set by running time, for example, if there is something wrong during read segment iterator.
753
1.56M
        return _healthy_status.status();
754
1.56M
    } catch (const doris::Exception& e) {
755
        // If there is an exception during load_xxx, should not throw exception directly because
756
        // the caller may not exception safe.
757
0
        return e.to_status();
758
0
    } catch (const std::exception& e) {
759
        // The exception is not thrown by doris code.
760
0
        return Status::InternalError("Unexcepted error during load segment: {}", e.what());
761
0
    }
762
1.56M
}
763
764
// Return the storage datatype of related column to field.
765
DataTypePtr Segment::get_data_type_of(const TabletColumn& column,
766
30.6M
                                      const StorageReadOptions& read_options) {
767
30.6M
    const PathInDataPtr path = column.path_info_ptr();
768
769
    // none variant column
770
30.7M
    if (path == nullptr || path->empty()) {
771
30.7M
        return DataTypeFactory::instance().create_data_type(column);
772
30.7M
    }
773
774
    // Path exists, proceed with variant logic.
775
18.4E
    PathInData relative_path = path->copy_pop_front();
776
18.4E
    int32_t unique_id = column.unique_id() >= 0 ? column.unique_id() : column.parent_unique_id();
777
778
    // If this uid does not exist in segment meta, fallback to schema type.
779
18.4E
    if (!_column_meta_accessor->has_column_uid(unique_id)) {
780
542
        return DataTypeFactory::instance().create_data_type(column);
781
542
    }
782
783
18.4E
    std::shared_ptr<ColumnReader> v_reader;
784
785
    // Get the parent variant column reader
786
18.4E
    OlapReaderStatistics stats;
787
    // If status is not ok, it will throw exception(data corruption)
788
18.4E
    THROW_IF_ERROR(get_column_reader(unique_id, &v_reader, &stats));
789
18.4E
    DCHECK(v_reader != nullptr);
790
18.4E
    auto* variant_reader = static_cast<VariantColumnReader*>(v_reader.get());
791
    // Delegate type inference for variant paths to VariantColumnReader.
792
18.4E
    DataTypePtr type;
793
18.4E
    THROW_IF_ERROR(variant_reader->infer_data_type_for_path(&type, column, read_options,
794
18.4E
                                                            _column_reader_cache.get()));
795
18.4E
    return type;
796
18.4E
}
797
798
57.2M
Status Segment::_create_column_meta_once(OlapReaderStatistics* stats) {
799
57.2M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
800
57.2M
    return _create_column_meta_once_call.call([&] {
801
756k
        std::shared_ptr<SegmentFooterPB> footer_pb_shared;
802
756k
        RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, stats));
803
756k
        return _create_column_meta(*footer_pb_shared);
804
756k
    });
805
57.2M
}
806
807
754k
Status Segment::_create_column_meta(const SegmentFooterPB& footer) {
808
    // Initialize column meta accessor which internally maintains uid -> column_ordinal mapping.
809
754k
    _column_meta_accessor = std::make_unique<ColumnMetaAccessor>();
810
754k
    RETURN_IF_ERROR(_column_meta_accessor->init(footer, _file_reader));
811
812
754k
    if (config::enable_adaptive_batch_size) {
813
        // Cache raw_data_bytes per column uid for adaptive batch size prediction.
814
        // This runs under call_once, so no thread-safety concerns.
815
10.8M
        auto st = _column_meta_accessor->traverse_metas(footer, [this](const ColumnMetaPB& meta) {
816
10.8M
            if (meta.has_unique_id() && meta.unique_id() != -1 && meta.has_raw_data_bytes()) {
817
10.6M
                _column_uid_to_raw_bytes[meta.unique_id()] = meta.raw_data_bytes();
818
10.6M
            }
819
10.8M
        });
820
821
751k
        if (!st.ok()) {
822
0
            LOG(WARNING) << "Failed to traverse column metas to cache raw_data_bytes, error: "
823
0
                         << st.to_string();
824
0
        }
825
751k
    }
826
827
754k
    _column_reader_cache = std::make_unique<ColumnReaderCache>(
828
754k
            _column_meta_accessor.get(), _tablet_schema, _file_reader, _num_rows,
829
12.0M
            [this](std::shared_ptr<SegmentFooterPB>& footer_pb, OlapReaderStatistics* stats) {
830
12.0M
                return _get_segment_footer(footer_pb, stats);
831
12.0M
            });
832
754k
    return Status::OK();
833
754k
}
834
835
Status Segment::new_default_iterator(const TabletColumn& tablet_column,
836
13.0k
                                     std::unique_ptr<ColumnIterator>* iter) {
837
13.0k
    if (!tablet_column.has_default_value() && !tablet_column.is_nullable()) {
838
0
        return Status::InternalError(
839
0
                "invalid nonexistent column without default value. column_uid={}, "
840
0
                "column_name={}, "
841
0
                "column_type={}",
842
0
                tablet_column.unique_id(), tablet_column.name(), tablet_column.type());
843
0
    }
844
13.0k
    std::unique_ptr<DefaultValueColumnIterator> default_value_iter(new DefaultValueColumnIterator(
845
13.0k
            tablet_column.has_default_value(), tablet_column.default_value(),
846
13.0k
            tablet_column.is_nullable(), tablet_column.type(), tablet_column.precision(),
847
13.0k
            tablet_column.frac(), tablet_column.length()));
848
13.0k
    ColumnIteratorOptions iter_opts;
849
850
13.0k
    RETURN_IF_ERROR(default_value_iter->init(iter_opts));
851
13.0k
    *iter = std::move(default_value_iter);
852
13.0k
    return Status::OK();
853
13.0k
}
854
855
// Not use cid anymore, for example original table schema is colA int, then user do following actions
856
// 1.add column b
857
// 2. drop column b
858
// 3. add column c
859
// in the new schema column c's cid == 2
860
// but in the old schema column b's cid == 2
861
// but they are not the same column
862
Status Segment::new_column_iterator(const TabletColumn& tablet_column,
863
                                    std::unique_ptr<ColumnIterator>* iter,
864
                                    const StorageReadOptions* opt,
865
                                    const std::unordered_map<int32_t, PathToBinaryColumnCacheUPtr>*
866
26.5M
                                            variant_sparse_column_cache) {
867
26.5M
    if (opt->runtime_state != nullptr) {
868
26.0M
        _be_exec_version = opt->runtime_state->be_exec_version();
869
26.0M
    }
870
26.5M
    RETURN_IF_ERROR(_create_column_meta_once(opt->stats));
871
872
    // For compability reason unique_id may less than 0 for variant extracted column
873
26.6M
    int32_t unique_id = tablet_column.unique_id() >= 0 ? tablet_column.unique_id()
874
18.4E
                                                       : tablet_column.parent_unique_id();
875
876
    // If column meta for this uid is not found in this segment, use default iterator.
877
26.5M
    if (!_column_meta_accessor->has_column_uid(unique_id)) {
878
4.08k
        RETURN_IF_ERROR(new_default_iterator(tablet_column, iter));
879
4.08k
        return Status::OK();
880
4.08k
    }
881
882
    // __DORIS_COMMIT_TSO_COL__ on a single-version segment stores a 0 placeholder on disk (its
883
    // real value is the rowset's commit_tso, filled at read time). Pass the real commit_tso as a
884
    // const value so the cache returns a ConstantColumnReader, whose iterator yields the real value
885
    // on every read path (projection / predicate / MIN-MAX zone-map) instead of the placeholder 0.
886
    // commit_tso == -1 means it is not assigned yet (before publish); keep the on-disk value then.
887
    // The value is constant per segment (a segment belongs to a single rowset), so caching the
888
    // ConstantColumnReader does not cross-pollute other queries. Some internal read paths (e.g. MOW
889
    // partial-update row fetch) build a bare StorageReadOptions without tablet_schema, so guard it.
890
26.5M
    std::optional<Field> const_value;
891
26.6M
    if (opt->tablet_schema != nullptr && opt->version.first == opt->version.second &&
892
26.5M
        opt->commit_tso.end_tso() != -1) {
893
1
        int32_t tso_idx = opt->tablet_schema->commit_tso_col_idx();
894
1
        if (tso_idx != -1 && opt->tablet_schema->column(tso_idx).unique_id() == unique_id) {
895
1
            const_value = Field::create_field<TYPE_BIGINT>(opt->commit_tso.end_tso());
896
1
        }
897
1
    }
898
899
    // init iterator by unique id
900
26.5M
    std::shared_ptr<ColumnReader> reader;
901
26.5M
    RETURN_IF_ERROR(get_column_reader(unique_id, &reader, opt->stats, std::move(const_value)));
902
26.5M
    if (reader == nullptr) {
903
0
        return Status::InternalError("column reader is nullptr, unique_id={}", unique_id);
904
0
    }
905
26.5M
    if (reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT) {
906
        // if sparse_column_cache_ptr is nullptr, means the sparse column cache is not used
907
30.8k
        PathToBinaryColumnCache* sparse_column_cache_ptr = nullptr;
908
30.8k
        if (variant_sparse_column_cache) {
909
30.3k
            auto it = variant_sparse_column_cache->find(unique_id);
910
30.3k
            if (it != variant_sparse_column_cache->end()) {
911
30.3k
                sparse_column_cache_ptr = it->second.get();
912
30.3k
            } else {
913
2
                DCHECK(false) << "sparse column cache is not found, unique_id=" << unique_id;
914
2
            }
915
30.3k
        }
916
        // use _column_reader_cache to get variant subcolumn(path column) reader
917
30.8k
        RETURN_IF_ERROR(assert_cast<VariantColumnReader*>(reader.get())
918
30.8k
                                ->new_iterator(iter, &tablet_column, opt,
919
30.8k
                                               _column_reader_cache.get(),
920
30.8k
                                               sparse_column_cache_ptr));
921
26.5M
    } else {
922
26.5M
        RETURN_IF_ERROR(reader->new_iterator(iter, &tablet_column, opt));
923
26.5M
        if (opt->all_access_paths.contains(unique_id) ||
924
26.5M
            opt->predicate_access_paths.contains(unique_id)) {
925
62.3k
            const auto& all_access_paths = opt->all_access_paths.contains(unique_id)
926
62.3k
                                                   ? opt->all_access_paths.at(unique_id)
927
62.3k
                                                   : TColumnAccessPaths {};
928
62.3k
            const auto& predicate_access_paths = opt->predicate_access_paths.contains(unique_id)
929
62.3k
                                                         ? opt->predicate_access_paths.at(unique_id)
930
62.3k
                                                         : TColumnAccessPaths {};
931
932
            // set column name to apply access paths.
933
62.3k
            (*iter)->set_column_name(tablet_column.name());
934
62.3k
            RETURN_IF_ERROR((*iter)->set_access_paths(all_access_paths, predicate_access_paths));
935
62.3k
            (*iter)->remove_pruned_sub_iterators();
936
62.3k
        }
937
26.5M
    }
938
939
26.6M
    if (config::enable_column_type_check && !tablet_column.has_path_info() &&
940
26.6M
        !tablet_column.is_agg_state_type() && tablet_column.type() != reader->get_meta_type()) {
941
0
        LOG(WARNING) << "different type between schema and column reader,"
942
0
                     << " column schema name: " << tablet_column.name()
943
0
                     << " column schema type: " << int(tablet_column.type())
944
0
                     << " column reader meta type: " << int(reader->get_meta_type());
945
0
        return Status::InternalError("different type between schema and column reader");
946
0
    }
947
26.5M
    return Status::OK();
948
26.5M
}
949
950
Status Segment::get_column_reader(int32_t col_uid, std::shared_ptr<ColumnReader>* column_reader,
951
26.7M
                                  OlapReaderStatistics* stats, std::optional<Field> const_value) {
952
26.7M
    RETURN_IF_ERROR(_create_column_meta_once(stats));
953
26.7M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
954
    // The column is not in this segment, return nullptr
955
26.7M
    if (!_tablet_schema->has_column_unique_id(col_uid)) {
956
0
        *column_reader = nullptr;
957
0
        return Status::Error<ErrorCode::NOT_FOUND, false>("column not found in segment, col_uid={}",
958
0
                                                          col_uid);
959
0
    }
960
26.7M
    return _column_reader_cache->get_column_reader(col_uid, column_reader, stats,
961
26.7M
                                                   std::move(const_value));
962
26.7M
}
963
964
46.1k
Status Segment::traverse_column_meta_pbs(const std::function<void(const ColumnMetaPB&)>& visitor) {
965
    // Ensure column meta accessor and reader cache are initialized once.
966
46.1k
    OlapReaderStatistics dummy_stats;
967
46.1k
    RETURN_IF_ERROR(_create_column_meta_once(&dummy_stats));
968
46.1k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared;
969
46.1k
    RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, &dummy_stats));
970
46.1k
    return _column_meta_accessor->traverse_metas(*footer_pb_shared, visitor);
971
46.1k
}
972
973
Status Segment::get_column_reader(const TabletColumn& col,
974
                                  std::shared_ptr<ColumnReader>* column_reader,
975
1.93M
                                  OlapReaderStatistics* stats, std::optional<Field> const_value) {
976
1.93M
    RETURN_IF_ERROR(_create_column_meta_once(stats));
977
1.93M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
978
18.4E
    int col_uid = col.unique_id() >= 0 ? col.unique_id() : col.parent_unique_id();
979
    // The column is not in this segment, return nullptr
980
1.93M
    if (!_tablet_schema->has_column_unique_id(col_uid)) {
981
85
        *column_reader = nullptr;
982
85
        return Status::Error<ErrorCode::NOT_FOUND, false>("column not found in segment, col_uid={}",
983
85
                                                          col_uid);
984
85
    }
985
1.93M
    if (col.has_path_info()) {
986
1.89k
        PathInData relative_path = col.path_info_ptr()->copy_pop_front();
987
1.89k
        return _column_reader_cache->get_path_column_reader(col_uid, relative_path, column_reader,
988
1.89k
                                                            stats);
989
1.89k
    }
990
1.93M
    return _column_reader_cache->get_column_reader(col_uid, column_reader, stats,
991
1.93M
                                                   std::move(const_value));
992
1.93M
}
993
994
Status Segment::new_index_iterator(const TabletColumn& tablet_column, const TabletIndex* index_meta,
995
                                   const StorageReadOptions& read_options,
996
76.1k
                                   std::unique_ptr<IndexIterator>* iter) {
997
76.1k
    if (read_options.runtime_state != nullptr) {
998
67.1k
        _be_exec_version = read_options.runtime_state->be_exec_version();
999
67.1k
    }
1000
76.1k
    RETURN_IF_ERROR(_create_column_meta_once(read_options.stats));
1001
76.1k
    std::shared_ptr<ColumnReader> reader;
1002
76.1k
    auto st = get_column_reader(tablet_column, &reader, read_options.stats);
1003
76.1k
    if (st.is<ErrorCode::NOT_FOUND>()) {
1004
451
        return Status::OK();
1005
451
    }
1006
75.6k
    RETURN_IF_ERROR(st);
1007
75.6k
    DCHECK(reader != nullptr);
1008
75.8k
    if (index_meta) {
1009
        // call DorisCallOnce.call without check if _index_file_reader is nullptr
1010
        // to avoid data race during parallel method calls
1011
75.8k
        RETURN_IF_ERROR(_index_file_reader_open.call([&] { return _open_index_file_reader(); }));
1012
        // after DorisCallOnce.call, _index_file_reader is guaranteed to be not nullptr
1013
75.8k
        const std::string rowset_id =
1014
75.8k
                index_meta->index_type() == IndexType::ANN ? _rowset_id.to_string() : "";
1015
75.8k
        const bool need_binding_diagnostic = tablet_column.is_variant_type() ||
1016
75.8k
                                             tablet_column.is_extracted_column() ||
1017
75.8k
                                             !index_meta->get_index_suffix().empty();
1018
75.8k
        bool index_file_exists = false;
1019
75.8k
        Status probe_status;
1020
75.8k
        if (need_binding_diagnostic) {
1021
1.15k
            probe_status = _index_file_reader->init(config::inverted_index_read_buffer_size,
1022
1.15k
                                                    &read_options.io_ctx);
1023
1.15k
            if (probe_status.ok()) {
1024
1.15k
                probe_status = _index_file_reader->index_file_exist(index_meta, &index_file_exists);
1025
1.15k
            }
1026
1.15k
            const auto diagnostic = fmt::format(
1027
1.15k
                    "[VariantSearchBinding] phase=index_file_probe tablet_id={} rowset_id={} "
1028
1.15k
                    "segment_id={} column={} logical_path={} index_id={} suffix={} exists={} "
1029
1.15k
                    "status={}",
1030
1.15k
                    read_options.tablet_id, _rowset_id.to_string(), _segment_id,
1031
1.15k
                    tablet_column.name(),
1032
1.15k
                    tablet_column.has_path_info() ? tablet_column.path_info_ptr()->get_path()
1033
1.15k
                                                  : tablet_column.name(),
1034
1.15k
                    index_meta->index_id(), index_meta->get_index_suffix(), index_file_exists,
1035
1.15k
                    probe_status.ok() ? "OK" : probe_status.to_string());
1036
18.4E
            VLOG_DEBUG << diagnostic;
1037
1.15k
            if (read_options.stats != nullptr) {
1038
1.15k
                read_options.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
1039
1.15k
            }
1040
1.15k
        }
1041
75.8k
        Status iter_status = reader->new_index_iterator(_index_file_reader, index_meta, rowset_id,
1042
75.8k
                                                        _segment_id, _num_rows, iter);
1043
75.8k
        if (!iter_status.ok()) {
1044
0
            if (need_binding_diagnostic) {
1045
0
                const auto diagnostic = fmt::format(
1046
0
                        "[VariantSearchBinding] phase=index_iterator_create result=reject "
1047
0
                        "tablet_id={} rowset_id={} segment_id={} column={} logical_path={} "
1048
0
                        "index_id={} suffix={} reason={}",
1049
0
                        read_options.tablet_id, _rowset_id.to_string(), _segment_id,
1050
0
                        tablet_column.name(),
1051
0
                        tablet_column.has_path_info() ? tablet_column.path_info_ptr()->get_path()
1052
0
                                                      : tablet_column.name(),
1053
0
                        index_meta->index_id(), index_meta->get_index_suffix(),
1054
0
                        iter_status.to_string());
1055
0
                VLOG_DEBUG << diagnostic;
1056
0
                if (read_options.stats != nullptr) {
1057
0
                    read_options.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
1058
0
                }
1059
0
            }
1060
0
            return iter_status;
1061
0
        }
1062
75.8k
        return Status::OK();
1063
75.8k
    }
1064
18.4E
    return Status::OK();
1065
75.6k
}
1066
1067
Status Segment::lookup_row_key(const Slice& key, const TabletSchema* latest_schema,
1068
                               bool with_seq_col, bool with_rowid, RowLocation* row_location,
1069
3.74M
                               OlapReaderStatistics* stats, std::string* encoded_seq_value) {
1070
3.74M
    RETURN_IF_ERROR(load_pk_index_and_bf(stats));
1071
3.74M
    bool has_seq_col = latest_schema->has_sequence_col();
1072
3.74M
    bool has_rowid = !latest_schema->cluster_key_uids().empty();
1073
3.74M
    size_t seq_col_length = 0;
1074
3.74M
    if (has_seq_col) {
1075
25.1k
        seq_col_length = latest_schema->column(latest_schema->sequence_col_idx()).length() + 1;
1076
25.1k
    }
1077
3.74M
    size_t rowid_length = has_rowid ? PrimaryKeyIndexReader::ROW_ID_LENGTH : 0;
1078
1079
3.74M
    Slice key_without_seq =
1080
3.74M
            Slice(key.get_data(), key.get_size() - (with_seq_col ? seq_col_length : 0) -
1081
3.74M
                                          (with_rowid ? rowid_length : 0));
1082
1083
3.74M
    DCHECK(_pk_index_reader != nullptr);
1084
3.74M
    if (!_pk_index_reader->check_present(key_without_seq)) {
1085
61.1k
        return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1086
61.1k
    }
1087
3.67M
    bool exact_match = false;
1088
3.67M
    std::unique_ptr<segment_v2::IndexedColumnIterator> index_iterator;
1089
3.67M
    RETURN_IF_ERROR(_pk_index_reader->new_iterator(&index_iterator, stats));
1090
3.67M
    auto st = index_iterator->seek_at_or_after(&key_without_seq, &exact_match);
1091
3.67M
    if (!st.ok() && !st.is<ErrorCode::ENTRY_NOT_FOUND>()) {
1092
0
        return st;
1093
0
    }
1094
3.70M
    if (st.is<ErrorCode::ENTRY_NOT_FOUND>() || (!has_seq_col && !has_rowid && !exact_match)) {
1095
42
        return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1096
42
    }
1097
3.67M
    row_location->row_id = cast_set<uint32_t>(index_iterator->get_current_ordinal());
1098
3.67M
    row_location->segment_id = _segment_id;
1099
3.67M
    row_location->rowset_id = _rowset_id;
1100
1101
3.67M
    size_t num_to_read = 1;
1102
3.67M
    auto index_type = DataTypeFactory::instance().create_data_type(_pk_index_reader->type(), 1, 0);
1103
3.67M
    auto index_column = index_type->create_column();
1104
3.67M
    size_t num_read = num_to_read;
1105
3.67M
    RETURN_IF_ERROR(index_iterator->next_batch(&num_read, index_column));
1106
3.67M
    DCHECK(num_to_read == num_read);
1107
1108
3.67M
    Slice sought_key = Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
1109
1110
    // user may use "ALTER TABLE tbl ENABLE FEATURE "SEQUENCE_LOAD" WITH ..." to add a hidden sequence column
1111
    // for a merge-on-write table which doesn't have sequence column, so `has_seq_col ==  true` doesn't mean
1112
    // data in segment has sequence column value
1113
3.67M
    bool segment_has_seq_col = _tablet_schema->has_sequence_col();
1114
3.67M
    Slice sought_key_without_seq = Slice(
1115
3.67M
            sought_key.get_data(),
1116
3.67M
            sought_key.get_size() - (segment_has_seq_col ? seq_col_length : 0) - rowid_length);
1117
1118
3.67M
    if (has_seq_col) {
1119
        // compare key
1120
25.2k
        if (key_without_seq.compare(sought_key_without_seq) != 0) {
1121
0
            return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1122
0
        }
1123
1124
25.2k
        if (with_seq_col && segment_has_seq_col) {
1125
            // compare sequence id
1126
23.3k
            Slice sequence_id =
1127
23.3k
                    Slice(key.get_data() + key_without_seq.get_size() + 1, seq_col_length - 1);
1128
23.3k
            Slice previous_sequence_id =
1129
23.3k
                    Slice(sought_key.get_data() + sought_key_without_seq.get_size() + 1,
1130
23.3k
                          seq_col_length - 1);
1131
23.3k
            if (sequence_id.compare(previous_sequence_id) < 0) {
1132
343
                return Status::Error<ErrorCode::KEY_ALREADY_EXISTS>(
1133
343
                        "key with higher sequence id exists");
1134
343
            }
1135
23.3k
        }
1136
3.65M
    } else if (has_rowid) {
1137
51.6k
        Slice sought_key_without_rowid =
1138
51.6k
                Slice(sought_key.get_data(), sought_key.get_size() - rowid_length);
1139
        // compare key
1140
51.6k
        if (key_without_seq.compare(sought_key_without_rowid) != 0) {
1141
0
            return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1142
0
        }
1143
51.6k
    }
1144
    // found the key, use rowid in pk index if necessary.
1145
3.67M
    if (has_rowid) {
1146
63.5k
        Slice rowid_slice = Slice(sought_key.get_data() + sought_key_without_seq.get_size() +
1147
63.5k
                                          (segment_has_seq_col ? seq_col_length : 0) + 1,
1148
63.5k
                                  rowid_length - 1);
1149
63.5k
        const auto* rowid_coder = get_key_coder(FieldType::OLAP_FIELD_TYPE_UNSIGNED_INT);
1150
63.5k
        RETURN_IF_ERROR(rowid_coder->decode_ascending(&rowid_slice, rowid_length,
1151
63.5k
                                                      (uint8_t*)&row_location->row_id));
1152
63.5k
    }
1153
1154
3.67M
    if (encoded_seq_value) {
1155
78
        if (!segment_has_seq_col) {
1156
0
            *encoded_seq_value = std::string {};
1157
78
        } else {
1158
            // include marker
1159
78
            *encoded_seq_value =
1160
78
                    Slice(sought_key.get_data() + sought_key_without_seq.get_size(), seq_col_length)
1161
78
                            .to_string();
1162
78
        }
1163
78
    }
1164
3.67M
    return Status::OK();
1165
3.67M
}
1166
1167
0
Status Segment::read_key_by_rowid(uint32_t row_id, std::string* key) {
1168
0
    OlapReaderStatistics* null_stat = nullptr;
1169
0
    RETURN_IF_ERROR(load_pk_index_and_bf(null_stat));
1170
0
    std::unique_ptr<segment_v2::IndexedColumnIterator> iter;
1171
0
    RETURN_IF_ERROR(_pk_index_reader->new_iterator(&iter, null_stat));
1172
1173
0
    auto index_type = DataTypeFactory::instance().create_data_type(_pk_index_reader->type(), 1, 0);
1174
0
    auto index_column = index_type->create_column();
1175
0
    RETURN_IF_ERROR(iter->seek_to_ordinal(row_id));
1176
0
    size_t num_read = 1;
1177
0
    RETURN_IF_ERROR(iter->next_batch(&num_read, index_column));
1178
0
    CHECK(num_read == 1);
1179
    // trim row id
1180
0
    if (_tablet_schema->cluster_key_uids().empty()) {
1181
0
        *key = index_column->get_data_at(0).to_string();
1182
0
    } else {
1183
0
        Slice sought_key =
1184
0
                Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
1185
0
        Slice sought_key_without_rowid =
1186
0
                Slice(sought_key.get_data(),
1187
0
                      sought_key.get_size() - PrimaryKeyIndexReader::ROW_ID_LENGTH);
1188
0
        *key = sought_key_without_rowid.to_string();
1189
0
    }
1190
0
    return Status::OK();
1191
0
}
1192
1193
Status Segment::seek_and_read_by_rowid(const TabletSchema& schema, SlotDescriptor* slot,
1194
                                       const std::vector<uint32_t>& row_ids,
1195
                                       MutableColumnPtr& result,
1196
                                       StorageReadOptions& storage_read_options,
1197
12.9k
                                       std::unique_ptr<ColumnIterator>& iterator_hint) {
1198
12.9k
    if (row_ids.empty()) {
1199
0
        return Status::OK();
1200
0
    }
1201
12.9k
    DORIS_CHECK(std::is_sorted(row_ids.begin(), row_ids.end()));
1202
12.9k
    DORIS_CHECK(std::adjacent_find(row_ids.begin(), row_ids.end()) == row_ids.end());
1203
    // ColumnIterator::seek_and_read expects monotonically increasing row_ids without
1204
    // duplicates for correct ordinal scanning. Enforce this contract at the entry point.
1205
12.9k
    auto io_ctx = storage_read_options.io_ctx;
1206
12.9k
    io_ctx.reader_type = ReaderType::READER_QUERY;
1207
12.9k
    io_ctx.file_cache_stats = &storage_read_options.stats->file_cache_stats;
1208
12.9k
    segment_v2::ColumnIteratorOptions opt {
1209
12.9k
            .use_page_cache = !config::disable_storage_page_cache,
1210
12.9k
            .file_reader = file_reader().get(),
1211
12.9k
            .stats = storage_read_options.stats,
1212
12.9k
            .io_ctx = io_ctx,
1213
12.9k
    };
1214
1215
12.9k
    if (!slot->column_paths().empty()) {
1216
        // here need create column readers to make sure column reader is created before seek_and_read_by_rowid
1217
        // if segment cache miss, column reader will be created to make sure the variant column result not coredump
1218
297
        RETURN_IF_ERROR(_create_column_meta_once(storage_read_options.stats));
1219
1220
297
        const auto& dt_variant =
1221
297
                assert_cast<const DataTypeVariant&>(*remove_nullable(slot->type()));
1222
297
        TabletColumn column = TabletColumn::create_materialized_variant_column(
1223
297
                schema.column_by_uid(slot->col_unique_id()).name_lower_case(), slot->column_paths(),
1224
297
                slot->col_unique_id(), dt_variant.variant_max_subcolumns_count(),
1225
297
                dt_variant.enable_doc_mode());
1226
297
        auto storage_type = get_data_type_of(column, storage_read_options);
1227
297
        MutableColumnPtr file_storage_column = storage_type->create_column();
1228
297
        DCHECK(storage_type != nullptr);
1229
1230
297
        if (iterator_hint == nullptr) {
1231
297
            RETURN_IF_ERROR(new_column_iterator(column, &iterator_hint, &storage_read_options));
1232
297
            RETURN_IF_ERROR(iterator_hint->init(opt));
1233
297
        }
1234
297
        RETURN_IF_ERROR(
1235
297
                iterator_hint->read_by_rowids(row_ids.data(), row_ids.size(), file_storage_column));
1236
297
        ColumnPtr source_ptr;
1237
        // storage may have different type with schema, so we need to cast the column
1238
297
        RETURN_IF_ERROR(variant_util::cast_column(
1239
297
                ColumnWithTypeAndName(file_storage_column->get_ptr(), storage_type, column.name()),
1240
297
                slot->type(), &source_ptr));
1241
297
        RETURN_IF_CATCH_EXCEPTION(result->insert_range_from(*source_ptr, 0, row_ids.size()));
1242
12.6k
    } else {
1243
12.6k
        int index = (slot->col_unique_id() >= 0) ? schema.field_index(slot->col_unique_id())
1244
12.6k
                                                 : schema.field_index(slot->col_name());
1245
12.6k
        if (index < 0) {
1246
0
            std::stringstream ss;
1247
0
            ss << "field name is invalid. field=" << slot->col_name()
1248
0
               << ", field_name_to_index=" << schema.get_all_field_names();
1249
0
            return Status::InternalError(ss.str());
1250
0
        }
1251
12.6k
        if (iterator_hint == nullptr) {
1252
12.6k
            RETURN_IF_ERROR(new_column_iterator(schema.column(index), &iterator_hint,
1253
12.6k
                                                &storage_read_options));
1254
12.6k
            RETURN_IF_ERROR(iterator_hint->init(opt));
1255
12.6k
        }
1256
12.6k
        RETURN_IF_ERROR(iterator_hint->read_by_rowids(row_ids.data(), row_ids.size(), result));
1257
12.6k
    }
1258
12.9k
    return Status::OK();
1259
12.9k
}
1260
1261
Status Segment::_get_segment_footer(std::shared_ptr<SegmentFooterPB>& footer_pb,
1262
13.6M
                                    OlapReaderStatistics* stats) {
1263
13.6M
    std::shared_ptr<SegmentFooterPB> footer_pb_shared = _footer_pb.lock();
1264
13.6M
    if (footer_pb_shared != nullptr) {
1265
12.8M
        footer_pb = footer_pb_shared;
1266
12.8M
        return Status::OK();
1267
12.8M
    }
1268
1269
18.4E
    VLOG_DEBUG << fmt::format("Segment footer of {}:{}:{} is missing, try to load it",
1270
18.4E
                              _file_reader->path().native(), _file_reader->size(),
1271
18.4E
                              _file_reader->size() - 12);
1272
1273
826k
    StoragePageCache* segment_footer_cache = ExecEnv::GetInstance()->get_storage_page_cache();
1274
826k
    DCHECK(segment_footer_cache != nullptr);
1275
1276
826k
    auto cache_key = get_segment_footer_cache_key();
1277
1278
826k
    PageCacheHandle cache_handle;
1279
1280
    // Put segment footer into index page cache.
1281
    // Rationale:
1282
    // - Footer is metadata (small, parsed with indexes), not data page payload.
1283
    // - Using PageTypePB::INDEX_PAGE keeps it under the same eviction policy/shards
1284
    //   as other index/metadata pages and avoids competing with DATA_PAGE budget.
1285
826k
    if (!segment_footer_cache->lookup(cache_key, &cache_handle,
1286
826k
                                      segment_v2::PageTypePB::INDEX_PAGE)) {
1287
95.6k
        RETURN_IF_ERROR(_parse_footer(footer_pb_shared, stats));
1288
95.6k
        segment_footer_cache->insert(cache_key, footer_pb_shared, footer_pb_shared->ByteSizeLong(),
1289
95.6k
                                     &cache_handle, segment_v2::PageTypePB::INDEX_PAGE);
1290
730k
    } else {
1291
18.4E
        VLOG_DEBUG << fmt::format("Segment footer of {}:{}:{} is found in cache",
1292
18.4E
                                  _file_reader->path().native(), _file_reader->size(),
1293
18.4E
                                  _file_reader->size() - 12);
1294
730k
    }
1295
826k
    footer_pb_shared = cache_handle.get<std::shared_ptr<SegmentFooterPB>>();
1296
826k
    _footer_pb = footer_pb_shared;
1297
826k
    footer_pb = footer_pb_shared;
1298
826k
    return Status::OK();
1299
826k
}
1300
1301
880k
StoragePageCache::CacheKey Segment::get_segment_footer_cache_key() const {
1302
880k
    DCHECK(_file_reader != nullptr);
1303
    // The footer is always at the end of the segment file.
1304
    // The size of footer is 12.
1305
    // So we use the size of file minus 12 as the cache key, which is unique for each segment file.
1306
880k
    return get_segment_footer_cache_key(_file_reader);
1307
880k
}
1308
1309
StoragePageCache::CacheKey Segment::get_segment_footer_cache_key(
1310
879k
        const io::FileReaderSPtr& file_reader) {
1311
879k
    return {file_reader->path().native(), file_reader->size(),
1312
879k
            static_cast<int64_t>(file_reader->size() - 12)};
1313
879k
}
1314
1315
} // namespace doris::segment_v2