Coverage Report

Created: 2026-08-01 07:39

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