Coverage Report

Created: 2026-08-03 06:48

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