Coverage Report

Created: 2026-06-14 07:02

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