Coverage Report

Created: 2026-08-14 13:23

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