Coverage Report

Created: 2026-07-13 17:12

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