Coverage Report

Created: 2026-07-01 06:56

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