Coverage Report

Created: 2026-07-27 20:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/segment_writer.h
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
#pragma once
19
20
#include <butil/macros.h>
21
#include <gen_cpp/olap_file.pb.h>
22
#include <gen_cpp/segment_v2.pb.h>
23
#include <stddef.h>
24
25
#include <cstdint>
26
#include <functional>
27
#include <map>
28
#include <memory> // unique_ptr
29
#include <string>
30
#include <vector>
31
32
#include "common/status.h" // Status
33
#include "storage/index/index_file_writer.h"
34
#include "storage/key/row_key_encoder.h"
35
#include "storage/olap_define.h"
36
#include "storage/segment/column_writer.h"
37
#include "storage/segment/segment_index_file_cache_loader.h"
38
#include "storage/tablet/tablet.h"
39
#include "storage/tablet/tablet_schema.h"
40
#include "util/faststring.h"
41
#include "util/slice.h"
42
43
namespace doris {
44
class Block;
45
class IOlapColumnDataAccessor;
46
class OlapBlockDataConvertor;
47
48
// TODO(lingbin): Should be a conf that can be dynamically adjusted, or a member in the context
49
const uint32_t MAX_SEGMENT_SIZE = static_cast<uint32_t>(OLAP_MAX_COLUMN_SEGMENT_FILE_SIZE *
50
                                                        OLAP_COLUMN_FILE_SEGMENT_SIZE_SCALE);
51
class DataDir;
52
class MemTracker;
53
class ShortKeyIndexBuilder;
54
class PrimaryKeyIndexBuilder;
55
class KeyCoder;
56
struct RowsetWriterContext;
57
58
namespace io {
59
class FileWriter;
60
} // namespace io
61
62
namespace segment_v2 {
63
64
extern const char* k_segment_magic;
65
extern const uint32_t k_segment_magic_length;
66
67
class VariantStatsCaculator;
68
69
struct SegmentWriterOptions {
70
    uint32_t num_rows_per_block = 1024;
71
    uint32_t max_rows_per_segment = UINT32_MAX;
72
    bool enable_unique_key_merge_on_write = false;
73
    CompressionTypePB compression_type = UNKNOWN_COMPRESSION;
74
75
    RowsetWriterContext* rowset_ctx = nullptr;
76
    DataWriteType write_type = DataWriteType::TYPE_DEFAULT;
77
    std::shared_ptr<MowContext> mow_ctx;
78
};
79
80
using TabletSharedPtr = std::shared_ptr<Tablet>;
81
82
class SegmentWriter {
83
public:
84
    explicit SegmentWriter(io::FileWriter* file_writer, uint32_t segment_id,
85
                           TabletSchemaSPtr tablet_schema, BaseTabletSPtr tablet, DataDir* data_dir,
86
                           const SegmentWriterOptions& opts, IndexFileWriter* inverted_file_writer);
87
    virtual ~SegmentWriter();
88
89
    virtual Status init();
90
91
    // for vertical compaction
92
    virtual Status init(const std::vector<uint32_t>& col_ids, bool has_key);
93
94
    virtual Status append_block(const Block* block, size_t row_pos, size_t num_rows);
95
    Status probe_key_for_mow(std::string key, std::size_t segment_pos, bool have_input_seq_column,
96
                             bool have_delete_sign,
97
                             const std::vector<RowsetSharedPtr>& specified_rowsets,
98
                             std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
99
                             bool& has_default_or_nullable,
100
                             std::vector<bool>& use_default_or_null_flag,
101
                             const std::function<void(const RowLocation& loc)>& found_cb,
102
                             const std::function<Status()>& not_found_cb,
103
                             PartialUpdateStats& stats);
104
    Status partial_update_preconditions_check(size_t row_pos);
105
    Status append_block_with_partial_content(const Block* block, size_t row_pos, size_t num_rows);
106
107
    int64_t max_row_to_add(size_t row_avg_size_in_bytes);
108
109
    uint64_t estimate_segment_size();
110
111
6.66k
    uint32_t num_rows_written() const { return _num_rows_written; }
112
113
    // for partial update
114
2.56k
    int64_t num_rows_updated() const { return _num_rows_updated; }
115
2.56k
    int64_t num_rows_deleted() const { return _num_rows_deleted; }
116
2.56k
    int64_t num_rows_new_added() const { return _num_rows_new_added; }
117
2.56k
    int64_t num_rows_filtered() const { return _num_rows_filtered; }
118
119
6.72k
    uint32_t row_count() const { return _row_count; }
120
121
    Status finalize(uint64_t* segment_file_size, uint64_t* index_size,
122
                    SegmentIndexFileCacheInfo* index_file_cache_info = nullptr);
123
124
4.99k
    uint32_t get_segment_id() const { return _segment_id; }
125
126
    Status finalize_columns_data();
127
    Status finalize_columns_index(uint64_t* index_size);
128
    Status finalize_footer(uint64_t* segment_file_size,
129
                           SegmentIndexFileCacheInfo* index_file_cache_info = nullptr);
130
131
    void init_column_meta(ColumnMetaPB* meta, uint32_t column_id, const TabletColumn& column,
132
                          const ColumnWriterOptions& opts);
133
    Slice min_encoded_key();
134
    Slice max_encoded_key();
135
136
0
    bool is_unique_key() { return _tablet_schema->keys_type() == UNIQUE_KEYS; }
137
138
    void clear();
139
140
2.59k
    Status close_inverted_index(int64_t* inverted_index_file_size) {
141
        // no inverted index
142
2.59k
        if (_index_file_writer == nullptr) {
143
2.03k
            *inverted_index_file_size = 0;
144
2.03k
            return Status::OK();
145
2.03k
        }
146
558
        RETURN_IF_ERROR(_index_file_writer->begin_close());
147
558
        *inverted_index_file_size = _index_file_writer->get_index_file_total_size();
148
558
        return Status::OK();
149
558
    }
150
151
0
    uint64_t primary_keys_size() const { return _primary_keys_size; }
152
153
private:
154
    friend class TestSegmentWriter;
155
    DISALLOW_COPY_AND_ASSIGN(SegmentWriter);
156
    Status _create_column_writer(uint32_t cid, const TabletColumn& column,
157
                                 const TabletSchemaSPtr& schema);
158
    Status _create_writers(const TabletSchemaSPtr& tablet_schema,
159
                           const std::vector<uint32_t>& col_ids);
160
    Status _write_data();
161
    Status _write_ordinal_index();
162
    Status _write_zone_map();
163
    Status _write_inverted_index();
164
    Status _write_ann_index();
165
    Status _write_bloom_filter_index();
166
    Status _write_short_key_index();
167
    Status _write_primary_key_index();
168
    Status _write_footer();
169
    Status _write_raw_data(const std::vector<Slice>& slices);
170
    void _maybe_invalid_row_cache(const std::string& key);
171
    void set_min_max_key(const Slice& key);
172
    void set_min_key(const Slice& key);
173
    void set_max_key(const Slice& key);
174
    void _serialize_block_to_row_column(Block& block);
175
    Status _generate_primary_key_index(
176
            const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
177
            IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort);
178
    Status _generate_short_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
179
                                     size_t num_rows, const std::vector<size_t>& short_key_pos);
180
658k
    bool _is_mow() {
181
658k
        return _tablet_schema->keys_type() == UNIQUE_KEYS && _opts.enable_unique_key_merge_on_write;
182
658k
    }
183
324k
    bool _is_mow_with_cluster_key() {
184
324k
        return _is_mow() && !_tablet_schema->cluster_key_uids().empty();
185
324k
    }
186
187
protected:
188
    // Build key index for derived writers that override append_block.
189
    Status build_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
190
                           IOlapColumnDataAccessor* seq_column, size_t num_rows);
191
192
    uint32_t _segment_id;
193
    TabletSchemaSPtr _tablet_schema;
194
    BaseTabletSPtr _tablet;
195
    DataDir* _data_dir = nullptr;
196
    SegmentWriterOptions _opts;
197
198
    // Not owned. owned by RowsetWriter or SegmentFlusher
199
    io::FileWriter* _file_writer = nullptr;
200
    // Not owned. owned by RowsetWriter or SegmentFlusher
201
    IndexFileWriter* _index_file_writer = nullptr;
202
203
    SegmentFooterPB _footer;
204
    SegmentIndexFileCacheInfo _index_file_cache_info;
205
    size_t _num_short_key_columns;
206
207
    std::unique_ptr<ShortKeyIndexBuilder> _short_key_index_builder;
208
    std::unique_ptr<PrimaryKeyIndexBuilder> _primary_key_index_builder;
209
    std::vector<std::unique_ptr<ColumnWriter>> _column_writers;
210
    std::unique_ptr<MemTracker> _mem_tracker;
211
212
    std::unique_ptr<OlapBlockDataConvertor> _olap_data_convertor;
213
    // used for building short key index or primary key index during vectorized write.
214
    // NOTE: must stay declared after _tablet_schema and _opts, the constructor
215
    // init list reads both through _is_mow().
216
    RowKeyEncoder _key_encoder;
217
    size_t _short_key_row_pos = 0;
218
219
    std::vector<uint32_t> _column_ids;
220
    bool _has_key = true;
221
    // _num_rows_written means row count already written in this current column group
222
    uint32_t _num_rows_written = 0;
223
224
    /** for partial update stats **/
225
    int64_t _num_rows_updated = 0;
226
    int64_t _num_rows_new_added = 0;
227
    int64_t _num_rows_deleted = 0;
228
    // number of rows filtered in strict mode partial update
229
    int64_t _num_rows_filtered = 0;
230
    // _row_count means total row count of this segment
231
    // In vertical compaction row count is recorded when key columns group finish
232
    //  and _num_rows_written will be updated in value column group
233
    uint32_t _row_count = 0;
234
235
    bool _is_first_row = true;
236
    faststring _min_key;
237
    faststring _max_key;
238
239
    std::shared_ptr<MowContext> _mow_context;
240
    // group every rowset-segment row id to speed up reader
241
    std::map<RowsetId, RowsetSharedPtr> _rsid_to_rowset;
242
    std::vector<std::string> _primary_keys;
243
    uint64_t _primary_keys_size = 0;
244
    // variant statistics calculator for efficient stats collection
245
    std::unique_ptr<VariantStatsCaculator> _variant_stats_calculator;
246
};
247
248
} // namespace segment_v2
249
} // namespace doris