Coverage Report

Created: 2026-06-08 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/segment.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "storage/segment/segment.h"
19
20
#include <crc32c/crc32c.h>
21
#include <gen_cpp/Descriptors_types.h>
22
#include <gen_cpp/PlanNodes_types.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <gen_cpp/segment_v2.pb.h>
25
26
#include <algorithm>
27
#include <cstring>
28
#include <memory>
29
#include <set>
30
#include <sstream>
31
#include <utility>
32
33
#include "cloud/config.h"
34
#include "common/config.h"
35
#include "common/exception.h"
36
#include "common/logging.h"
37
#include "common/status.h"
38
#include "core/column/column.h"
39
#include "core/data_type/data_type.h"
40
#include "core/data_type/data_type_factory.hpp"
41
#include "core/data_type/data_type_nullable.h"
42
#include "core/data_type/data_type_variant.h"
43
#include "core/field.h"
44
#include "core/string_ref.h"
45
#include "cpp/sync_point.h"
46
#include "exprs/expr_zonemap_filter.h"
47
#include "exprs/vexpr_context.h"
48
#include "io/cache/block_file_cache.h"
49
#include "io/cache/block_file_cache_factory.h"
50
#include "io/cache/cached_remote_file_reader.h"
51
#include "io/fs/file_reader.h"
52
#include "io/fs/file_system.h"
53
#include "io/io_common.h"
54
#include "runtime/exec_env.h"
55
#include "runtime/query_context.h"
56
#include "runtime/runtime_predicate.h"
57
#include "runtime/runtime_state.h"
58
#include "storage/index/index_file_reader.h"
59
#include "storage/index/indexed_column_reader.h"
60
#include "storage/index/primary_key_index.h"
61
#include "storage/index/short_key_index.h"
62
#include "storage/index/zone_map/zonemap_eval_context.h"
63
#include "storage/iterator/vgeneric_iterators.h"
64
#include "storage/iterators.h"
65
#include "storage/key_coder.h"
66
#include "storage/olap_common.h"
67
#include "storage/predicate/block_column_predicate.h"
68
#include "storage/predicate/column_predicate.h"
69
#include "storage/rowset/rowset_reader_context.h"
70
#include "storage/schema.h"
71
#include "storage/segment/column_meta_accessor.h"
72
#include "storage/segment/column_reader.h"
73
#include "storage/segment/column_reader_cache.h"
74
#include "storage/segment/empty_segment_iterator.h"
75
#include "storage/segment/page_io.h"
76
#include "storage/segment/page_pointer.h"
77
#include "storage/segment/segment_iterator.h"
78
#include "storage/segment/segment_writer.h" // k_segment_magic_length
79
#include "storage/segment/stream_reader.h"
80
#include "storage/segment/variant/variant_column_reader.h"
81
#include "storage/tablet/tablet_schema.h"
82
#include "storage/types.h"
83
#include "storage/utils.h"
84
#include "util/coding.h"
85
#include "util/json/path_in_data.h"
86
#include "util/slice.h" // Slice
87
88
namespace doris::segment_v2 {
89
90
class InvertedIndexIterator;
91
92
namespace {
93
94
Status build_segment_zonemap_context(Segment* segment, const Schema& schema,
95
                                     const StorageReadOptions& read_options,
96
15.6k
                                     const VExprContextSPtrs& conjuncts, ZoneMapEvalContext* ctx) {
97
15.6k
    DORIS_CHECK(segment != nullptr);
98
15.6k
    DORIS_CHECK(ctx != nullptr);
99
15.6k
    std::set<int> slot_indexes;
100
17.6k
    for (const auto& conjunct : conjuncts) {
101
17.6k
        DORIS_CHECK(conjunct != nullptr);
102
17.6k
        auto root = conjunct->root();
103
17.6k
        DORIS_CHECK(root != nullptr);
104
17.6k
        if (!root->can_evaluate_zonemap_filter()) {
105
16.0k
            continue;
106
16.0k
        }
107
1.64k
        std::set<int> expr_slot_indexes;
108
1.64k
        root->collect_slot_column_ids(expr_slot_indexes);
109
1.64k
        slot_indexes.insert(expr_slot_indexes.begin(), expr_slot_indexes.end());
110
1.64k
    }
111
15.6k
    for (const int slot_index : slot_indexes) {
112
2.60k
        if (slot_index < 0 || cast_set<size_t>(slot_index) >= schema.num_column_ids()) {
113
0
            continue;
114
0
        }
115
2.60k
        const auto column_id = schema.column_id(cast_set<size_t>(slot_index));
116
2.60k
        const auto* field = schema.column(column_id);
117
2.60k
        DORIS_CHECK(field != nullptr);
118
2.60k
        if (!segment->can_apply_predicate_safely(
119
2.60k
                    column_id, schema, read_options.target_cast_type_for_variants, read_options)) {
120
34
            continue;
121
34
        }
122
2.57k
        auto data_type = segment->get_data_type_of(*field, read_options);
123
2.57k
        if (data_type == nullptr) {
124
0
            continue;
125
0
        }
126
2.57k
        ZoneMapEvalContext::SlotZoneMap slot_zone_map;
127
2.57k
        slot_zone_map.data_type = data_type;
128
2.57k
        std::shared_ptr<ColumnReader> reader;
129
2.57k
        Status st = segment->get_column_reader(*field, &reader, read_options.stats);
130
2.57k
        if (st.is<ErrorCode::NOT_FOUND>()) {
131
30
            ctx->slots.emplace(slot_index, std::move(slot_zone_map));
132
30
            continue;
133
30
        }
134
2.54k
        RETURN_IF_ERROR(st);
135
2.54k
        if (reader != nullptr && reader->has_zone_map()) {
136
2.27k
            ZoneMap zone_map;
137
2.27k
            RETURN_IF_ERROR(reader->get_segment_zone_map(&zone_map));
138
2.27k
            slot_zone_map.zone_map = std::move(zone_map);
139
2.27k
        }
140
2.54k
        ctx->slots.emplace(slot_index, std::move(slot_zone_map));
141
2.54k
    }
142
15.6k
    return Status::OK();
143
15.6k
}
144
145
16.4k
bool storage_expr_slots_match_reader_schema(const StorageReadOptions& read_options) {
146
16.4k
    DORIS_CHECK(read_options.tablet_schema != nullptr);
147
16.4k
    const auto keys_type = read_options.tablet_schema->keys_type();
148
16.4k
    return keys_type == KeysType::DUP_KEYS ||
149
16.4k
           (keys_type == KeysType::UNIQUE_KEYS && read_options.enable_unique_key_merge_on_write);
150
16.4k
}
151
152
} // namespace
153
154
Status Segment::open(io::FileSystemSPtr fs, const std::string& path, int64_t tablet_id,
155
                     uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
156
                     const io::FileReaderOptions& reader_options, std::shared_ptr<Segment>* output,
157
169k
                     InvertedIndexFileInfo idx_file_info, OlapReaderStatistics* stats) {
158
    // Ensure tablet_id is available in reader_options for CachedRemoteFileReader peer read.
159
169k
    io::FileReaderOptions opts_with_tablet = reader_options;
160
169k
    opts_with_tablet.tablet_id = tablet_id;
161
162
169k
    auto s = _open(fs, path, segment_id, rowset_id, tablet_schema, opts_with_tablet, output,
163
169k
                   idx_file_info, stats);
164
172k
    if (s.ok() && output && *output) {
165
172k
        (*output)->_tablet_id = tablet_id;
166
172k
    }
167
169k
    if (!s.ok()) {
168
5
        if (!config::is_cloud_mode()) {
169
5
            auto res = ExecEnv::get_tablet(tablet_id);
170
5
            TabletSharedPtr tablet =
171
5
                    res.has_value() ? std::dynamic_pointer_cast<Tablet>(res.value()) : nullptr;
172
5
            if (tablet) {
173
0
                tablet->report_error(s);
174
0
            }
175
5
        }
176
5
    }
177
178
169k
    return s;
179
169k
}
180
181
Status Segment::_open(io::FileSystemSPtr fs, const std::string& path, uint32_t segment_id,
182
                      RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
183
                      const io::FileReaderOptions& reader_options, std::shared_ptr<Segment>* output,
184
170k
                      InvertedIndexFileInfo idx_file_info, OlapReaderStatistics* stats) {
185
170k
    io::FileReaderSPtr file_reader;
186
170k
    auto st = fs->open_file(path, &file_reader, &reader_options);
187
170k
    TEST_INJECTION_POINT_CALLBACK("Segment::open:corruption", &st);
188
170k
    std::shared_ptr<Segment> segment(
189
170k
            new Segment(segment_id, rowset_id, std::move(tablet_schema), idx_file_info));
190
172k
    if (st) {
191
172k
        segment->_fs = fs;
192
172k
        segment->_file_reader = std::move(file_reader);
193
172k
        st = segment->_open(stats);
194
172k
    }
195
196
    // Three-tier retry for CORRUPTION errors when file cache is enabled.
197
    // This handles CORRUPTION from both open_file() and _parse_footer() (via _open()).
198
170k
    if (st.is<ErrorCode::CORRUPTION>() &&
199
170k
        reader_options.cache_type == io::FileCachePolicy::FILE_BLOCK_CACHE) {
200
        // Tier 1: Clear file cache and retry with cache support (re-downloads from remote).
201
2
        LOG(WARNING) << "bad segment file may be read from file cache, try to read remote source "
202
2
                        "file directly, file path: "
203
2
                     << path << " cache_key: " << file_cache_key_str(path);
204
2
        auto file_key = file_cache_key_from_path(path);
205
2
        auto* file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
206
2
        file_cache->remove_if_cached(file_key);
207
208
2
        st = fs->open_file(path, &file_reader, &reader_options);
209
2
        if (st) {
210
2
            segment->_fs = fs;
211
2
            segment->_file_reader = std::move(file_reader);
212
2
            st = segment->_open(stats);
213
2
        }
214
2
        TEST_INJECTION_POINT_CALLBACK("Segment::open:corruption1", &st);
215
2
        if (st.is<ErrorCode::CORRUPTION>()) { // corrupt again
216
            // Tier 2: Bypass cache entirely and read directly from remote storage.
217
0
            LOG(WARNING) << "failed to try to read remote source file again with cache support,"
218
0
                         << " try to read from remote directly, "
219
0
                         << " file path: " << path << " cache_key: " << file_cache_key_str(path);
220
0
            file_cache = io::FileCacheFactory::instance()->get_by_path(file_key);
221
0
            file_cache->remove_if_cached(file_key);
222
223
0
            io::FileReaderOptions opt = reader_options;
224
0
            opt.cache_type = io::FileCachePolicy::NO_CACHE; // skip cache
225
0
            RETURN_IF_ERROR(fs->open_file(path, &file_reader, &opt));
226
0
            segment->_fs = fs;
227
0
            segment->_file_reader = std::move(file_reader);
228
0
            st = segment->_open(stats);
229
0
            if (!st.ok()) {
230
                // Tier 3: Remote source itself is corrupt.
231
0
                LOG(WARNING) << "failed to try to read remote source file directly,"
232
0
                             << " file path: " << path
233
0
                             << " cache_key: " << file_cache_key_str(path);
234
0
            }
235
0
        }
236
2
    }
237
170k
    RETURN_IF_ERROR(st);
238
18.4E
    DCHECK(segment->_fs != nullptr) << "file system is nullptr after segment open";
239
170k
    *output = std::move(segment);
240
170k
    return Status::OK();
241
170k
}
242
243
Segment::Segment(uint32_t segment_id, RowsetId rowset_id, TabletSchemaSPtr tablet_schema,
244
                 InvertedIndexFileInfo idx_file_info)
245
172k
        : _segment_id(segment_id),
246
172k
          _meta_mem_usage(0),
247
172k
          _rowset_id(rowset_id),
248
172k
          _tablet_schema(std::move(tablet_schema)),
249
172k
          _idx_file_info(std::move(idx_file_info)) {}
250
251
137k
Segment::~Segment() {
252
137k
    g_segment_estimate_mem_bytes << -_tracked_meta_mem_usage;
253
    // if failed, fix `_tracked_meta_mem_usage` accuracy
254
137k
    DCHECK(_tracked_meta_mem_usage == meta_mem_usage());
255
137k
}
256
257
46.5k
io::UInt128Wrapper Segment::file_cache_key(std::string_view rowset_id, uint32_t seg_id) {
258
46.5k
    return io::BlockFileCache::hash(fmt::format("{}_{}.dat", rowset_id, seg_id));
259
46.5k
}
260
261
169k
int64_t Segment::get_metadata_size() const {
262
169k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared = _footer_pb.lock();
263
169k
    return sizeof(Segment) + (_pk_index_meta ? _pk_index_meta->ByteSizeLong() : 0) +
264
18.4E
           (footer_pb_shared ? footer_pb_shared->ByteSizeLong() : 0);
265
169k
}
266
267
170k
void Segment::update_metadata_size() {
268
170k
    MetadataAdder::update_metadata_size();
269
170k
    g_segment_estimate_mem_bytes << _meta_mem_usage - _tracked_meta_mem_usage;
270
170k
    _tracked_meta_mem_usage = _meta_mem_usage;
271
170k
}
272
273
172k
Status Segment::_open(OlapReaderStatistics* stats) {
274
172k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared;
275
172k
    RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, stats));
276
277
172k
    _pk_index_meta.reset(
278
172k
            footer_pb_shared->has_primary_key_index_meta()
279
172k
                    ? new PrimaryKeyIndexMetaPB(footer_pb_shared->primary_key_index_meta())
280
172k
                    : nullptr);
281
    // delete_bitmap_calculator_test.cpp
282
    // DCHECK(footer.has_short_key_index_page());
283
172k
    _sk_index_page = footer_pb_shared->short_key_index_page();
284
172k
    _num_rows = footer_pb_shared->num_rows();
285
286
    // An estimated memory usage of a segment
287
    // Footer is seperated to StoragePageCache so we don't need to add it to _meta_mem_usage
288
    // _meta_mem_usage += footer_pb_shared->ByteSizeLong();
289
172k
    if (_pk_index_meta != nullptr) {
290
105k
        _meta_mem_usage += _pk_index_meta->ByteSizeLong();
291
105k
    }
292
293
172k
    _meta_mem_usage += sizeof(*this);
294
172k
    _meta_mem_usage += std::min(static_cast<int>(_tablet_schema->num_columns()),
295
172k
                                config::max_segment_partial_column_cache_size) *
296
172k
                       config::estimated_mem_per_column_reader;
297
298
    // 1024 comes from SegmentWriterOptions
299
172k
    _meta_mem_usage += (_num_rows + 1023) / 1024 * (36 + 4);
300
    // 0.01 comes from PrimaryKeyIndexBuilder::init
301
172k
    _meta_mem_usage += BloomFilter::optimal_bit_num(_num_rows, 0.01) / 8;
302
303
172k
    update_metadata_size();
304
305
172k
    return Status::OK();
306
172k
}
307
308
5.38k
Status Segment::_open_index_file_reader() {
309
5.38k
    _index_file_reader = std::make_shared<IndexFileReader>(
310
5.38k
            _fs,
311
5.38k
            std::string {InvertedIndexDescriptor::get_index_file_path_prefix(
312
5.38k
                    _file_reader->path().native())},
313
5.38k
            _tablet_schema->get_inverted_index_storage_format(), _idx_file_info, _tablet_id);
314
5.38k
    return Status::OK();
315
5.38k
}
316
317
Status Segment::new_iterator(SchemaSPtr schema, const StorageReadOptions& read_options,
318
1.47M
                             std::unique_ptr<RowwiseIterator>* iter) {
319
1.47M
    if (read_options.runtime_state != nullptr) {
320
1.39M
        _be_exec_version = read_options.runtime_state->be_exec_version();
321
1.39M
    }
322
1.47M
    RETURN_IF_ERROR(_create_column_meta_once(read_options.stats));
323
324
1.47M
    read_options.stats->total_segment_number++;
325
    // trying to prune the current segment by segment-level zone map
326
1.47M
    for (const auto& entry : read_options.col_id_to_predicates) {
327
1.24M
        int32_t column_id = entry.first;
328
        // schema change
329
1.24M
        if (_tablet_schema->num_columns() <= column_id) {
330
1.21k
            continue;
331
1.21k
        }
332
1.24M
        const TabletColumn& col = read_options.tablet_schema->column(column_id);
333
1.24M
        std::shared_ptr<ColumnReader> reader;
334
1.24M
        Status st = get_column_reader(col, &reader, read_options.stats);
335
        // not found in this segment, skip
336
1.24M
        if (st.is<ErrorCode::NOT_FOUND>()) {
337
80
            continue;
338
80
        }
339
1.24M
        RETURN_IF_ERROR(st);
340
        // should be OK
341
1.24M
        DCHECK(reader != nullptr);
342
1.24M
        if (!reader->has_zone_map()) {
343
0
            continue;
344
0
        }
345
1.24M
        if (read_options.col_id_to_predicates.contains(column_id) &&
346
1.24M
            can_apply_predicate_safely(column_id, *schema,
347
1.24M
                                       read_options.target_cast_type_for_variants, read_options)) {
348
1.24M
            bool matched = true;
349
1.24M
            RETURN_IF_ERROR(reader->match_condition(entry.second.get(), &matched));
350
1.24M
            if (!matched) {
351
                // any condition not satisfied, return.
352
86.8k
                *iter = std::make_unique<EmptySegmentIterator>(*schema);
353
86.8k
                read_options.stats->filtered_segment_number++;
354
86.8k
                return Status::OK();
355
86.8k
            }
356
1.24M
        }
357
1.24M
    }
358
359
    // Segment-level expr-zonemap runs before SegmentIterator can rebind storage expressions to
360
    // the reader schema. Only apply it when scan tuple slot ordinals already match this schema.
361
1.38M
    if (expr_zonemap::is_expr_zonemap_filter_enabled(read_options.runtime_state) &&
362
1.38M
        !read_options.common_expr_ctxs_push_down.empty() &&
363
1.38M
        storage_expr_slots_match_reader_schema(read_options)) {
364
15.6k
        ZoneMapEvalContext ctx;
365
15.6k
        RETURN_IF_ERROR(build_segment_zonemap_context(
366
15.6k
                this, *schema, read_options, read_options.common_expr_ctxs_push_down, &ctx));
367
15.6k
        const auto result =
368
15.6k
                VExprContext::evaluate_zonemap_filter(read_options.common_expr_ctxs_push_down, ctx);
369
15.6k
        ctx.stats.accumulate_to(read_options.stats);
370
15.6k
        if (result == ZoneMapFilterResult::kNoMatch) {
371
316
            *iter = std::make_unique<EmptySegmentIterator>(*schema);
372
316
            read_options.stats->filtered_segment_number++;
373
316
            read_options.stats->expr_zonemap_filtered_segments++;
374
316
            return Status::OK();
375
316
        }
376
15.6k
    }
377
378
1.38M
    {
379
1.38M
        SCOPED_RAW_TIMER(&read_options.stats->segment_load_index_timer_ns);
380
1.38M
        RETURN_IF_ERROR(load_index(read_options.stats));
381
1.38M
    }
382
383
1.38M
    if (read_options.delete_condition_predicates->num_of_column_predicate() == 0 &&
384
1.38M
        read_options.push_down_agg_type_opt != TPushAggOp::NONE &&
385
1.38M
        read_options.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
386
7.28k
        iter->reset(new_vstatistics_iterator(this->shared_from_this(), *schema));
387
1.37M
    } else {
388
1.37M
        *iter = std::make_unique<SegmentIterator>(this->shared_from_this(), schema);
389
1.37M
    }
390
391
    // TODO: Valid the opt not only in ReaderType::READER_QUERY
392
1.38M
    if (read_options.io_ctx.reader_type == ReaderType::READER_QUERY &&
393
1.38M
        !read_options.column_predicates.empty()) {
394
1.11M
        auto pruned_predicates = read_options.column_predicates;
395
1.11M
        auto pruned = false;
396
15.7M
        for (auto& it : _column_reader_cache->get_available_readers(false)) {
397
15.7M
            const auto uid = it.first;
398
15.7M
            const auto column_id = read_options.tablet_schema->field_index(uid);
399
15.7M
            bool tmp_pruned = false;
400
15.7M
            RETURN_IF_ERROR(it.second->prune_predicates_by_zone_map(pruned_predicates, column_id,
401
15.7M
                                                                    &tmp_pruned));
402
15.7M
            pruned |= tmp_pruned;
403
15.7M
        }
404
405
1.11M
        if (pruned) {
406
7.49k
            auto options_with_pruned_predicates = read_options;
407
7.49k
            options_with_pruned_predicates.column_predicates = pruned_predicates;
408
            //because column_predicates is changed, we need to rebuild col_id_to_predicates so that inverted index will not go through it.
409
7.49k
            options_with_pruned_predicates.col_id_to_predicates.clear();
410
13.1k
            for (auto pred : options_with_pruned_predicates.column_predicates) {
411
13.1k
                if (!options_with_pruned_predicates.col_id_to_predicates.contains(
412
13.1k
                            pred->column_id())) {
413
9.45k
                    options_with_pruned_predicates.col_id_to_predicates.insert(
414
9.45k
                            {pred->column_id(), AndBlockColumnPredicate::create_shared()});
415
9.45k
                }
416
13.1k
                options_with_pruned_predicates.col_id_to_predicates[pred->column_id()]
417
13.1k
                        ->add_column_predicate(SingleColumnBlockPredicate::create_unique(pred));
418
13.1k
            }
419
7.49k
            return iter->get()->init(options_with_pruned_predicates);
420
7.49k
        }
421
1.11M
    }
422
1.37M
    return iter->get()->init(read_options);
423
1.38M
}
424
425
Status Segment::_write_error_file(size_t file_size, size_t offset, size_t bytes_read, char* data,
426
1
                                  io::IOContext& io_ctx) {
427
1
    if (!config::enbale_dump_error_file || !doris::config::is_cloud_mode()) {
428
1
        return Status::OK();
429
1
    }
430
431
0
    std::string file_name = _rowset_id.to_string() + "_" + std::to_string(_segment_id) + ".dat";
432
0
    std::string dir_path = io::FileCacheFactory::instance()->get_base_paths()[0] + "/error_file/";
433
0
    Status create_st = io::global_local_filesystem()->create_directory(dir_path, true);
434
0
    if (!create_st.ok() && !create_st.is<ErrorCode::ALREADY_EXIST>()) {
435
0
        LOG(WARNING) << "failed to create error file dir: " << create_st.to_string();
436
0
        return create_st;
437
0
    }
438
0
    size_t dir_size = 0;
439
0
    RETURN_IF_ERROR(io::global_local_filesystem()->directory_size(dir_path, &dir_size));
440
0
    if (dir_size > config::file_cache_error_log_limit_bytes) {
441
0
        LOG(WARNING) << "error file dir size is too large: " << dir_size;
442
0
        return Status::OK();
443
0
    }
444
445
0
    std::string error_part;
446
0
    error_part.resize(bytes_read);
447
0
    std::string part_path = dir_path + file_name + ".part_offset_" + std::to_string(offset);
448
0
    LOG(WARNING) << "writer error part to " << part_path;
449
0
    bool is_part_exist = false;
450
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(part_path, &is_part_exist));
451
0
    if (is_part_exist) {
452
0
        LOG(WARNING) << "error part already exists: " << part_path;
453
0
    } else {
454
0
        std::unique_ptr<io::FileWriter> part_writer;
455
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_file(part_path, &part_writer));
456
0
        RETURN_IF_ERROR(part_writer->append(Slice(data, bytes_read)));
457
0
        RETURN_IF_ERROR(part_writer->close());
458
0
    }
459
460
0
    std::string error_file;
461
0
    error_file.resize(file_size);
462
0
    auto* cached_reader = dynamic_cast<io::CachedRemoteFileReader*>(_file_reader.get());
463
0
    if (cached_reader == nullptr) {
464
0
        return Status::InternalError("file reader is not CachedRemoteFileReader");
465
0
    }
466
0
    size_t error_file_bytes_read = 0;
467
0
    RETURN_IF_ERROR(cached_reader->get_remote_reader()->read_at(
468
0
            0, Slice(error_file.data(), file_size), &error_file_bytes_read, &io_ctx));
469
0
    DCHECK(error_file_bytes_read == file_size);
470
    //std::string file_path = dir_path + std::to_string(cur_time) + "_" + ss.str();
471
0
    std::string file_path = dir_path + file_name;
472
0
    LOG(WARNING) << "writer error file to " << file_path;
473
0
    bool is_file_exist = false;
474
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(file_path, &is_file_exist));
475
0
    if (is_file_exist) {
476
0
        LOG(WARNING) << "error file already exists: " << part_path;
477
0
    } else {
478
0
        std::unique_ptr<io::FileWriter> writer;
479
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_file(file_path, &writer));
480
0
        RETURN_IF_ERROR(writer->append(Slice(error_file.data(), file_size)));
481
0
        RETURN_IF_ERROR(writer->close());
482
0
    }
483
0
    return Status::OK(); // already exists
484
0
};
485
486
Status Segment::_parse_footer(std::shared_ptr<SegmentFooterPB>& footer,
487
69.2k
                              OlapReaderStatistics* stats) {
488
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
489
69.2k
    auto file_size = _file_reader->size();
490
69.2k
    if (file_size < 12) {
491
0
        return Status::Corruption("Bad segment file {}: file size {} < 12, cache_key: {}",
492
0
                                  _file_reader->path().native(), file_size,
493
0
                                  file_cache_key_str(_file_reader->path().native()));
494
0
    }
495
496
69.2k
    uint8_t fixed_buf[12];
497
69.2k
    size_t bytes_read = 0;
498
    // TODO(plat1ko): Support session variable `enable_file_cache`
499
69.2k
    io::IOContext io_ctx {.is_index_data = true,
500
69.2k
                          .file_cache_stats = stats ? &stats->file_cache_stats : nullptr};
501
69.2k
    RETURN_IF_ERROR(
502
69.2k
            _file_reader->read_at(file_size - 12, Slice(fixed_buf, 12), &bytes_read, &io_ctx));
503
69.2k
    DCHECK_EQ(bytes_read, 12);
504
69.2k
    TEST_SYNC_POINT_CALLBACK("Segment::parse_footer:magic_number_corruption", fixed_buf);
505
69.2k
    TEST_INJECTION_POINT_CALLBACK("Segment::parse_footer:magic_number_corruption_inj", fixed_buf);
506
69.2k
    if (memcmp(fixed_buf + 8, k_segment_magic, k_segment_magic_length) != 0) {
507
1
        Status st =
508
1
                _write_error_file(file_size, file_size - 12, bytes_read, (char*)fixed_buf, io_ctx);
509
1
        if (!st.ok()) {
510
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
511
0
        }
512
1
        return Status::Corruption(
513
1
                "Bad segment file {}: file_size: {}, magic number not match, cache_key: {}",
514
1
                _file_reader->path().native(), file_size,
515
1
                file_cache_key_str(_file_reader->path().native()));
516
1
    }
517
518
    // read footer PB
519
69.2k
    uint32_t footer_length = decode_fixed32_le(fixed_buf);
520
69.2k
    if (file_size < 12 + footer_length) {
521
0
        Status st =
522
0
                _write_error_file(file_size, file_size - 12, bytes_read, (char*)fixed_buf, io_ctx);
523
0
        if (!st.ok()) {
524
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
525
0
        }
526
0
        return Status::Corruption("Bad segment file {}: file size {} < {}, cache_key: {}",
527
0
                                  _file_reader->path().native(), file_size, 12 + footer_length,
528
0
                                  file_cache_key_str(_file_reader->path().native()));
529
0
    }
530
531
69.2k
    std::string footer_buf;
532
69.2k
    footer_buf.resize(footer_length);
533
69.2k
    RETURN_IF_ERROR(_file_reader->read_at(file_size - 12 - footer_length, footer_buf, &bytes_read,
534
69.2k
                                          &io_ctx));
535
69.2k
    DCHECK_EQ(bytes_read, footer_length);
536
537
    // validate footer PB's checksum
538
69.2k
    uint32_t expect_checksum = decode_fixed32_le(fixed_buf + 4);
539
69.2k
    uint32_t actual_checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
540
69.2k
    if (actual_checksum != expect_checksum) {
541
0
        Status st = _write_error_file(file_size, file_size - 12 - footer_length, bytes_read,
542
0
                                      footer_buf.data(), io_ctx);
543
0
        if (!st.ok()) {
544
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
545
0
        }
546
0
        return Status::Corruption(
547
0
                "Bad segment file {}: file_size = {}, footer checksum not match, actual={} "
548
0
                "vs expect={}, cache_key: {}",
549
0
                _file_reader->path().native(), file_size, actual_checksum, expect_checksum,
550
0
                file_cache_key_str(_file_reader->path().native()));
551
0
    }
552
553
    // deserialize footer PB
554
69.2k
    footer = std::make_shared<SegmentFooterPB>();
555
69.2k
    if (!footer->ParseFromString(footer_buf)) {
556
0
        Status st = _write_error_file(file_size, file_size - 12 - footer_length, bytes_read,
557
0
                                      footer_buf.data(), io_ctx);
558
0
        if (!st.ok()) {
559
0
            LOG(WARNING) << "failed to write error file: " << st.to_string();
560
0
        }
561
0
        return Status::Corruption(
562
0
                "Bad segment file {}: file_size = {}, failed to parse SegmentFooterPB, "
563
0
                "cache_key: ",
564
0
                _file_reader->path().native(), file_size,
565
0
                file_cache_key_str(_file_reader->path().native()));
566
0
    }
567
568
69.2k
    VLOG_DEBUG << fmt::format("Loading segment footer from {} finished",
569
21
                              _file_reader->path().native());
570
69.2k
    return Status::OK();
571
69.2k
}
572
573
3.97M
Status Segment::_load_pk_bloom_filter(OlapReaderStatistics* stats) {
574
#ifdef BE_TEST
575
    if (_pk_index_meta == nullptr) {
576
        // for BE UT "segment_cache_test"
577
        return _load_pk_bf_once.call([this] {
578
            _meta_mem_usage += 100;
579
            update_metadata_size();
580
            return Status::OK();
581
        });
582
    }
583
#endif
584
3.97M
    DCHECK(_tablet_schema->keys_type() == UNIQUE_KEYS);
585
3.97M
    DCHECK(_pk_index_meta != nullptr);
586
3.97M
    DCHECK(_pk_index_reader != nullptr);
587
588
3.97M
    return _load_pk_bf_once.call([this, stats] {
589
38.6k
        RETURN_IF_ERROR(_pk_index_reader->parse_bf(_file_reader, *_pk_index_meta, stats));
590
        // _meta_mem_usage += _pk_index_reader->get_bf_memory_size();
591
38.6k
        return Status::OK();
592
38.6k
    });
593
3.97M
}
594
595
3.98M
Status Segment::load_pk_index_and_bf(OlapReaderStatistics* index_load_stats) {
596
    // `DorisCallOnce` may catch exception in calling stack A and re-throw it in
597
    // a different calling stack B which doesn't have catch block. So we add catch block here
598
    // to prevent coreudmp
599
3.98M
    RETURN_IF_CATCH_EXCEPTION({
600
3.98M
        RETURN_IF_ERROR(load_index(index_load_stats));
601
3.98M
        RETURN_IF_ERROR(_load_pk_bloom_filter(index_load_stats));
602
3.98M
    });
603
3.98M
    return Status::OK();
604
3.98M
}
605
606
5.38M
Status Segment::load_index(OlapReaderStatistics* stats) {
607
5.38M
    return _load_index_once.call([this, stats] {
608
89.4k
        if (_tablet_schema->keys_type() == UNIQUE_KEYS && _pk_index_meta != nullptr) {
609
49.7k
            _pk_index_reader = std::make_unique<PrimaryKeyIndexReader>();
610
49.7k
            RETURN_IF_ERROR(_pk_index_reader->parse_index(_file_reader, *_pk_index_meta, stats));
611
            // _meta_mem_usage += _pk_index_reader->get_memory_size();
612
49.7k
            return Status::OK();
613
49.7k
        } else {
614
            // read and parse short key index page
615
39.6k
            OlapReaderStatistics tmp_stats;
616
39.6k
            OlapReaderStatistics* stats_ptr = stats != nullptr ? stats : &tmp_stats;
617
39.6k
            PageReadOptions opts(io::IOContext {.is_index_data = true,
618
39.6k
                                                .file_cache_stats = &stats_ptr->file_cache_stats});
619
39.6k
            opts.use_page_cache = true;
620
39.6k
            opts.type = INDEX_PAGE;
621
39.6k
            opts.file_reader = _file_reader.get();
622
39.6k
            opts.page_pointer = PagePointer(_sk_index_page);
623
            // short key index page uses NO_COMPRESSION for now
624
39.6k
            opts.codec = nullptr;
625
39.6k
            opts.stats = &tmp_stats;
626
627
39.6k
            Slice body;
628
39.6k
            PageFooterPB footer;
629
39.6k
            RETURN_IF_ERROR(
630
39.6k
                    PageIO::read_and_decompress_page(opts, &_sk_index_handle, &body, &footer));
631
39.6k
            DCHECK_EQ(footer.type(), SHORT_KEY_PAGE);
632
39.6k
            DCHECK(footer.has_short_key_page_footer());
633
634
            // _meta_mem_usage += body.get_size();
635
39.6k
            _sk_index_decoder = std::make_unique<ShortKeyIndexDecoder>();
636
39.6k
            return _sk_index_decoder->parse(body, footer.short_key_page_footer());
637
39.6k
        }
638
89.4k
    });
639
5.38M
}
640
641
1.52M
Status Segment::healthy_status() {
642
1.52M
    try {
643
1.52M
        if (_load_index_once.has_called()) {
644
1.47M
            RETURN_IF_ERROR(_load_index_once.stored_result());
645
1.47M
        }
646
1.52M
        if (_load_pk_bf_once.has_called()) {
647
851k
            RETURN_IF_ERROR(_load_pk_bf_once.stored_result());
648
851k
        }
649
1.52M
        if (_create_column_meta_once_call.has_called()) {
650
1.47M
            RETURN_IF_ERROR(_create_column_meta_once_call.stored_result());
651
1.47M
        }
652
1.52M
        if (_index_file_reader_open.has_called()) {
653
23.3k
            RETURN_IF_ERROR(_index_file_reader_open.stored_result());
654
23.3k
        }
655
        // This status is set by running time, for example, if there is something wrong during read segment iterator.
656
1.52M
        return _healthy_status.status();
657
1.52M
    } catch (const doris::Exception& e) {
658
        // If there is an exception during load_xxx, should not throw exception directly because
659
        // the caller may not exception safe.
660
0
        return e.to_status();
661
0
    } catch (const std::exception& e) {
662
        // The exception is not thrown by doris code.
663
0
        return Status::InternalError("Unexcepted error during load segment: {}", e.what());
664
0
    }
665
1.52M
}
666
667
// Return the storage datatype of related column to field.
668
DataTypePtr Segment::get_data_type_of(const TabletColumn& column,
669
20.5M
                                      const StorageReadOptions& read_options) {
670
20.5M
    const PathInDataPtr path = column.path_info_ptr();
671
672
    // none variant column
673
20.6M
    if (path == nullptr || path->empty()) {
674
20.6M
        return DataTypeFactory::instance().create_data_type(column);
675
20.6M
    }
676
677
    // Path exists, proceed with variant logic.
678
18.4E
    PathInData relative_path = path->copy_pop_front();
679
18.4E
    int32_t unique_id = column.unique_id() >= 0 ? column.unique_id() : column.parent_unique_id();
680
681
    // If this uid does not exist in segment meta, fallback to schema type.
682
18.4E
    if (!_column_meta_accessor->has_column_uid(unique_id)) {
683
1.12k
        return DataTypeFactory::instance().create_data_type(column);
684
1.12k
    }
685
686
18.4E
    std::shared_ptr<ColumnReader> v_reader;
687
688
    // Get the parent variant column reader
689
18.4E
    OlapReaderStatistics stats;
690
    // If status is not ok, it will throw exception(data corruption)
691
18.4E
    THROW_IF_ERROR(get_column_reader(unique_id, &v_reader, &stats));
692
18.4E
    DCHECK(v_reader != nullptr);
693
18.4E
    auto* variant_reader = static_cast<VariantColumnReader*>(v_reader.get());
694
    // Delegate type inference for variant paths to VariantColumnReader.
695
18.4E
    DataTypePtr type;
696
18.4E
    THROW_IF_ERROR(variant_reader->infer_data_type_for_path(&type, column, read_options,
697
18.4E
                                                            _column_reader_cache.get()));
698
18.4E
    return type;
699
18.4E
}
700
701
38.5M
Status Segment::_create_column_meta_once(OlapReaderStatistics* stats) {
702
38.5M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
703
38.5M
    return _create_column_meta_once_call.call([&] {
704
109k
        std::shared_ptr<SegmentFooterPB> footer_pb_shared;
705
109k
        RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, stats));
706
109k
        return _create_column_meta(*footer_pb_shared);
707
109k
    });
708
38.5M
}
709
710
109k
Status Segment::_create_column_meta(const SegmentFooterPB& footer) {
711
    // Initialize column meta accessor which internally maintains uid -> column_ordinal mapping.
712
109k
    _column_meta_accessor = std::make_unique<ColumnMetaAccessor>();
713
109k
    RETURN_IF_ERROR(_column_meta_accessor->init(footer, _file_reader));
714
715
109k
    if (config::enable_adaptive_batch_size) {
716
        // Cache raw_data_bytes per column uid for adaptive batch size prediction.
717
        // This runs under call_once, so no thread-safety concerns.
718
1.32M
        auto st = _column_meta_accessor->traverse_metas(footer, [this](const ColumnMetaPB& meta) {
719
1.33M
            if (meta.has_unique_id() && meta.unique_id() != -1 && meta.has_raw_data_bytes()) {
720
1.07M
                _column_uid_to_raw_bytes[meta.unique_id()] = meta.raw_data_bytes();
721
1.07M
            }
722
1.32M
        });
723
724
107k
        if (!st.ok()) {
725
0
            LOG(WARNING) << "Failed to traverse column metas to cache raw_data_bytes, error: "
726
0
                         << st.to_string();
727
0
        }
728
107k
    }
729
730
109k
    _column_reader_cache = std::make_unique<ColumnReaderCache>(
731
109k
            _column_meta_accessor.get(), _tablet_schema, _file_reader, _num_rows,
732
3.92M
            [this](std::shared_ptr<SegmentFooterPB>& footer_pb, OlapReaderStatistics* stats) {
733
3.92M
                return _get_segment_footer(footer_pb, stats);
734
3.92M
            });
735
109k
    return Status::OK();
736
109k
}
737
738
Status Segment::new_default_iterator(const TabletColumn& tablet_column,
739
12.3k
                                     std::unique_ptr<ColumnIterator>* iter) {
740
12.3k
    if (!tablet_column.has_default_value() && !tablet_column.is_nullable()) {
741
0
        return Status::InternalError(
742
0
                "invalid nonexistent column without default value. column_uid={}, "
743
0
                "column_name={}, "
744
0
                "column_type={}",
745
0
                tablet_column.unique_id(), tablet_column.name(), tablet_column.type());
746
0
    }
747
12.3k
    std::unique_ptr<DefaultValueColumnIterator> default_value_iter(new DefaultValueColumnIterator(
748
12.3k
            tablet_column.has_default_value(), tablet_column.default_value(),
749
12.3k
            tablet_column.is_nullable(), tablet_column.type(), tablet_column.precision(),
750
12.3k
            tablet_column.frac(), tablet_column.length()));
751
12.3k
    ColumnIteratorOptions iter_opts;
752
753
12.3k
    RETURN_IF_ERROR(default_value_iter->init(iter_opts));
754
12.3k
    *iter = std::move(default_value_iter);
755
12.3k
    return Status::OK();
756
12.3k
}
757
758
// Not use cid anymore, for example original table schema is colA int, then user do following actions
759
// 1.add column b
760
// 2. drop column b
761
// 3. add column c
762
// in the new schema column c's cid == 2
763
// but in the old schema column b's cid == 2
764
// but they are not the same column
765
Status Segment::new_column_iterator(const TabletColumn& tablet_column,
766
                                    std::unique_ptr<ColumnIterator>* iter,
767
                                    const StorageReadOptions* opt,
768
                                    const std::unordered_map<int32_t, PathToBinaryColumnCacheUPtr>*
769
17.8M
                                            variant_sparse_column_cache) {
770
17.8M
    if (opt->runtime_state != nullptr) {
771
17.5M
        _be_exec_version = opt->runtime_state->be_exec_version();
772
17.5M
    }
773
17.8M
    RETURN_IF_ERROR(_create_column_meta_once(opt->stats));
774
775
    // For compability reason unique_id may less than 0 for variant extracted column
776
17.9M
    int32_t unique_id = tablet_column.unique_id() >= 0 ? tablet_column.unique_id()
777
18.4E
                                                       : tablet_column.parent_unique_id();
778
779
    // If column meta for this uid is not found in this segment, use default iterator.
780
17.8M
    if (!_column_meta_accessor->has_column_uid(unique_id)) {
781
3.90k
        RETURN_IF_ERROR(new_default_iterator(tablet_column, iter));
782
3.90k
        return Status::OK();
783
3.90k
    }
784
785
    // init iterator by unique id
786
17.8M
    std::shared_ptr<ColumnReader> reader;
787
17.8M
    RETURN_IF_ERROR(get_column_reader(unique_id, &reader, opt->stats));
788
17.8M
    if (reader == nullptr) {
789
0
        return Status::InternalError("column reader is nullptr, unique_id={}", unique_id);
790
0
    }
791
17.8M
    if (reader->get_meta_type() == FieldType::OLAP_FIELD_TYPE_VARIANT) {
792
        // if sparse_column_cache_ptr is nullptr, means the sparse column cache is not used
793
34.4k
        PathToBinaryColumnCache* sparse_column_cache_ptr = nullptr;
794
34.4k
        if (variant_sparse_column_cache) {
795
33.8k
            auto it = variant_sparse_column_cache->find(unique_id);
796
33.8k
            if (it != variant_sparse_column_cache->end()) {
797
33.8k
                sparse_column_cache_ptr = it->second.get();
798
18.4E
            } else {
799
18.4E
                DCHECK(false) << "sparse column cache is not found, unique_id=" << unique_id;
800
18.4E
            }
801
33.8k
        }
802
        // use _column_reader_cache to get variant subcolumn(path column) reader
803
34.4k
        RETURN_IF_ERROR(assert_cast<VariantColumnReader*>(reader.get())
804
34.4k
                                ->new_iterator(iter, &tablet_column, opt,
805
34.4k
                                               _column_reader_cache.get(),
806
34.4k
                                               sparse_column_cache_ptr));
807
17.8M
    } else {
808
17.8M
        RETURN_IF_ERROR(reader->new_iterator(iter, &tablet_column, opt));
809
17.8M
        if (opt->all_access_paths.contains(unique_id) ||
810
17.8M
            opt->predicate_access_paths.contains(unique_id)) {
811
62.7k
            const auto& all_access_paths = opt->all_access_paths.contains(unique_id)
812
62.7k
                                                   ? opt->all_access_paths.at(unique_id)
813
62.7k
                                                   : TColumnAccessPaths {};
814
62.7k
            const auto& predicate_access_paths = opt->predicate_access_paths.contains(unique_id)
815
62.7k
                                                         ? opt->predicate_access_paths.at(unique_id)
816
62.7k
                                                         : TColumnAccessPaths {};
817
818
            // set column name to apply access paths.
819
62.7k
            (*iter)->set_column_name(tablet_column.name());
820
62.7k
            RETURN_IF_ERROR((*iter)->set_access_paths(all_access_paths, predicate_access_paths));
821
62.7k
            (*iter)->remove_pruned_sub_iterators();
822
62.7k
        }
823
17.8M
    }
824
825
17.9M
    if (config::enable_column_type_check && !tablet_column.has_path_info() &&
826
17.9M
        !tablet_column.is_agg_state_type() && tablet_column.type() != reader->get_meta_type()) {
827
0
        LOG(WARNING) << "different type between schema and column reader,"
828
0
                     << " column schema name: " << tablet_column.name()
829
0
                     << " column schema type: " << int(tablet_column.type())
830
0
                     << " column reader meta type: " << int(reader->get_meta_type());
831
0
        return Status::InternalError("different type between schema and column reader");
832
0
    }
833
17.8M
    return Status::OK();
834
17.8M
}
835
836
Status Segment::get_column_reader(int32_t col_uid, std::shared_ptr<ColumnReader>* column_reader,
837
17.9M
                                  OlapReaderStatistics* stats) {
838
17.9M
    RETURN_IF_ERROR(_create_column_meta_once(stats));
839
17.9M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
840
    // The column is not in this segment, return nullptr
841
17.9M
    if (!_tablet_schema->has_column_unique_id(col_uid)) {
842
0
        *column_reader = nullptr;
843
0
        return Status::Error<ErrorCode::NOT_FOUND, false>("column not found in segment, col_uid={}",
844
0
                                                          col_uid);
845
0
    }
846
17.9M
    return _column_reader_cache->get_column_reader(col_uid, column_reader, stats);
847
17.9M
}
848
849
42.2k
Status Segment::traverse_column_meta_pbs(const std::function<void(const ColumnMetaPB&)>& visitor) {
850
    // Ensure column meta accessor and reader cache are initialized once.
851
42.2k
    OlapReaderStatistics dummy_stats;
852
42.2k
    RETURN_IF_ERROR(_create_column_meta_once(&dummy_stats));
853
42.2k
    std::shared_ptr<SegmentFooterPB> footer_pb_shared;
854
42.2k
    RETURN_IF_ERROR(_get_segment_footer(footer_pb_shared, &dummy_stats));
855
42.2k
    return _column_meta_accessor->traverse_metas(*footer_pb_shared, visitor);
856
42.2k
}
857
858
Status Segment::get_column_reader(const TabletColumn& col,
859
                                  std::shared_ptr<ColumnReader>* column_reader,
860
1.32M
                                  OlapReaderStatistics* stats) {
861
1.32M
    RETURN_IF_ERROR(_create_column_meta_once(stats));
862
1.32M
    SCOPED_RAW_TIMER(&stats->segment_create_column_readers_timer_ns);
863
18.4E
    int col_uid = col.unique_id() >= 0 ? col.unique_id() : col.parent_unique_id();
864
    // The column is not in this segment, return nullptr
865
1.32M
    if (!_tablet_schema->has_column_unique_id(col_uid)) {
866
9
        *column_reader = nullptr;
867
9
        return Status::Error<ErrorCode::NOT_FOUND, false>("column not found in segment, col_uid={}",
868
9
                                                          col_uid);
869
9
    }
870
1.32M
    if (col.has_path_info()) {
871
2.08k
        PathInData relative_path = col.path_info_ptr()->copy_pop_front();
872
2.08k
        return _column_reader_cache->get_path_column_reader(col_uid, relative_path, column_reader,
873
2.08k
                                                            stats);
874
2.08k
    }
875
1.31M
    return _column_reader_cache->get_column_reader(col_uid, column_reader, stats);
876
1.32M
}
877
878
Status Segment::new_index_iterator(const TabletColumn& tablet_column, const TabletIndex* index_meta,
879
                                   const StorageReadOptions& read_options,
880
78.1k
                                   std::unique_ptr<IndexIterator>* iter) {
881
78.1k
    if (read_options.runtime_state != nullptr) {
882
69.1k
        _be_exec_version = read_options.runtime_state->be_exec_version();
883
69.1k
    }
884
78.1k
    RETURN_IF_ERROR(_create_column_meta_once(read_options.stats));
885
78.1k
    std::shared_ptr<ColumnReader> reader;
886
78.1k
    auto st = get_column_reader(tablet_column, &reader, read_options.stats);
887
78.1k
    if (st.is<ErrorCode::NOT_FOUND>()) {
888
541
        return Status::OK();
889
541
    }
890
77.5k
    RETURN_IF_ERROR(st);
891
77.5k
    DCHECK(reader != nullptr);
892
77.6k
    if (index_meta) {
893
        // call DorisCallOnce.call without check if _index_file_reader is nullptr
894
        // to avoid data race during parallel method calls
895
77.6k
        RETURN_IF_ERROR(_index_file_reader_open.call([&] { return _open_index_file_reader(); }));
896
        // after DorisCallOnce.call, _index_file_reader is guaranteed to be not nullptr
897
77.6k
        const std::string rowset_id =
898
77.6k
                index_meta->index_type() == IndexType::ANN ? _rowset_id.to_string() : "";
899
77.6k
        const bool need_binding_diagnostic = tablet_column.is_variant_type() ||
900
77.6k
                                             tablet_column.is_extracted_column() ||
901
77.6k
                                             !index_meta->get_index_suffix().empty();
902
77.6k
        bool index_file_exists = false;
903
77.6k
        Status probe_status;
904
77.6k
        if (need_binding_diagnostic) {
905
1.29k
            probe_status = _index_file_reader->init(config::inverted_index_read_buffer_size,
906
1.29k
                                                    &read_options.io_ctx);
907
1.29k
            if (probe_status.ok()) {
908
1.29k
                probe_status = _index_file_reader->index_file_exist(index_meta, &index_file_exists);
909
1.29k
            }
910
1.29k
            const auto diagnostic = fmt::format(
911
1.29k
                    "[VariantSearchBinding] phase=index_file_probe tablet_id={} rowset_id={} "
912
1.29k
                    "segment_id={} column={} logical_path={} index_id={} suffix={} exists={} "
913
1.29k
                    "status={}",
914
1.29k
                    read_options.tablet_id, _rowset_id.to_string(), _segment_id,
915
1.29k
                    tablet_column.name(),
916
1.29k
                    tablet_column.has_path_info() ? tablet_column.path_info_ptr()->get_path()
917
1.29k
                                                  : tablet_column.name(),
918
1.29k
                    index_meta->index_id(), index_meta->get_index_suffix(), index_file_exists,
919
1.29k
                    probe_status.ok() ? "OK" : probe_status.to_string());
920
18.4E
            VLOG_DEBUG << diagnostic;
921
1.29k
            if (read_options.stats != nullptr) {
922
1.29k
                read_options.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
923
1.29k
            }
924
1.29k
        }
925
77.6k
        Status iter_status = reader->new_index_iterator(_index_file_reader, index_meta, rowset_id,
926
77.6k
                                                        _segment_id, _num_rows, iter);
927
77.6k
        if (!iter_status.ok()) {
928
0
            if (need_binding_diagnostic) {
929
0
                const auto diagnostic = fmt::format(
930
0
                        "[VariantSearchBinding] phase=index_iterator_create result=reject "
931
0
                        "tablet_id={} rowset_id={} segment_id={} column={} logical_path={} "
932
0
                        "index_id={} suffix={} reason={}",
933
0
                        read_options.tablet_id, _rowset_id.to_string(), _segment_id,
934
0
                        tablet_column.name(),
935
0
                        tablet_column.has_path_info() ? tablet_column.path_info_ptr()->get_path()
936
0
                                                      : tablet_column.name(),
937
0
                        index_meta->index_id(), index_meta->get_index_suffix(),
938
0
                        iter_status.to_string());
939
0
                VLOG_DEBUG << diagnostic;
940
0
                if (read_options.stats != nullptr) {
941
0
                    read_options.stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
942
0
                }
943
0
            }
944
0
            return iter_status;
945
0
        }
946
77.6k
        return Status::OK();
947
77.6k
    }
948
18.4E
    return Status::OK();
949
77.5k
}
950
951
Status Segment::lookup_row_key(const Slice& key, const TabletSchema* latest_schema,
952
                               bool with_seq_col, bool with_rowid, RowLocation* row_location,
953
3.95M
                               OlapReaderStatistics* stats, std::string* encoded_seq_value) {
954
3.95M
    RETURN_IF_ERROR(load_pk_index_and_bf(stats));
955
3.95M
    bool has_seq_col = latest_schema->has_sequence_col();
956
3.95M
    bool has_rowid = !latest_schema->cluster_key_uids().empty();
957
3.95M
    size_t seq_col_length = 0;
958
3.95M
    if (has_seq_col) {
959
25.2k
        seq_col_length = latest_schema->column(latest_schema->sequence_col_idx()).length() + 1;
960
25.2k
    }
961
3.95M
    size_t rowid_length = has_rowid ? PrimaryKeyIndexReader::ROW_ID_LENGTH : 0;
962
963
3.95M
    Slice key_without_seq =
964
3.95M
            Slice(key.get_data(), key.get_size() - (with_seq_col ? seq_col_length : 0) -
965
3.95M
                                          (with_rowid ? rowid_length : 0));
966
967
3.95M
    DCHECK(_pk_index_reader != nullptr);
968
3.95M
    if (!_pk_index_reader->check_present(key_without_seq)) {
969
164k
        return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
970
164k
    }
971
3.78M
    bool exact_match = false;
972
3.78M
    std::unique_ptr<segment_v2::IndexedColumnIterator> index_iterator;
973
3.78M
    RETURN_IF_ERROR(_pk_index_reader->new_iterator(&index_iterator, stats));
974
3.78M
    auto st = index_iterator->seek_at_or_after(&key_without_seq, &exact_match);
975
3.78M
    if (!st.ok() && !st.is<ErrorCode::ENTRY_NOT_FOUND>()) {
976
0
        return st;
977
0
    }
978
3.80M
    if (st.is<ErrorCode::ENTRY_NOT_FOUND>() || (!has_seq_col && !has_rowid && !exact_match)) {
979
113
        return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
980
113
    }
981
3.78M
    row_location->row_id = cast_set<uint32_t>(index_iterator->get_current_ordinal());
982
3.78M
    row_location->segment_id = _segment_id;
983
3.78M
    row_location->rowset_id = _rowset_id;
984
985
3.78M
    size_t num_to_read = 1;
986
3.78M
    auto index_type = DataTypeFactory::instance().create_data_type(_pk_index_reader->type(), 1, 0);
987
3.78M
    auto index_column = index_type->create_column();
988
3.78M
    size_t num_read = num_to_read;
989
3.78M
    RETURN_IF_ERROR(index_iterator->next_batch(&num_read, index_column));
990
3.78M
    DCHECK(num_to_read == num_read);
991
992
3.78M
    Slice sought_key = Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
993
994
    // user may use "ALTER TABLE tbl ENABLE FEATURE "SEQUENCE_LOAD" WITH ..." to add a hidden sequence column
995
    // for a merge-on-write table which doesn't have sequence column, so `has_seq_col ==  true` doesn't mean
996
    // data in segment has sequence column value
997
3.78M
    bool segment_has_seq_col = _tablet_schema->has_sequence_col();
998
3.78M
    Slice sought_key_without_seq = Slice(
999
3.78M
            sought_key.get_data(),
1000
3.78M
            sought_key.get_size() - (segment_has_seq_col ? seq_col_length : 0) - rowid_length);
1001
1002
3.78M
    if (has_seq_col) {
1003
        // compare key
1004
25.2k
        if (key_without_seq.compare(sought_key_without_seq) != 0) {
1005
0
            return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1006
0
        }
1007
1008
25.2k
        if (with_seq_col && segment_has_seq_col) {
1009
            // compare sequence id
1010
23.3k
            Slice sequence_id =
1011
23.3k
                    Slice(key.get_data() + key_without_seq.get_size() + 1, seq_col_length - 1);
1012
23.3k
            Slice previous_sequence_id =
1013
23.3k
                    Slice(sought_key.get_data() + sought_key_without_seq.get_size() + 1,
1014
23.3k
                          seq_col_length - 1);
1015
23.3k
            if (sequence_id.compare(previous_sequence_id) < 0) {
1016
343
                return Status::Error<ErrorCode::KEY_ALREADY_EXISTS>(
1017
343
                        "key with higher sequence id exists");
1018
343
            }
1019
23.3k
        }
1020
3.76M
    } else if (has_rowid) {
1021
54.0k
        Slice sought_key_without_rowid =
1022
54.0k
                Slice(sought_key.get_data(), sought_key.get_size() - rowid_length);
1023
        // compare key
1024
54.0k
        if (key_without_seq.compare(sought_key_without_rowid) != 0) {
1025
0
            return Status::Error<ErrorCode::KEY_NOT_FOUND, false>("");
1026
0
        }
1027
54.0k
    }
1028
    // found the key, use rowid in pk index if necessary.
1029
3.78M
    if (has_rowid) {
1030
66.0k
        Slice rowid_slice = Slice(sought_key.get_data() + sought_key_without_seq.get_size() +
1031
66.0k
                                          (segment_has_seq_col ? seq_col_length : 0) + 1,
1032
66.0k
                                  rowid_length - 1);
1033
66.0k
        const auto* rowid_coder = get_key_coder(FieldType::OLAP_FIELD_TYPE_UNSIGNED_INT);
1034
66.0k
        RETURN_IF_ERROR(rowid_coder->decode_ascending(&rowid_slice, rowid_length,
1035
66.0k
                                                      (uint8_t*)&row_location->row_id));
1036
66.0k
    }
1037
1038
3.78M
    if (encoded_seq_value) {
1039
78
        if (!segment_has_seq_col) {
1040
0
            *encoded_seq_value = std::string {};
1041
78
        } else {
1042
            // include marker
1043
78
            *encoded_seq_value =
1044
78
                    Slice(sought_key.get_data() + sought_key_without_seq.get_size(), seq_col_length)
1045
78
                            .to_string();
1046
78
        }
1047
78
    }
1048
3.78M
    return Status::OK();
1049
3.78M
}
1050
1051
0
Status Segment::read_key_by_rowid(uint32_t row_id, std::string* key) {
1052
0
    OlapReaderStatistics* null_stat = nullptr;
1053
0
    RETURN_IF_ERROR(load_pk_index_and_bf(null_stat));
1054
0
    std::unique_ptr<segment_v2::IndexedColumnIterator> iter;
1055
0
    RETURN_IF_ERROR(_pk_index_reader->new_iterator(&iter, null_stat));
1056
1057
0
    auto index_type = DataTypeFactory::instance().create_data_type(_pk_index_reader->type(), 1, 0);
1058
0
    auto index_column = index_type->create_column();
1059
0
    RETURN_IF_ERROR(iter->seek_to_ordinal(row_id));
1060
0
    size_t num_read = 1;
1061
0
    RETURN_IF_ERROR(iter->next_batch(&num_read, index_column));
1062
0
    CHECK(num_read == 1);
1063
    // trim row id
1064
0
    if (_tablet_schema->cluster_key_uids().empty()) {
1065
0
        *key = index_column->get_data_at(0).to_string();
1066
0
    } else {
1067
0
        Slice sought_key =
1068
0
                Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
1069
0
        Slice sought_key_without_rowid =
1070
0
                Slice(sought_key.get_data(),
1071
0
                      sought_key.get_size() - PrimaryKeyIndexReader::ROW_ID_LENGTH);
1072
0
        *key = sought_key_without_rowid.to_string();
1073
0
    }
1074
0
    return Status::OK();
1075
0
}
1076
1077
Status Segment::seek_and_read_by_rowid(const TabletSchema& schema, SlotDescriptor* slot,
1078
                                       const std::vector<uint32_t>& row_ids,
1079
                                       MutableColumnPtr& result,
1080
                                       StorageReadOptions& storage_read_options,
1081
12.1k
                                       std::unique_ptr<ColumnIterator>& iterator_hint) {
1082
12.1k
    if (row_ids.empty()) {
1083
0
        return Status::OK();
1084
0
    }
1085
12.1k
    DORIS_CHECK(std::is_sorted(row_ids.begin(), row_ids.end()));
1086
12.1k
    DORIS_CHECK(std::adjacent_find(row_ids.begin(), row_ids.end()) == row_ids.end());
1087
    // ColumnIterator::seek_and_read expects monotonically increasing row_ids without
1088
    // duplicates for correct ordinal scanning. Enforce this contract at the entry point.
1089
12.1k
    segment_v2::ColumnIteratorOptions opt {
1090
12.1k
            .use_page_cache = !config::disable_storage_page_cache,
1091
12.1k
            .file_reader = file_reader().get(),
1092
12.1k
            .stats = storage_read_options.stats,
1093
12.1k
            .io_ctx = io::IOContext {.reader_type = ReaderType::READER_QUERY,
1094
12.1k
                                     .file_cache_stats =
1095
12.1k
                                             &storage_read_options.stats->file_cache_stats},
1096
12.1k
    };
1097
1098
12.1k
    if (!slot->column_paths().empty()) {
1099
        // here need create column readers to make sure column reader is created before seek_and_read_by_rowid
1100
        // if segment cache miss, column reader will be created to make sure the variant column result not coredump
1101
351
        RETURN_IF_ERROR(_create_column_meta_once(storage_read_options.stats));
1102
1103
351
        const auto& dt_variant =
1104
351
                assert_cast<const DataTypeVariant&>(*remove_nullable(slot->type()));
1105
351
        TabletColumn column = TabletColumn::create_materialized_variant_column(
1106
351
                schema.column_by_uid(slot->col_unique_id()).name_lower_case(), slot->column_paths(),
1107
351
                slot->col_unique_id(), dt_variant.variant_max_subcolumns_count(),
1108
351
                dt_variant.enable_doc_mode());
1109
351
        auto storage_type = get_data_type_of(column, storage_read_options);
1110
351
        MutableColumnPtr file_storage_column = storage_type->create_column();
1111
351
        DCHECK(storage_type != nullptr);
1112
1113
351
        if (iterator_hint == nullptr) {
1114
351
            RETURN_IF_ERROR(new_column_iterator(column, &iterator_hint, &storage_read_options));
1115
351
            RETURN_IF_ERROR(iterator_hint->init(opt));
1116
351
        }
1117
351
        RETURN_IF_ERROR(
1118
351
                iterator_hint->read_by_rowids(row_ids.data(), row_ids.size(), file_storage_column));
1119
351
        ColumnPtr source_ptr;
1120
        // storage may have different type with schema, so we need to cast the column
1121
351
        RETURN_IF_ERROR(variant_util::cast_column(
1122
351
                ColumnWithTypeAndName(file_storage_column->get_ptr(), storage_type, column.name()),
1123
351
                slot->type(), &source_ptr));
1124
351
        RETURN_IF_CATCH_EXCEPTION(result->insert_range_from(*source_ptr, 0, row_ids.size()));
1125
11.8k
    } else {
1126
11.8k
        int index = (slot->col_unique_id() >= 0) ? schema.field_index(slot->col_unique_id())
1127
11.8k
                                                 : schema.field_index(slot->col_name());
1128
11.8k
        if (index < 0) {
1129
0
            std::stringstream ss;
1130
0
            ss << "field name is invalid. field=" << slot->col_name()
1131
0
               << ", field_name_to_index=" << schema.get_all_field_names();
1132
0
            return Status::InternalError(ss.str());
1133
0
        }
1134
11.8k
        if (iterator_hint == nullptr) {
1135
11.8k
            RETURN_IF_ERROR(new_column_iterator(schema.column(index), &iterator_hint,
1136
11.8k
                                                &storage_read_options));
1137
11.8k
            RETURN_IF_ERROR(iterator_hint->init(opt));
1138
11.8k
        }
1139
11.8k
        RETURN_IF_ERROR(iterator_hint->read_by_rowids(row_ids.data(), row_ids.size(), result));
1140
11.8k
    }
1141
12.1k
    return Status::OK();
1142
12.1k
}
1143
1144
Status Segment::_get_segment_footer(std::shared_ptr<SegmentFooterPB>& footer_pb,
1145
4.23M
                                    OlapReaderStatistics* stats) {
1146
4.23M
    std::shared_ptr<SegmentFooterPB> footer_pb_shared = _footer_pb.lock();
1147
4.23M
    if (footer_pb_shared != nullptr) {
1148
4.06M
        footer_pb = footer_pb_shared;
1149
4.06M
        return Status::OK();
1150
4.06M
    }
1151
1152
18.4E
    VLOG_DEBUG << fmt::format("Segment footer of {}:{}:{} is missing, try to load it",
1153
18.4E
                              _file_reader->path().native(), _file_reader->size(),
1154
18.4E
                              _file_reader->size() - 12);
1155
1156
170k
    StoragePageCache* segment_footer_cache = ExecEnv::GetInstance()->get_storage_page_cache();
1157
170k
    DCHECK(segment_footer_cache != nullptr);
1158
1159
170k
    auto cache_key = get_segment_footer_cache_key();
1160
1161
170k
    PageCacheHandle cache_handle;
1162
1163
    // Put segment footer into index page cache.
1164
    // Rationale:
1165
    // - Footer is metadata (small, parsed with indexes), not data page payload.
1166
    // - Using PageTypePB::INDEX_PAGE keeps it under the same eviction policy/shards
1167
    //   as other index/metadata pages and avoids competing with DATA_PAGE budget.
1168
170k
    if (!segment_footer_cache->lookup(cache_key, &cache_handle,
1169
170k
                                      segment_v2::PageTypePB::INDEX_PAGE)) {
1170
69.0k
        RETURN_IF_ERROR(_parse_footer(footer_pb_shared, stats));
1171
69.0k
        segment_footer_cache->insert(cache_key, footer_pb_shared, footer_pb_shared->ByteSizeLong(),
1172
69.0k
                                     &cache_handle, segment_v2::PageTypePB::INDEX_PAGE);
1173
101k
    } else {
1174
18.4E
        VLOG_DEBUG << fmt::format("Segment footer of {}:{}:{} is found in cache",
1175
18.4E
                                  _file_reader->path().native(), _file_reader->size(),
1176
18.4E
                                  _file_reader->size() - 12);
1177
101k
    }
1178
170k
    footer_pb_shared = cache_handle.get<std::shared_ptr<SegmentFooterPB>>();
1179
170k
    _footer_pb = footer_pb_shared;
1180
170k
    footer_pb = footer_pb_shared;
1181
170k
    return Status::OK();
1182
170k
}
1183
1184
178k
StoragePageCache::CacheKey Segment::get_segment_footer_cache_key() const {
1185
178k
    DCHECK(_file_reader != nullptr);
1186
    // The footer is always at the end of the segment file.
1187
    // The size of footer is 12.
1188
    // So we use the size of file minus 12 as the cache key, which is unique for each segment file.
1189
178k
    return get_segment_footer_cache_key(_file_reader);
1190
178k
}
1191
1192
StoragePageCache::CacheKey Segment::get_segment_footer_cache_key(
1193
178k
        const io::FileReaderSPtr& file_reader) {
1194
178k
    return {file_reader->path().native(), file_reader->size(),
1195
178k
            static_cast<int64_t>(file_reader->size() - 12)};
1196
178k
}
1197
1198
} // namespace doris::segment_v2