Coverage Report

Created: 2026-08-14 11:09

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