Coverage Report

Created: 2026-06-25 13:24

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