Coverage Report

Created: 2026-07-14 18:57

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
22
                                     const VExprContextSPtrs& conjuncts, ZoneMapEvalContext* ctx) {
97
22
    DORIS_CHECK(segment != nullptr);
98
22
    DORIS_CHECK(ctx != nullptr);
99
22
    std::set<int> slot_indexes;
100
22
    for (const auto& conjunct : conjuncts) {
101
22
        DORIS_CHECK(conjunct != nullptr);
102
22
        const auto& root = conjunct->root();
103
22
        DORIS_CHECK(root != nullptr);
104
22
        if (!root->can_evaluate_zonemap_filter()) {
105
10
            continue;
106
10
        }
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
12
        root->collect_slot_column_ids(slot_indexes);
112
12
    }
113
22
    for (const int slot_index : slot_indexes) {
114
12
        if (slot_index < 0 || cast_set<size_t>(slot_index) >= schema.num_column_ids()) {
115
0
            continue;
116
0
        }
117
12
        const auto column_id = schema.column_id(cast_set<size_t>(slot_index));
118
12
        const auto* tablet_column = schema.column(column_id);
119
12
        DORIS_CHECK(tablet_column != nullptr);
120
12
        if (!segment->can_apply_predicate_safely(
121
12
                    column_id, schema, read_options.target_cast_type_for_variants, read_options)) {
122
0
            continue;
123
0
        }
124
12
        auto data_type = segment->get_data_type_of(*tablet_column, read_options);
125
12
        if (data_type == nullptr) {
126
0
            continue;
127
0
        }
128
12
        ZoneMapEvalContext::SlotZoneMap slot_zone_map;
129
12
        slot_zone_map.data_type = data_type;
130
12
        std::shared_ptr<ColumnReader> reader;
131
12
        Status st = segment->get_column_reader(*tablet_column, &reader, read_options.stats);
132
12
        if (st.is<ErrorCode::NOT_FOUND>()) {
133
4
            ctx->slots.emplace(slot_index, std::move(slot_zone_map));
134
4
            continue;
135
4
        }
136
8
        RETURN_IF_ERROR(st);
137
8
        if (reader != nullptr && reader->has_zone_map()) {
138
8
            ZoneMap zone_map;
139
8
            RETURN_IF_ERROR(reader->get_segment_zone_map(&zone_map));
140
8
            slot_zone_map.zone_map = std::make_shared<ZoneMap>(std::move(zone_map));
141
8
        }
142
8
        ctx->slots.emplace(slot_index, std::move(slot_zone_map));
143
8
    }
144
22
    return Status::OK();
145
22
}
146
147
6.41k
void fill_missing_decimal_precision(const TabletColumn& column, ColumnMetaPB* meta) {
148
6.41k
    auto meta_type = static_cast<FieldType>(meta->type());
149
6.41k
    if (meta_type != column.type()) {
150
0
        return;
151
0
    }
152
153
6.41k
    if (field_is_decimal_type(meta_type)) {
154
4
        if ((!meta->has_precision() || meta->precision() <= 0) && column.precision() > 0) {
155
4
            meta->set_precision(column.precision());
156
4
        }
157
4
        if ((!meta->has_frac() || meta->frac() < 0) && column.frac() >= 0) {
158
4
            meta->set_frac(column.frac());
159
4
        }
160
4
    }
161
162
    // Complex column meta may also include storage helper children, such as
163
    // array offsets. Only schema children have matching TabletColumn subtypes.
164
6.41k
    int child_count =
165
6.41k
            std::min(meta->children_columns_size(), static_cast<int>(column.get_subtype_count()));
166
6.42k
    for (int i = 0; i < child_count; ++i) {
167
16
        fill_missing_decimal_precision(column.get_sub_column(i), meta->mutable_children_columns(i));
168
16
    }
169
6.41k
}
170
171
void fill_missing_decimal_precision_from_schema(const TabletSchemaSPtr& tablet_schema,
172
6.90k
                                                ColumnMetaPB* meta) {
173
6.90k
    if (!meta->has_unique_id()) {
174
0
        return;
175
0
    }
176
6.90k
    int32_t col_idx = tablet_schema->field_index(static_cast<int32_t>(meta->unique_id()));
177
6.90k
    if (col_idx < 0) {
178
508
        return;
179
508
    }
180
6.39k
    fill_missing_decimal_precision(tablet_schema->column(col_idx), meta);
181
6.39k
}
182
183
void fill_footer_missing_decimal_precision(const TabletSchemaSPtr& tablet_schema,
184
2.20k
                                           SegmentFooterPB* footer) {
185
9.11k
    for (int i = 0; i < footer->columns_size(); ++i) {
186
6.90k
        fill_missing_decimal_precision_from_schema(tablet_schema, footer->mutable_columns(i));
187
6.90k
    }
188
2.20k
}
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
3.83k
                     InvertedIndexFileInfo idx_file_info, OlapReaderStatistics* stats) {
196
    // Ensure tablet_id is available in reader_options for CachedRemoteFileReader peer read.
197
3.83k
    io::FileReaderOptions opts_with_tablet = reader_options;
198
3.83k
    opts_with_tablet.tablet_id = tablet_id;
199
200
3.83k
    auto s = _open(fs, path, segment_id, rowset_id, tablet_schema, opts_with_tablet, output,
201
3.83k
                   idx_file_info, stats);
202
3.83k
    if (s.ok() && output && *output) {
203
3.82k
        (*output)->_tablet_id = tablet_id;
204
3.82k
    }
205
3.83k
    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
3.83k
    return s;
217
3.83k
}
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
3.83k
                      InvertedIndexFileInfo idx_file_info, OlapReaderStatistics* stats) {
223
3.83k
    io::FileReaderSPtr file_reader;
224
3.83k
    auto st = fs->open_file(path, &file_reader, &reader_options);
225
3.83k
    TEST_INJECTION_POINT_CALLBACK("Segment::open:corruption", &st);
226
3.83k
    std::shared_ptr<Segment> segment(
227
3.83k
            new Segment(segment_id, rowset_id, std::move(tablet_schema), idx_file_info));
228
3.83k
    segment->_seg_path = path;
229
3.83k
    if (st) {
230
3.82k
        segment->_fs = fs;
231
3.82k
        segment->_file_reader = std::move(file_reader);
232
3.82k
        st = segment->_open(stats);
233
3.82k
    }
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
3.83k
    if (st.is<ErrorCode::CORRUPTION>() &&
238
3.83k
        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
3.83k
    RETURN_IF_ERROR(st);
277
3.83k
    DCHECK(segment->_fs != nullptr) << "file system is nullptr after segment open";
278
3.82k
    *output = std::move(segment);
279
3.82k
    return Status::OK();
280
3.83k
}
281
282
Segment::Segment(uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
283
                 InvertedIndexFileInfo idx_file_info)
284
3.85k
        : _segment_id(segment_id),
285
3.85k
          _meta_mem_usage(0),
286
3.85k
          _rowset_id(rowset_id),
287
3.85k
          _tablet_schema(std::move(tablet_schema)),
288
3.85k
          _idx_file_info(std::move(idx_file_info)) {}
289
290
3.85k
Segment::~Segment() {
291
3.85k
    g_segment_estimate_mem_bytes << -_tracked_meta_mem_usage;
292
    // if failed, fix `_tracked_meta_mem_usage` accuracy
293
3.85k
    DCHECK(_tracked_meta_mem_usage == meta_mem_usage());
294
3.85k
}
295
296
0
io::UInt128Wrapper Segment::file_cache_key(std::string_view rowset_id, uint32_t seg_id) {
297
0
    return io::BlockFileCache::hash(fmt::format("{}_{}.dat", rowset_id, seg_id));
298
0
}
299
300
3.82k
int64_t Segment::get_metadata_size() const {
301
3.82k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared = _footer_pb.lock();
302
3.82k
    return sizeof(Segment) + (_pk_index_meta ? _pk_index_meta->ByteSizeLong() : 0) +
303
3.82k
           (footer_pb_shared ? footer_pb_shared->ByteSizeLong() : 0);
304
3.82k
}
305
306
3.82k
void Segment::update_metadata_size() {
307
3.82k
    MetadataAdder::update_metadata_size();
308
3.82k
    g_segment_estimate_mem_bytes << _meta_mem_usage - _tracked_meta_mem_usage;
309
3.82k
    _tracked_meta_mem_usage = _meta_mem_usage;
310
3.82k
}
311
312
3.82k
Status Segment::_open(OlapReaderStatistics* stats) {
313
3.82k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared;
314
3.82k
    RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, stats));
315
316
3.82k
    _pk_index_meta.reset(
317
3.82k
            footer_pb_shared->has_primary_key_index_meta()
318
3.82k
                    ? new PrimaryKeyIndexMetaPB(footer_pb_shared->primary_key_index_meta())
319
3.82k
                    : nullptr);
320
    // delete_bitmap_calculator_test.cpp
321
    // DCHECK(footer.has_short_key_index_page());
322
3.82k
    _sk_index_page = footer_pb_shared->short_key_index_page();
323
3.82k
    _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
3.82k
    if (_pk_index_meta != nullptr) {
329
74
        _meta_mem_usage += _pk_index_meta->ByteSizeLong();
330
74
    }
331
332
3.82k
    _meta_mem_usage += sizeof(*this);
333
3.82k
    _meta_mem_usage += std::min(static_cast<int>(_tablet_schema->num_columns()),
334
3.82k
                                config::max_segment_partial_column_cache_size) *
335
3.82k
                       config::estimated_mem_per_column_reader;
336
337
    // 1024 comes from SegmentWriterOptions
338
3.82k
    _meta_mem_usage += (_num_rows + 1023) / 1024 * (36 + 4);
339
    // 0.01 comes from PrimaryKeyIndexBuilder::init
340
3.82k
    _meta_mem_usage += BloomFilter::optimal_bit_num(_num_rows, 0.01) / 8;
341
342
3.82k
    update_metadata_size();
343
344
3.82k
    return Status::OK();
345
3.82k
}
346
347
743
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
743
    _index_file_reader = std::make_shared<IndexFileReader>(
351
743
            _fs, std::string {InvertedIndexDescriptor::get_index_file_path_prefix(_seg_path)},
352
743
            _tablet_schema->get_inverted_index_storage_format(), _idx_file_info, _tablet_id);
353
743
    return Status::OK();
354
743
}
355
356
bool Segment::is_tso_placeholder_col(int cid, const Schema& schema,
357
136
                                     const StorageReadOptions& read_options) const {
358
136
    if (read_options.version.first != read_options.version.second) {
359
20
        return false;
360
20
    }
361
116
    if (read_options.io_ctx.reader_type != ReaderType::READER_BINLOG &&
362
116
        read_options.io_ctx.reader_type != ReaderType::READER_BINLOG_COMPACTION) {
363
116
        return false;
364
116
    }
365
    // tso_col_idx() is -1 for non-binlog schemas, so this returns false there.
366
0
    return cid == schema.tso_col_idx();
367
116
}
368
369
Status Segment::new_iterator(SchemaSPtr schema, const StorageReadOptions& read_options,
370
3.04k
                             std::unique_ptr<RowwiseIterator>* iter) {
371
3.04k
    if (read_options.runtime_state != nullptr) {
372
117
        _be_exec_version = read_options.runtime_state->be_exec_version();
373
117
    }
374
3.04k
    RETURN_IF_ERROR(_create_column_meta_once(read_options.stats));
375
376
3.04k
    read_options.stats->total_segment_number++;
377
    // trying to prune the current segment by segment-level zone map
378
3.04k
    for (const auto& entry : read_options.col_id_to_predicates) {
379
72
        int32_t column_id = entry.first;
380
        // schema change
381
72
        if (_tablet_schema->num_columns() <= column_id) {
382
0
            continue;
383
0
        }
384
72
        const TabletColumn& col = read_options.tablet_schema->column(column_id);
385
72
        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
72
        std::optional<Field> const_value;
391
72
        if (read_options.version.first == read_options.version.second &&
392
72
            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
72
        Status st = get_column_reader(col, &reader, read_options.stats, std::move(const_value));
396
        // not found in this segment, skip
397
72
        if (st.is<ErrorCode::NOT_FOUND>()) {
398
0
            continue;
399
0
        }
400
72
        RETURN_IF_ERROR(st);
401
        // should be OK
402
72
        DCHECK(reader != nullptr);
403
72
        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
72
        if (read_options.col_id_to_predicates.contains(column_id) &&
413
72
            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
72
        if (read_options.col_id_to_predicates.contains(column_id) &&
429
72
            can_apply_predicate_safely(column_id, *schema,
430
72
                                       read_options.target_cast_type_for_variants, read_options)) {
431
72
            bool matched = true;
432
72
            RETURN_IF_ERROR(reader->match_condition(entry.second.get(), &matched));
433
72
            if (!matched) {
434
                // any condition not satisfied, return.
435
8
                *iter = std::make_unique<EmptySegmentIterator>(*schema);
436
8
                read_options.stats->filtered_segment_number++;
437
8
                read_options.stats->rows_stats_filtered += num_rows();
438
8
                return Status::OK();
439
8
            }
440
72
        }
441
72
    }
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
3.03k
    if (expr_zonemap::is_expr_zonemap_filter_enabled(read_options.runtime_state) &&
446
3.03k
        !read_options.common_expr_ctxs_push_down.empty()) {
447
22
        ZoneMapEvalContext ctx;
448
22
        RETURN_IF_ERROR(build_segment_zonemap_context(
449
22
                this, *schema, read_options, read_options.common_expr_ctxs_push_down, &ctx));
450
22
        const auto result =
451
22
                VExprContext::evaluate_zonemap_filter(read_options.common_expr_ctxs_push_down, ctx);
452
22
        ctx.stats.accumulate_to(read_options.stats);
453
22
        if (result == ZoneMapFilterResult::kNoMatch) {
454
1
            *iter = std::make_unique<EmptySegmentIterator>(*schema);
455
1
            read_options.stats->filtered_segment_number++;
456
1
            read_options.stats->expr_zonemap_filtered_segments++;
457
1
            return Status::OK();
458
1
        }
459
22
    }
460
461
3.03k
    {
462
3.03k
        SCOPED_RAW_TIMER(&read_options.stats->segment_load_index_timer_ns);
463
3.03k
        RETURN_IF_ERROR(load_index(read_options.stats));
464
3.03k
    }
465
466
3.03k
    if (read_options.delete_condition_predicates->num_of_column_predicate() == 0 &&
467
3.03k
        read_options.push_down_agg_type_opt != TPushAggOp::NONE &&
468
3.03k
        read_options.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
469
0
        iter->reset(new_vstatistics_iterator(this->shared_from_this(), *schema));
470
3.03k
    } else {
471
3.03k
        *iter = std::make_unique<SegmentIterator>(this->shared_from_this(), schema);
472
3.03k
    }
473
474
    // TODO: Valid the opt not only in ReaderType::READER_QUERY
475
3.03k
    if (read_options.io_ctx.reader_type == ReaderType::READER_QUERY &&
476
3.03k
        !read_options.column_predicates.empty()) {
477
64
        auto pruned_predicates = read_options.column_predicates;
478
64
        auto pruned = false;
479
64
        for (auto& it : _column_reader_cache->get_available_readers(false)) {
480
64
            const auto uid = it.first;
481
64
            const auto column_id = read_options.tablet_schema->field_index(uid);
482
64
            bool tmp_pruned = false;
483
64
            RETURN_IF_ERROR(it.second->prune_predicates_by_zone_map(pruned_predicates, column_id,
484
64
                                                                    &tmp_pruned));
485
64
            pruned |= tmp_pruned;
486
64
        }
487
488
64
        if (pruned) {
489
0
            auto options_with_pruned_predicates = read_options;
490
0
            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
0
            options_with_pruned_predicates.col_id_to_predicates.clear();
493
0
            for (auto pred : options_with_pruned_predicates.column_predicates) {
494
0
                if (!options_with_pruned_predicates.col_id_to_predicates.contains(
495
0
                            pred->column_id())) {
496
0
                    options_with_pruned_predicates.col_id_to_predicates.insert(
497
0
                            {pred->column_id(), AndBlockColumnPredicate::create_shared()});
498
0
                }
499
0
                options_with_pruned_predicates.col_id_to_predicates[pred->column_id()]
500
0
                        ->add_column_predicate(SingleColumnBlockPredicate::create_unique(pred));
501
0
            }
502
0
            for (const auto& pred : read_options.column_predicates) {
503
0
                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
0
                if (!read_options.tablet_schema->column(pred_cid).is_key() &&
508
0
                    !options_with_pruned_predicates.col_id_to_predicates.contains(pred_cid)) {
509
0
                    options_with_pruned_predicates.zonemap_always_true_pred_cols.insert(pred_cid);
510
0
                }
511
0
            }
512
0
            return iter->get()->init(options_with_pruned_predicates);
513
0
        }
514
64
    }
515
3.03k
    return iter->get()->init(read_options);
516
3.03k
}
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
2.20k
                              OlapReaderStatistics* stats) {
581
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
582
2.20k
    auto file_size = _file_reader->size();
583
2.20k
    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
2.20k
    uint8_t fixed_buf[12];
590
2.20k
    size_t bytes_read = 0;
591
    // TODO(plat1ko): Support session variable `enable_file_cache`
592
2.20k
    io::IOContext io_ctx {.is_index_data = true,
593
2.20k
                          .file_cache_stats = stats ? &stats->file_cache_stats : nullptr};
594
2.20k
    RETURN_IF_ERROR(
595
2.20k
            _file_reader->read_at(file_size - 12, Slice(fixed_buf, 12), &bytes_read, &io_ctx));
596
2.20k
    DCHECK_EQ(bytes_read, 12);
597
2.20k
    TEST_SYNC_POINT_CALLBACK("Segment::parse_footer:magic_number_corruption", fixed_buf);
598
2.20k
    TEST_INJECTION_POINT_CALLBACK("Segment::parse_footer:magic_number_corruption_inj", fixed_buf);
599
2.20k
    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
2.20k
    uint32_t footer_length = decode_fixed32_le(fixed_buf);
613
2.20k
    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
2.20k
    std::string footer_buf;
625
2.20k
    footer_buf.resize(footer_length);
626
2.20k
    RETURN_IF_ERROR(_file_reader->read_at(file_size - 12 - footer_length, footer_buf, &bytes_read,
627
2.20k
                                          &io_ctx));
628
2.20k
    DCHECK_EQ(bytes_read, footer_length);
629
630
    // validate footer PB's checksum
631
2.20k
    uint32_t expect_checksum = decode_fixed32_le(fixed_buf + 4);
632
2.20k
    uint32_t actual_checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
633
2.20k
    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
2.20k
    footer = std::make_shared<SegmentFooterPB>();
648
2.20k
    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
2.20k
    fill_footer_missing_decimal_precision(_tablet_schema, footer.get());
664
665
2.20k
    VLOG_DEBUG << fmt::format("Loading segment footer from {} finished",
666
0
                              _file_reader->path().native());
667
2.20k
    return Status::OK();
668
2.20k
}
669
670
6
Status Segment::_load_pk_bloom_filter(OlapReaderStatistics* stats) {
671
6
#ifdef BE_TEST
672
6
    if (_pk_index_meta == nullptr) {
673
        // for BE UT "segment_cache_test"
674
2
        return _load_pk_bf_once.call([this] {
675
1
            _meta_mem_usage += 100;
676
1
            update_metadata_size();
677
1
            return Status::OK();
678
1
        });
679
2
    }
680
4
#endif
681
6
    DCHECK(_tablet_schema->keys_type() == UNIQUE_KEYS);
682
4
    DCHECK(_pk_index_meta != nullptr);
683
4
    DCHECK(_pk_index_reader != nullptr);
684
685
4
    return _load_pk_bf_once.call([this, stats] {
686
2
        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
2
        return Status::OK();
689
2
    });
690
6
}
691
692
6
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
6
    RETURN_IF_CATCH_EXCEPTION({
697
6
        RETURN_IF_ERROR(load_index(index_load_stats));
698
6
        RETURN_IF_ERROR(_load_pk_bloom_filter(index_load_stats));
699
6
    });
700
6
    return Status::OK();
701
6
}
702
703
3.08k
Status Segment::load_index(OlapReaderStatistics* stats) {
704
3.08k
    return _load_index_once.call([this, stats] {
705
3.02k
        if (_tablet_schema->keys_type() == UNIQUE_KEYS && _pk_index_meta != nullptr) {
706
57
            _pk_index_reader = std::make_unique<PrimaryKeyIndexReader>();
707
57
            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
57
            return Status::OK();
710
2.97k
        } else {
711
            // read and parse short key index page
712
2.97k
            OlapReaderStatistics tmp_stats;
713
2.97k
            OlapReaderStatistics* stats_ptr = stats != nullptr ? stats : &tmp_stats;
714
2.97k
            PageReadOptions opts(io::IOContext {.is_index_data = true,
715
2.97k
                                                .file_cache_stats = &stats_ptr->file_cache_stats});
716
2.97k
            opts.use_page_cache = true;
717
2.97k
            opts.type = INDEX_PAGE;
718
2.97k
            opts.file_reader = _file_reader.get();
719
2.97k
            opts.page_pointer = PagePointer(_sk_index_page);
720
            // short key index page uses NO_COMPRESSION for now
721
2.97k
            opts.codec = nullptr;
722
2.97k
            opts.stats = &tmp_stats;
723
724
2.97k
            Slice body;
725
2.97k
            PageFooterPB footer;
726
2.97k
            RETURN_IF_ERROR(
727
2.97k
                    PageIO::read_and_decompress_page(opts, &_sk_index_handle, &body, &footer));
728
2.97k
            DCHECK_EQ(footer.type(), SHORT_KEY_PAGE);
729
2.97k
            DCHECK(footer.has_short_key_page_footer());
730
731
            // _meta_mem_usage += body.get_size();
732
2.97k
            _sk_index_decoder = std::make_unique<ShortKeyIndexDecoder>();
733
2.97k
            return _sk_index_decoder->parse(body, footer.short_key_page_footer());
734
2.97k
        }
735
3.02k
    });
736
3.08k
}
737
738
0
Status Segment::healthy_status() {
739
0
    try {
740
0
        if (_load_index_once.has_called()) {
741
0
            RETURN_IF_ERROR(_load_index_once.stored_result());
742
0
        }
743
0
        if (_load_pk_bf_once.has_called()) {
744
0
            RETURN_IF_ERROR(_load_pk_bf_once.stored_result());
745
0
        }
746
0
        if (_create_column_meta_once_call.has_called()) {
747
0
            RETURN_IF_ERROR(_create_column_meta_once_call.stored_result());
748
0
        }
749
0
        if (_index_file_reader_open.has_called()) {
750
0
            RETURN_IF_ERROR(_index_file_reader_open.stored_result());
751
0
        }
752
        // This status is set by running time, for example, if there is something wrong during read segment iterator.
753
0
        return _healthy_status.status();
754
0
    } 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
0
}
763
764
// Return the storage datatype of related column to field.
765
DataTypePtr Segment::get_data_type_of(const TabletColumn& column,
766
9.27k
                                      const StorageReadOptions& read_options) {
767
9.27k
    const PathInDataPtr path = column.path_info_ptr();
768
769
    // none variant column
770
9.27k
    if (path == nullptr || path->empty()) {
771
8.63k
        return DataTypeFactory::instance().create_data_type(column);
772
8.63k
    }
773
774
    // Path exists, proceed with variant logic.
775
641
    PathInData relative_path = path->copy_pop_front();
776
641
    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
641
    if (!_column_meta_accessor->has_column_uid(unique_id)) {
780
0
        return DataTypeFactory::instance().create_data_type(column);
781
0
    }
782
783
641
    std::shared_ptr<ColumnReader> v_reader;
784
785
    // Get the parent variant column reader
786
641
    OlapReaderStatistics stats;
787
    // If status is not ok, it will throw exception(data corruption)
788
641
    THROW_IF_ERROR(get_column_reader(unique_id, &v_reader, &stats));
789
641
    DCHECK(v_reader != nullptr);
790
641
    auto* variant_reader = static_cast<VariantColumnReader*>(v_reader.get());
791
    // Delegate type inference for variant paths to VariantColumnReader.
792
641
    DataTypePtr type;
793
641
    THROW_IF_ERROR(variant_reader->infer_data_type_for_path(&type, column, read_options,
794
641
                                                            _column_reader_cache.get()));
795
641
    return type;
796
641
}
797
798
24.9k
Status Segment::_create_column_meta_once(OlapReaderStatistics* stats) {
799
24.9k
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
800
24.9k
    return _create_column_meta_once_call.call([&] {
801
3.62k
        std::shared_ptr<SegmentFooterPB> footer_pb_shared;
802
3.62k
        RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, stats));
803
3.62k
        return _create_column_meta(*footer_pb_shared);
804
3.62k
    });
805
24.9k
}
806
807
3.63k
Status Segment::_create_column_meta(const SegmentFooterPB& footer) {
808
    // Initialize column meta accessor which internally maintains uid -> column_ordinal mapping.
809
3.63k
    _column_meta_accessor = std::make_unique<ColumnMetaAccessor>();
810
3.63k
    RETURN_IF_ERROR(_column_meta_accessor->init(footer, _file_reader));
811
812
3.63k
    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
28.0k
        auto st = _column_meta_accessor->traverse_metas(footer, [this](const ColumnMetaPB& meta) {
816
28.0k
            if (meta.has_unique_id() && meta.unique_id() != -1 && meta.has_raw_data_bytes()) {
817
25.2k
                _column_uid_to_raw_bytes[meta.unique_id()] = meta.raw_data_bytes();
818
25.2k
            }
819
28.0k
        });
820
821
3.63k
        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
3.63k
    }
826
827
3.63k
    _column_reader_cache = std::make_unique<ColumnReaderCache>(
828
3.63k
            _column_meta_accessor.get(), _tablet_schema, _file_reader, _num_rows,
829
8.34k
            [this](std::shared_ptr<SegmentFooterPB>& footer_pb, OlapReaderStatistics* stats) {
830
8.34k
                return _get_segment_footer(footer_pb, stats);
831
8.34k
            });
832
3.63k
    return Status::OK();
833
3.63k
}
834
835
Status Segment::new_default_iterator(const TabletColumn& tablet_column,
836
14
                                     std::unique_ptr<ColumnIterator>* iter) {
837
14
    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
14
    std::unique_ptr<DefaultValueColumnIterator> default_value_iter(new DefaultValueColumnIterator(
845
14
            tablet_column.has_default_value(), tablet_column.default_value(),
846
14
            tablet_column.is_nullable(), tablet_column.type(), tablet_column.precision(),
847
14
            tablet_column.frac(), tablet_column.length()));
848
14
    ColumnIteratorOptions iter_opts;
849
850
14
    RETURN_IF_ERROR(default_value_iter->init(iter_opts));
851
14
    *iter = std::move(default_value_iter);
852
14
    return Status::OK();
853
14
}
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
7.50k
                                            variant_sparse_column_cache) {
867
7.50k
    if (opt->runtime_state != nullptr) {
868
222
        _be_exec_version = opt->runtime_state->be_exec_version();
869
222
    }
870
7.50k
    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
7.50k
    int32_t unique_id = tablet_column.unique_id() >= 0 ? tablet_column.unique_id()
874
7.50k
                                                       : tablet_column.parent_unique_id();
875
876
    // If column meta for this uid is not found in this segment, use default iterator.
877
7.50k
    if (!_column_meta_accessor->has_column_uid(unique_id)) {
878
6
        RETURN_IF_ERROR(new_default_iterator(tablet_column, iter));
879
6
        return Status::OK();
880
6
    }
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
7.49k
    std::optional<Field> const_value;
891
7.49k
    if (opt->tablet_schema != nullptr && opt->version.first == opt->version.second &&
892
7.49k
        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
7.49k
    std::shared_ptr<ColumnReader> reader;
901
7.49k
    RETURN_IF_ERROR(get_column_reader(unique_id, &reader, opt->stats, std::move(const_value)));
902
7.49k
    if (reader == nullptr) {
903
0
        return Status::InternalError("column reader is nullptr, unique_id={}", unique_id);
904
0
    }
905
7.49k
    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
370
        PathToBinaryColumnCache* sparse_column_cache_ptr = nullptr;
908
370
        if (variant_sparse_column_cache) {
909
370
            auto it = variant_sparse_column_cache->find(unique_id);
910
370
            if (it != variant_sparse_column_cache->end()) {
911
370
                sparse_column_cache_ptr = it->second.get();
912
370
            } else {
913
0
                DCHECK(false) << "sparse column cache is not found, unique_id=" << unique_id;
914
0
            }
915
370
        }
916
        // use _column_reader_cache to get variant subcolumn(path column) reader
917
370
        RETURN_IF_ERROR(assert_cast<VariantColumnReader*>(reader.get())
918
370
                                ->new_iterator(iter, &tablet_column, opt,
919
370
                                               _column_reader_cache.get(),
920
370
                                               sparse_column_cache_ptr));
921
7.12k
    } else {
922
7.12k
        RETURN_IF_ERROR(reader->new_iterator(iter, &tablet_column, opt));
923
7.12k
        if (opt->all_access_paths.contains(unique_id) ||
924
7.12k
            opt->predicate_access_paths.contains(unique_id)) {
925
0
            const auto& all_access_paths = opt->all_access_paths.contains(unique_id)
926
0
                                                   ? opt->all_access_paths.at(unique_id)
927
0
                                                   : TColumnAccessPaths {};
928
0
            const auto& predicate_access_paths = opt->predicate_access_paths.contains(unique_id)
929
0
                                                         ? opt->predicate_access_paths.at(unique_id)
930
0
                                                         : TColumnAccessPaths {};
931
932
            // set column name to apply access paths.
933
0
            (*iter)->set_column_name(tablet_column.name());
934
0
            RETURN_IF_ERROR((*iter)->set_access_paths(all_access_paths, predicate_access_paths));
935
0
            (*iter)->remove_pruned_sub_iterators();
936
0
        }
937
7.12k
    }
938
939
7.49k
    if (config::enable_column_type_check && !tablet_column.has_path_info() &&
940
7.49k
        !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
7.49k
    return Status::OK();
948
7.49k
}
949
950
Status Segment::get_column_reader(int32_t col_uid, std::shared_ptr<ColumnReader>* column_reader,
951
8.57k
                                  OlapReaderStatistics* stats, std::optional<Field> const_value) {
952
8.57k
    RETURN_IF_ERROR(_create_column_meta_once(stats));
953
8.57k
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
954
    // The column is not in this segment, return nullptr
955
8.57k
    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
8.57k
    return _column_reader_cache->get_column_reader(col_uid, column_reader, stats,
961
8.57k
                                                   std::move(const_value));
962
8.57k
}
963
964
332
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
332
    OlapReaderStatistics dummy_stats;
967
332
    RETURN_IF_ERROR(_create_column_meta_once(&dummy_stats));
968
332
    std::shared_ptr<SegmentFooterPB> footer_pb_shared;
969
332
    RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, &dummy_stats));
970
332
    return _column_meta_accessor->traverse_metas(*footer_pb_shared, visitor);
971
332
}
972
973
Status Segment::get_column_reader(const TabletColumn& col,
974
                                  std::shared_ptr<ColumnReader>* column_reader,
975
2.77k
                                  OlapReaderStatistics* stats, std::optional<Field> const_value) {
976
2.77k
    RETURN_IF_ERROR(_create_column_meta_once(stats));
977
2.77k
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
978
2.77k
    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
2.77k
    if (!_tablet_schema->has_column_unique_id(col_uid)) {
981
0
        *column_reader = nullptr;
982
0
        return Status::Error<ErrorCode::NOT_FOUND, false>("column not found in segment, col_uid={}",
983
0
                                                          col_uid);
984
0
    }
985
2.77k
    if (col.has_path_info()) {
986
152
        PathInData relative_path = col.path_info_ptr()->copy_pop_front();
987
152
        return _column_reader_cache->get_path_column_reader(col_uid, relative_path, column_reader,
988
152
                                                            stats);
989
152
    }
990
2.62k
    return _column_reader_cache->get_column_reader(col_uid, column_reader, stats,
991
2.62k
                                                   std::move(const_value));
992
2.77k
}
993
994
Status Segment::new_index_iterator(const TabletColumn& tablet_column, const TabletIndex* index_meta,
995
                                   const StorageReadOptions& read_options,
996
2.68k
                                   std::unique_ptr<IndexIterator>* iter) {
997
2.68k
    if (read_options.runtime_state != nullptr) {
998
76
        _be_exec_version = read_options.runtime_state->be_exec_version();
999
76
    }
1000
2.68k
    RETURN_IF_ERROR(_create_column_meta_once(read_options.stats));
1001
2.68k
    std::shared_ptr<ColumnReader> reader;
1002
2.68k
    auto st = get_column_reader(tablet_column, &reader, read_options.stats);
1003
2.68k
    if (st.is<ErrorCode::NOT_FOUND>()) {
1004
2
        return Status::OK();
1005
2
    }
1006
2.67k
    RETURN_IF_ERROR(st);
1007
2.67k
    DCHECK(reader != nullptr);
1008
2.67k
    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
2.67k
        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
2.67k
        const std::string rowset_id =
1014
2.67k
                index_meta->index_type() == IndexType::ANN ? _rowset_id.to_string() : "";
1015
2.67k
        const bool need_binding_diagnostic = tablet_column.is_variant_type() ||
1016
2.67k
                                             tablet_column.is_extracted_column() ||
1017
2.67k
                                             !index_meta->get_index_suffix().empty();
1018
2.67k
        bool index_file_exists = false;
1019
2.67k
        Status probe_status;
1020
2.67k
        if (need_binding_diagnostic) {
1021
85
            probe_status = _index_file_reader->init(config::inverted_index_read_buffer_size,
1022
85
                                                    &read_options.io_ctx);
1023
85
            if (probe_status.ok()) {
1024
85
                probe_status = _index_file_reader->index_file_exist(index_meta, &index_file_exists);
1025
85
            }
1026
85
            const auto diagnostic = fmt::format(
1027
85
                    "[VariantSearchBinding] phase=index_file_probe tablet_id={} rowset_id={} "
1028
85
                    "segment_id={} column={} logical_path={} index_id={} suffix={} exists={} "
1029
85
                    "status={}",
1030
85
                    read_options.tablet_id, _rowset_id.to_string(), _segment_id,
1031
85
                    tablet_column.name(),
1032
85
                    tablet_column.has_path_info() ? tablet_column.path_info_ptr()->get_path()
1033
85
                                                  : tablet_column.name(),
1034
85
                    index_meta->index_id(), index_meta->get_index_suffix(), index_file_exists,
1035
85
                    probe_status.ok() ? "OK" : probe_status.to_string());
1036
85
            VLOG_DEBUG << diagnostic;
1037
85
            if (read_options.stats != nullptr) {
1038
85
                read_options.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
1039
85
            }
1040
85
        }
1041
2.67k
        Status iter_status = reader->new_index_iterator(_index_file_reader, index_meta, rowset_id,
1042
2.67k
                                                        _segment_id, _num_rows, iter);
1043
2.67k
        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
2.67k
        return Status::OK();
1063
2.67k
    }
1064
0
    return Status::OK();
1065
2.67k
}
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
2
                               OlapReaderStatistics* stats, std::string* encoded_seq_value) {
1070
2
    RETURN_IF_ERROR(load_pk_index_and_bf(stats));
1071
2
    bool has_seq_col = latest_schema->has_sequence_col();
1072
2
    bool has_rowid = !latest_schema->cluster_key_uids().empty();
1073
2
    size_t seq_col_length = 0;
1074
2
    if (has_seq_col) {
1075
2
        seq_col_length = latest_schema->column(latest_schema->sequence_col_idx()).length() + 1;
1076
2
    }
1077
2
    size_t rowid_length = has_rowid ? PrimaryKeyIndexReader::ROW_ID_LENGTH : 0;
1078
1079
2
    Slice key_without_seq =
1080
2
            Slice(key.get_data(), key.get_size() - (with_seq_col ? seq_col_length : 0) -
1081
2
                                          (with_rowid ? rowid_length : 0));
1082
1083
2
    DCHECK(_pk_index_reader != nullptr);
1084
2
    if (!_pk_index_reader->check_present(key_without_seq)) {
1085
0
        return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1086
0
    }
1087
2
    bool exact_match = false;
1088
2
    std::unique_ptr<segment_v2::IndexedColumnIterator> index_iterator;
1089
2
    RETURN_IF_ERROR(_pk_index_reader->new_iterator(&index_iterator, stats));
1090
2
    auto st = index_iterator->seek_at_or_after(&key_without_seq, &exact_match);
1091
2
    if (!st.ok() && !st.is<ErrorCode::ENTRY_NOT_FOUND>()) {
1092
0
        return st;
1093
0
    }
1094
2
    if (st.is<ErrorCode::ENTRY_NOT_FOUND>() || (!has_seq_col && !has_rowid && !exact_match)) {
1095
0
        return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1096
0
    }
1097
2
    row_location->row_id = cast_set<uint32_t>(index_iterator->get_current_ordinal());
1098
2
    row_location->segment_id = _segment_id;
1099
2
    row_location->rowset_id = _rowset_id;
1100
1101
2
    size_t num_to_read = 1;
1102
2
    auto index_type = DataTypeFactory::instance().create_data_type(_pk_index_reader->type(), 1, 0);
1103
2
    auto index_column = index_type->create_column();
1104
2
    size_t num_read = num_to_read;
1105
2
    RETURN_IF_ERROR(index_iterator->next_batch(&num_read, index_column));
1106
2
    DCHECK(num_to_read == num_read);
1107
1108
2
    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
2
    bool segment_has_seq_col = _tablet_schema->has_sequence_col();
1114
2
    Slice sought_key_without_seq = Slice(
1115
2
            sought_key.get_data(),
1116
2
            sought_key.get_size() - (segment_has_seq_col ? seq_col_length : 0) - rowid_length);
1117
1118
2
    if (has_seq_col) {
1119
        // compare key
1120
2
        if (key_without_seq.compare(sought_key_without_seq) != 0) {
1121
0
            return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1122
0
        }
1123
1124
2
        if (with_seq_col && segment_has_seq_col) {
1125
            // compare sequence id
1126
2
            Slice sequence_id =
1127
2
                    Slice(key.get_data() + key_without_seq.get_size() + 1, seq_col_length - 1);
1128
2
            Slice previous_sequence_id =
1129
2
                    Slice(sought_key.get_data() + sought_key_without_seq.get_size() + 1,
1130
2
                          seq_col_length - 1);
1131
2
            if (sequence_id.compare(previous_sequence_id) < 0) {
1132
1
                return Status::Error<ErrorCode::KEY_ALREADY_EXISTS>(
1133
1
                        "key with higher sequence id exists");
1134
1
            }
1135
2
        }
1136
2
    } else if (has_rowid) {
1137
0
        Slice sought_key_without_rowid =
1138
0
                Slice(sought_key.get_data(), sought_key.get_size() - rowid_length);
1139
        // compare key
1140
0
        if (key_without_seq.compare(sought_key_without_rowid) != 0) {
1141
0
            return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1142
0
        }
1143
0
    }
1144
    // found the key, use rowid in pk index if necessary.
1145
1
    if (has_rowid) {
1146
0
        Slice rowid_slice = Slice(sought_key.get_data() + sought_key_without_seq.get_size() +
1147
0
                                          (segment_has_seq_col ? seq_col_length : 0) + 1,
1148
0
                                  rowid_length - 1);
1149
0
        const auto* rowid_coder = get_key_coder(FieldType::OLAP_FIELD_TYPE_UNSIGNED_INT);
1150
0
        RETURN_IF_ERROR(rowid_coder->decode_ascending(&rowid_slice, rowid_length,
1151
0
                                                      (uint8_t*)&row_location->row_id));
1152
0
    }
1153
1154
1
    if (encoded_seq_value) {
1155
0
        if (!segment_has_seq_col) {
1156
0
            *encoded_seq_value = std::string {};
1157
0
        } else {
1158
            // include marker
1159
0
            *encoded_seq_value =
1160
0
                    Slice(sought_key.get_data() + sought_key_without_seq.get_size(), seq_col_length)
1161
0
                            .to_string();
1162
0
        }
1163
0
    }
1164
1
    return Status::OK();
1165
1
}
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
0
                                       std::unique_ptr<ColumnIterator>& iterator_hint) {
1198
0
    if (row_ids.empty()) {
1199
0
        return Status::OK();
1200
0
    }
1201
0
    DORIS_CHECK(std::is_sorted(row_ids.begin(), row_ids.end()));
1202
0
    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
0
    auto io_ctx = storage_read_options.io_ctx;
1206
0
    io_ctx.reader_type = ReaderType::READER_QUERY;
1207
0
    io_ctx.file_cache_stats = &storage_read_options.stats->file_cache_stats;
1208
0
    segment_v2::ColumnIteratorOptions opt {
1209
0
            .use_page_cache = !config::disable_storage_page_cache,
1210
0
            .file_reader = file_reader().get(),
1211
0
            .stats = storage_read_options.stats,
1212
0
            .io_ctx = io_ctx,
1213
0
    };
1214
1215
0
    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
0
        RETURN_IF_ERROR(_create_column_meta_once(storage_read_options.stats));
1219
1220
0
        const auto& dt_variant =
1221
0
                assert_cast<const DataTypeVariant&>(*remove_nullable(slot->type()));
1222
0
        TabletColumn column = TabletColumn::create_materialized_variant_column(
1223
0
                schema.column_by_uid(slot->col_unique_id()).name_lower_case(), slot->column_paths(),
1224
0
                slot->col_unique_id(), dt_variant.variant_max_subcolumns_count(),
1225
0
                dt_variant.enable_doc_mode());
1226
0
        auto storage_type = get_data_type_of(column, storage_read_options);
1227
0
        MutableColumnPtr file_storage_column = storage_type->create_column();
1228
0
        DCHECK(storage_type != nullptr);
1229
1230
0
        if (iterator_hint == nullptr) {
1231
0
            RETURN_IF_ERROR(new_column_iterator(column, &iterator_hint, &storage_read_options));
1232
0
            RETURN_IF_ERROR(iterator_hint->init(opt));
1233
0
        }
1234
0
        RETURN_IF_ERROR(
1235
0
                iterator_hint->read_by_rowids(row_ids.data(), row_ids.size(), file_storage_column));
1236
0
        ColumnPtr source_ptr;
1237
        // storage may have different type with schema, so we need to cast the column
1238
0
        RETURN_IF_ERROR(variant_util::cast_column(
1239
0
                ColumnWithTypeAndName(file_storage_column->get_ptr(), storage_type, column.name()),
1240
0
                slot->type(), &source_ptr));
1241
0
        RETURN_IF_CATCH_EXCEPTION(result->insert_range_from(*source_ptr, 0, row_ids.size()));
1242
0
    } else {
1243
0
        int index = (slot->col_unique_id() >= 0) ? schema.field_index(slot->col_unique_id())
1244
0
                                                 : schema.field_index(slot->col_name());
1245
0
        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
0
        if (iterator_hint == nullptr) {
1252
0
            RETURN_IF_ERROR(new_column_iterator(schema.column(index), &iterator_hint,
1253
0
                                                &storage_read_options));
1254
0
            RETURN_IF_ERROR(iterator_hint->init(opt));
1255
0
        }
1256
0
        RETURN_IF_ERROR(iterator_hint->read_by_rowids(row_ids.data(), row_ids.size(), result));
1257
0
    }
1258
0
    return Status::OK();
1259
0
}
1260
1261
Status Segment::_get_segment_footer(std::shared_ptr<SegmentFooterPB>& footer_pb,
1262
16.1k
                                    OlapReaderStatistics* stats) {
1263
16.1k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared = _footer_pb.lock();
1264
16.1k
    if (footer_pb_shared != nullptr) {
1265
12.3k
        footer_pb = footer_pb_shared;
1266
12.3k
        return Status::OK();
1267
12.3k
    }
1268
1269
3.82k
    VLOG_DEBUG << fmt::format("Segment footer of {}:{}:{} is missing, try to load it",
1270
0
                              _file_reader->path().native(), _file_reader->size(),
1271
0
                              _file_reader->size() - 12);
1272
1273
3.82k
    StoragePageCache* segment_footer_cache = ExecEnv::GetInstance()->get_storage_page_cache();
1274
3.82k
    DCHECK(segment_footer_cache != nullptr);
1275
1276
3.82k
    auto cache_key = get_segment_footer_cache_key();
1277
1278
3.82k
    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
3.82k
    if (!segment_footer_cache->lookup(cache_key, &cache_handle,
1286
3.82k
                                      segment_v2::PageTypePB::INDEX_PAGE)) {
1287
2.20k
        RETURN_IF_ERROR(_parse_footer(footer_pb_shared, stats));
1288
2.20k
        segment_footer_cache->insert(cache_key, footer_pb_shared, footer_pb_shared->ByteSizeLong(),
1289
2.20k
                                     &cache_handle, segment_v2::PageTypePB::INDEX_PAGE);
1290
2.20k
    } else {
1291
1.62k
        VLOG_DEBUG << fmt::format("Segment footer of {}:{}:{} is found in cache",
1292
0
                                  _file_reader->path().native(), _file_reader->size(),
1293
0
                                  _file_reader->size() - 12);
1294
1.62k
    }
1295
3.82k
    footer_pb_shared = cache_handle.get<std::shared_ptr<SegmentFooterPB>>();
1296
3.82k
    _footer_pb = footer_pb_shared;
1297
3.82k
    footer_pb = footer_pb_shared;
1298
3.82k
    return Status::OK();
1299
3.82k
}
1300
1301
3.83k
StoragePageCache::CacheKey Segment::get_segment_footer_cache_key() const {
1302
3.83k
    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
3.83k
    return get_segment_footer_cache_key(_file_reader);
1307
3.83k
}
1308
1309
StoragePageCache::CacheKey Segment::get_segment_footer_cache_key(
1310
3.87k
        const io::FileReaderSPtr& file_reader) {
1311
3.87k
    return {file_reader->path().native(), file_reader->size(),
1312
3.87k
            static_cast<int64_t>(file_reader->size() - 12)};
1313
3.87k
}
1314
1315
} // namespace doris::segment_v2