Coverage Report

Created: 2026-07-13 07:44

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