Coverage Report

Created: 2026-03-12 16:03

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/olap_define.h"
35
#include "storage/segment/column_writer.h"
36
#include "storage/tablet/tablet.h"
37
#include "storage/tablet/tablet_schema.h"
38
#include "util/faststring.h"
39
#include "util/slice.h"
40
41
namespace doris {
42
class Block;
43
class IOlapColumnDataAccessor;
44
class OlapBlockDataConvertor;
45
46
// TODO(lingbin): Should be a conf that can be dynamically adjusted, or a member in the context
47
const uint32_t MAX_SEGMENT_SIZE = static_cast<uint32_t>(OLAP_MAX_COLUMN_SEGMENT_FILE_SIZE *
48
                                                        OLAP_COLUMN_FILE_SEGMENT_SIZE_SCALE);
49
class DataDir;
50
class MemTracker;
51
class ShortKeyIndexBuilder;
52
class PrimaryKeyIndexBuilder;
53
class KeyCoder;
54
struct RowsetWriterContext;
55
56
namespace io {
57
class FileWriter;
58
} // namespace io
59
60
namespace segment_v2 {
61
62
extern const char* k_segment_magic;
63
extern const uint32_t k_segment_magic_length;
64
65
class VariantStatsCaculator;
66
67
struct SegmentWriterOptions {
68
    uint32_t num_rows_per_block = 1024;
69
    uint32_t max_rows_per_segment = UINT32_MAX;
70
    bool enable_unique_key_merge_on_write = false;
71
    CompressionTypePB compression_type = UNKNOWN_COMPRESSION;
72
73
    RowsetWriterContext* rowset_ctx = nullptr;
74
    DataWriteType write_type = DataWriteType::TYPE_DEFAULT;
75
    std::shared_ptr<MowContext> mow_ctx;
76
};
77
78
using TabletSharedPtr = std::shared_ptr<Tablet>;
79
80
class SegmentWriter {
81
public:
82
    explicit SegmentWriter(io::FileWriter* file_writer, uint32_t segment_id,
83
                           TabletSchemaSPtr tablet_schema, BaseTabletSPtr tablet, DataDir* data_dir,
84
                           const SegmentWriterOptions& opts, IndexFileWriter* inverted_file_writer);
85
    ~SegmentWriter();
86
87
    Status init();
88
89
    // for vertical compaction
90
    Status init(const std::vector<uint32_t>& col_ids, bool has_key);
91
92
    Status append_row(const RowCursor& row);
93
94
    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
45.7k
    uint32_t num_rows_written() const { return _num_rows_written; }
112
113
    // for partial update
114
5.35k
    int64_t num_rows_updated() const { return _num_rows_updated; }
115
5.35k
    int64_t num_rows_deleted() const { return _num_rows_deleted; }
116
5.35k
    int64_t num_rows_new_added() const { return _num_rows_new_added; }
117
5.35k
    int64_t num_rows_filtered() const { return _num_rows_filtered; }
118
119
50.5k
    uint32_t row_count() const { return _row_count; }
120
121
    Status finalize(uint64_t* segment_file_size, uint64_t* index_size);
122
123
5.36k
    uint32_t get_segment_id() const { return _segment_id; }
124
125
    Status finalize_columns_data();
126
    Status finalize_columns_index(uint64_t* index_size);
127
    Status finalize_footer(uint64_t* segment_file_size);
128
129
    void init_column_meta(ColumnMetaPB* meta, uint32_t column_id, const TabletColumn& column,
130
                          TabletSchemaSPtr tablet_schema);
131
    Slice min_encoded_key();
132
    Slice max_encoded_key();
133
134
0
    bool is_unique_key() { return _tablet_schema->keys_type() == UNIQUE_KEYS; }
135
136
    void clear();
137
138
    void set_mow_context(std::shared_ptr<MowContext> mow_context);
139
140
5.36k
    Status close_inverted_index(int64_t* inverted_index_file_size) {
141
        // no inverted index
142
5.36k
        if (_index_file_writer == nullptr) {
143
4.85k
            *inverted_index_file_size = 0;
144
4.85k
            return Status::OK();
145
4.85k
        }
146
505
        RETURN_IF_ERROR(_index_file_writer->begin_close());
147
505
        *inverted_index_file_size = _index_file_writer->get_index_file_total_size();
148
505
        return Status::OK();
149
505
    }
150
151
6
    uint64_t primary_keys_size() const { return _primary_keys_size; }
152
153
private:
154
    DISALLOW_COPY_AND_ASSIGN(SegmentWriter);
155
    Status _create_column_writer(uint32_t cid, const TabletColumn& column,
156
                                 const TabletSchemaSPtr& schema);
157
    Status _create_writers(const TabletSchemaSPtr& tablet_schema,
158
                           const std::vector<uint32_t>& col_ids);
159
    Status _write_data();
160
    Status _write_ordinal_index();
161
    Status _write_zone_map();
162
    Status _write_inverted_index();
163
    Status _write_ann_index();
164
    Status _write_bloom_filter_index();
165
    Status _write_short_key_index();
166
    Status _write_primary_key_index();
167
    Status _write_footer();
168
    Status _write_raw_data(const std::vector<Slice>& slices);
169
    void _maybe_invalid_row_cache(const std::string& key);
170
    std::string _encode_keys(const std::vector<IOlapColumnDataAccessor*>& key_columns, size_t pos);
171
    // used for unique-key with merge on write and segment min_max key
172
    std::string _full_encode_keys(const std::vector<IOlapColumnDataAccessor*>& key_columns,
173
                                  size_t pos, bool null_first = true);
174
175
    static std::string _full_encode_keys(const std::vector<const KeyCoder*>& key_coders,
176
                                         const std::vector<IOlapColumnDataAccessor*>& key_columns,
177
                                         size_t pos, bool null_first = true);
178
179
    // used for unique-key with merge on write
180
    void _encode_seq_column(const IOlapColumnDataAccessor* seq_column, size_t pos,
181
                            std::string* encoded_keys);
182
    void _encode_rowid(const uint32_t rowid, std::string* encoded_keys);
183
    void set_min_max_key(const Slice& key);
184
    void set_min_key(const Slice& key);
185
    void set_max_key(const Slice& key);
186
    void _serialize_block_to_row_column(const Block& block);
187
    Status _generate_primary_key_index(
188
            const std::vector<const KeyCoder*>& primary_key_coders,
189
            const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
190
            IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort);
191
    Status _generate_short_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
192
                                     size_t num_rows, const std::vector<size_t>& short_key_pos);
193
    bool _is_mow();
194
    bool _is_mow_with_cluster_key();
195
196
private:
197
    uint32_t _segment_id;
198
    TabletSchemaSPtr _tablet_schema;
199
    BaseTabletSPtr _tablet;
200
    DataDir* _data_dir = nullptr;
201
    SegmentWriterOptions _opts;
202
203
    // Not owned. owned by RowsetWriter or SegmentFlusher
204
    io::FileWriter* _file_writer = nullptr;
205
    // Not owned. owned by RowsetWriter or SegmentFlusher
206
    IndexFileWriter* _index_file_writer = nullptr;
207
208
    SegmentFooterPB _footer;
209
    // for mow tables with cluster key, the sort key is the cluster keys not unique keys
210
    // for other tables, the sort key is the keys
211
    size_t _num_sort_key_columns;
212
    size_t _num_short_key_columns;
213
214
    std::unique_ptr<ShortKeyIndexBuilder> _short_key_index_builder;
215
    std::unique_ptr<PrimaryKeyIndexBuilder> _primary_key_index_builder;
216
    std::vector<std::unique_ptr<ColumnWriter>> _column_writers;
217
    std::unique_ptr<MemTracker> _mem_tracker;
218
219
    std::unique_ptr<OlapBlockDataConvertor> _olap_data_convertor;
220
    // used for building short key index or primary key index during vectorized write.
221
    // for mow table with cluster keys, this is cluster keys
222
    std::vector<const KeyCoder*> _key_coders;
223
    // for mow table with cluster keys, this is primary keys
224
    std::vector<const KeyCoder*> _primary_key_coders;
225
    const KeyCoder* _seq_coder = nullptr;
226
    const KeyCoder* _rowid_coder = nullptr;
227
    std::vector<uint16_t> _key_index_size;
228
    size_t _short_key_row_pos = 0;
229
230
    std::vector<uint32_t> _column_ids;
231
    bool _has_key = true;
232
    // _num_rows_written means row count already written in this current column group
233
    uint32_t _num_rows_written = 0;
234
235
    /** for partial update stats **/
236
    int64_t _num_rows_updated = 0;
237
    int64_t _num_rows_new_added = 0;
238
    int64_t _num_rows_deleted = 0;
239
    // number of rows filtered in strict mode partial update
240
    int64_t _num_rows_filtered = 0;
241
    // _row_count means total row count of this segment
242
    // In vertical compaction row count is recorded when key columns group finish
243
    //  and _num_rows_written will be updated in value column group
244
    uint32_t _row_count = 0;
245
246
    bool _is_first_row = true;
247
    faststring _min_key;
248
    faststring _max_key;
249
250
    std::shared_ptr<MowContext> _mow_context;
251
    // group every rowset-segment row id to speed up reader
252
    std::map<RowsetId, RowsetSharedPtr> _rsid_to_rowset;
253
    std::vector<std::string> _primary_keys;
254
    uint64_t _primary_keys_size = 0;
255
    // variant statistics calculator for efficient stats collection
256
    std::unique_ptr<VariantStatsCaculator> _variant_stats_calculator;
257
};
258
259
} // namespace segment_v2
260
} // namespace doris