Coverage Report

Created: 2026-09-02 00:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/rowset/rowset_writer_context.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 <gen_cpp/olap_file.pb.h>
21
#include <glog/logging.h>
22
23
#include <functional>
24
#include <memory>
25
#include <mutex>
26
#include <optional>
27
#include <string_view>
28
#include <unordered_map>
29
#include <vector>
30
31
#include "cloud/config.h"
32
#include "common/status.h"
33
#include "io/fs/encrypted_fs_factory.h"
34
#include "io/fs/file_system.h"
35
#include "io/fs/file_writer.h"
36
#include "io/fs/local_file_system.h"
37
#include "io/fs/packed_file_system.h"
38
#include "runtime/exec_env.h"
39
#include "storage/binlog.h"
40
#include "storage/olap_define.h"
41
#include "storage/partial_update_info.h"
42
#include "storage/segment/historical_row_retriever.h"
43
#include "storage/storage_policy.h"
44
#include "storage/tablet/tablet.h"
45
#include "storage/tablet/tablet_schema.h"
46
47
namespace doris {
48
49
class RowsetWriterContextBuilder;
50
using RowsetWriterContextBuilderSharedPtr = std::shared_ptr<RowsetWriterContextBuilder>;
51
class DataDir;
52
class Tablet;
53
class FileWriterCreator;
54
class SegmentCollector;
55
56
namespace segment_v2 {
57
struct HistoricalRowRetrieverContext;
58
}
59
60
struct RowsetWriterContext {
61
3.06k
    RowsetWriterContext() : schema_lock(new std::mutex) {
62
3.06k
        load_id.set_hi(0);
63
3.06k
        load_id.set_lo(0);
64
3.06k
    }
65
66
    RowsetId rowset_id;
67
    int64_t db_id {0};
68
    int64_t table_id {0};
69
    int64_t tablet_id {0};
70
    int32_t tablet_schema_hash {0};
71
    int64_t index_id {0};
72
    int64_t partition_id {0};
73
    RowsetTypePB rowset_type {BETA_ROWSET};
74
75
    TabletSchemaSPtr tablet_schema;
76
    // Immutable inverted-index file format inherited from the owner tablet.
77
    std::optional<InvertedIndexStorageFormatPB> inverted_index_storage_format;
78
    // Whether the owner tablet persists the format in its top-level metadata.
79
    // This is derived from TabletMeta and keeps rowset metadata consistent with it.
80
    bool persist_inverted_index_storage_format = false;
81
    // PREPARED/COMMITTED for pending rowset
82
    // VISIBLE for non-pending rowset
83
    RowsetStatePB rowset_state {PREPARED};
84
    // properties for non-pending rowset
85
    Version version {0, 0};
86
87
    // properties for pending rowset
88
    int64_t txn_id {0};
89
    int64_t txn_expiration {0}; // For cloud mode
90
    PUniqueId load_id;
91
    TabletUid tablet_uid {0, 0};
92
    // indicate whether the data among segments is overlapping.
93
    // default is OVERLAP_UNKNOWN.
94
    SegmentsOverlapPB segments_overlap {OVERLAP_UNKNOWN};
95
    // segment file use uint32 to represent row number, therefore the maximum is UINT32_MAX.
96
    // the default is set to INT32_MAX to avoid overflow issue when casting from uint32_t to int.
97
    // test cases can change this value to control flush timing
98
    uint32_t max_rows_per_segment = INT32_MAX;
99
    // not owned, point to the data dir of this rowset
100
    // for checking disk capacity when write data to disk.
101
    // ATTN: not support for RowsetConvertor.
102
    // (because it hard to refactor, and RowsetConvertor will be deprecated in future)
103
    DataDir* data_dir = nullptr;
104
105
    int64_t newest_write_timestamp = -1;
106
    bool enable_unique_key_merge_on_write = false;
107
    // store column_unique_id to do index compaction
108
    std::set<int32_t> columns_to_do_index_compaction;
109
    // SNII only: (column_unique_id, index_id) pairs whose postings are produced
110
    // by index compaction. The segment writer raw-builds every OTHER SNII index
111
    // of the column, so one eligible and one new index on the same column can
112
    // coexist in a single pass. V2/V3 keep columns_to_do_index_compaction:
113
    // their per-column CLucene directories cannot split an index off a column.
114
    std::set<std::pair<int32_t, int64_t>> snii_indexes_to_do_compaction;
115
    DataWriteType write_type = DataWriteType::TYPE_DEFAULT;
116
    // need to figure out the sub type of compaction
117
    ReaderType compaction_type = ReaderType::UNKNOWN;
118
    BaseTabletSPtr tablet = nullptr;
119
120
    std::shared_ptr<MowContext> mow_context;
121
    std::shared_ptr<FileWriterCreator> file_writer_creator;
122
    std::shared_ptr<SegmentCollector> segment_collector;
123
124
    // memtable_on_sink_support_index_v2 = true, we will create SinkFileWriter to send inverted index file
125
    bool memtable_on_sink_support_index_v2 = false;
126
127
    /// begin file cache opts
128
    bool write_file_cache = false;
129
    bool is_hot_data = false;
130
    uint64_t file_cache_ttl_sec = 0;
131
    uint64_t approximate_bytes_to_write = 0;
132
    // If true, compaction output only writes index files to file cache, not data files
133
    bool compaction_output_write_index_only = false;
134
    /// end file cache opts
135
136
    // segcompaction for this RowsetWriter, only enabled when importing data
137
    bool enable_segcompaction = false;
138
139
    std::shared_ptr<PartialUpdateInfo> partial_update_info;
140
141
    bool is_transient_rowset_writer = false;
142
143
    segment_v2::HistoricalRowRetrieverContext make_historical_row_retriever_context();
144
145
    // Intent flag: caller can actively turn merge-file feature on/off for this rowset.
146
    // This describes whether we *want* to try small-file merging.
147
    bool allow_packed_file = true;
148
149
    // Physical id of the first segment in this rowset. It can be nonzero for writers that
150
    // allocate segment ids from a configured range.
151
    int64_t first_segment_id = 0;
152
153
    // Effective flag: whether this context actually ends up using MergeFileSystem for writes.
154
    // This is decided inside fs() based on enable_merge_file plus other conditions
155
    // (cloud mode, S3 filesystem, V1 inverted index, global config, etc.), and once
156
    // set to true it remains stable even if config::enable_merge_file changes later.
157
    mutable bool packed_file_active = false;
158
159
    // Cached FileSystem instance to ensure consistency across multiple fs() calls.
160
    // This prevents creating multiple MergeFileSystem instances and ensures
161
    // packed_file_active flag remains consistent.
162
    mutable io::FileSystemSPtr _cached_fs = nullptr;
163
164
2
    void set_first_segment_id(int64_t segment_id) {
165
2
        DORIS_CHECK_GE(segment_id, 0);
166
2
        DORIS_CHECK(_cached_fs == nullptr);
167
2
        first_segment_id = segment_id;
168
2
    }
169
170
    // For collect segment statistics for compaction
171
    std::vector<RowsetReaderSharedPtr> input_rs_readers;
172
173
    // TODO(lihangyu) remove this lock
174
    // In semi-structure senario tablet_schema will be updated concurrently,
175
    // this lock need to be held when update.Use shared_ptr to avoid delete copy contructor
176
    std::shared_ptr<std::mutex> schema_lock;
177
178
    int64_t compaction_level = 0;
179
180
    // For local rowset
181
    std::string tablet_path;
182
183
    // For remote rowset
184
    std::optional<StorageResource> storage_resource;
185
186
    std::optional<EncryptionAlgorithmPB> encrypt_algorithm;
187
188
    std::string job_id;
189
190
    // Per-segment LSNs allocated before memtable flush. The same storage feeds
191
    // both the base row LSN column and row-binlog LSN column.
192
    std::shared_ptr<segment_v2::SegmentAllocatedLsnMap> allocated_lsn_map = nullptr;
193
    bool _need_allocate_lsn = false;
194
195
    void insert_segment_allocated_lsns(int64_t segment_id,
196
81
                                       ConstAllocatedLsnVectorSharedPtr allocated_lsns) {
197
81
        DCHECK(allocated_lsn_map != nullptr);
198
81
        allocated_lsn_map->insert_segment_allocated_lsns(segment_id, std::move(allocated_lsns));
199
81
    }
200
201
66
    void remove_segment_allocated_lsns(int64_t segment_id) {
202
66
        DCHECK(allocated_lsn_map != nullptr);
203
66
        allocated_lsn_map->remove_segment(segment_id);
204
66
    }
205
206
67
    ConstAllocatedLsnVectorSharedPtr get_segment_allocated_lsns(int64_t segment_id) const {
207
67
        DCHECK(allocated_lsn_map != nullptr);
208
67
        return allocated_lsn_map->get_segment_allocated_lsns(segment_id);
209
67
    }
210
211
42
    bool need_allocated_lsn() const { return _need_allocate_lsn; }
212
213
8.57k
    bool is_local_rowset() const { return !storage_resource; }
214
215
7.06k
    std::string segment_path(int seg_id) const {
216
7.06k
        if (is_local_rowset()) {
217
7.02k
            return local_segment_path(tablet_path, rowset_id.to_string(), seg_id);
218
7.02k
        } else {
219
32
            return storage_resource->remote_segment_path(tablet_id, rowset_id.to_string(), seg_id);
220
32
        }
221
7.06k
    }
222
223
4.13k
    io::FileSystemSPtr fs() const {
224
        // Return cached instance if available to ensure consistency across multiple calls
225
4.13k
        if (_cached_fs != nullptr) {
226
3.17k
            return _cached_fs;
227
3.17k
        }
228
229
965
        auto fs = [this]() -> io::FileSystemSPtr {
230
965
            if (is_local_rowset()) {
231
960
                return io::global_local_filesystem();
232
960
            } else {
233
5
                return storage_resource->fs;
234
5
            }
235
965
        }();
236
237
965
        bool is_s3_fs = fs->type() == io::FileSystemType::S3;
238
239
965
        auto algorithm = encrypt_algorithm;
240
241
965
        if (!algorithm.has_value()) {
242
#ifndef BE_TEST
243
            constexpr std::string_view msg =
244
                    "RowsetWriterContext::determine_encryption is not called when creating this "
245
                    "RowsetWriterContext, it will result in encrypted rowsets left unencrypted";
246
            auto st = Status::InternalError(msg);
247
248
            LOG(WARNING) << st;
249
            DCHECK(false) << st;
250
#else
251
843
            algorithm = EncryptionAlgorithmPB::PLAINTEXT;
252
843
#endif
253
843
        }
254
255
        // Apply packed file system first for write path if enabled
256
        // Create empty index_map for write path
257
        // Index information will be populated after write completes
258
965
        bool has_v1_inverted_index = tablet_schema != nullptr &&
259
965
                                     tablet_schema->has_inverted_index() &&
260
965
                                     tablet_schema->get_inverted_index_storage_format() ==
261
208
                                             InvertedIndexStorageFormatPB::V1;
262
263
965
        if (has_v1_inverted_index && allow_packed_file && config::enable_packed_file) {
264
8
            static constexpr std::string_view kMsg =
265
8
                    "Disable packed file for V1 inverted index tablet to avoid missing index "
266
8
                    "metadata (temporary workaround)";
267
8
            LOG(INFO) << kMsg << ", tablet_id=" << tablet_id << ", rowset_id=" << rowset_id;
268
8
        }
269
270
        // Only enable merge file for S3 file system, not for HDFS or other remote file systems
271
965
        packed_file_active = allow_packed_file && config::is_cloud_mode() &&
272
965
                             config::enable_packed_file && !has_v1_inverted_index && is_s3_fs;
273
274
965
        if (packed_file_active) {
275
0
            io::PackedAppendContext append_info;
276
0
            append_info.tablet_id = tablet_id;
277
0
            append_info.rowset_id = rowset_id.to_string();
278
0
            append_info.first_segment_id = first_segment_id;
279
0
            append_info.txn_id = txn_id;
280
0
            append_info.expiration_time = file_cache_ttl_sec > 0 && newest_write_timestamp > 0
281
0
                                                  ? newest_write_timestamp + file_cache_ttl_sec
282
0
                                                  : 0;
283
0
            fs = std::make_shared<io::PackedFileSystem>(fs, append_info);
284
0
        }
285
286
        // Then apply encryption on top
287
965
        if (algorithm.has_value()) {
288
965
            fs = io::make_file_system(fs, algorithm.value());
289
965
        }
290
291
        // Cache the result to ensure consistency across multiple calls
292
965
        _cached_fs = fs;
293
965
        return fs;
294
4.13k
    }
295
296
0
    io::FileSystem& fs_ref() const { return *fs(); }
297
298
4.11k
    io::FileWriterOptions get_file_writer_options(FileType file_type = FileType::SEGMENT_FILE) {
299
4.11k
        io::FileWriterOptions opts {.write_file_cache = write_file_cache,
300
4.11k
                                    .is_cold_data = is_hot_data,
301
4.11k
                                    .file_cache_expiration_time = file_cache_ttl_sec,
302
4.11k
                                    .approximate_bytes_to_write = approximate_bytes_to_write};
303
304
4.11k
        if (config::enable_file_cache_write_index_file_only) {
305
20
            opts.allow_adaptive_file_cache_write = false;
306
20
            opts.approximate_bytes_to_write = 0;
307
20
            opts.write_file_cache = file_type == FileType::INVERTED_INDEX_FILE;
308
20
            return opts;
309
20
        }
310
311
4.09k
        if (compaction_output_write_index_only && file_type == FileType::SEGMENT_FILE) {
312
4
            opts.write_file_cache = false;
313
4
            opts.allow_adaptive_file_cache_write = false;
314
4
            opts.approximate_bytes_to_write = 0;
315
4
        }
316
317
4.09k
        return opts;
318
4.11k
    }
319
320
    struct BinlogOptions {
321
    public:
322
        bool enable = false;
323
324
42
        void set_need_before(bool need_before) {
325
42
            this->_need_before = need_before;
326
42
            _segment_write_binlog_opt.write_before = need_before;
327
42
        }
328
329
211
        segment_v2::SegmentWriteBinlogOptions& write_binlog_config() {
330
211
            return _segment_write_binlog_opt;
331
211
        }
332
333
73
        const segment_v2::SegmentWriteBinlogOptions& write_binlog_config() const {
334
73
            return _segment_write_binlog_opt;
335
73
        }
336
337
    private:
338
        bool _need_before = false;
339
        segment_v2::SegmentWriteBinlogOptions _segment_write_binlog_opt;
340
    } _write_binlog_opt;
341
342
3.35k
    BinlogOptions& write_binlog_opt() { return _write_binlog_opt; }
343
344
4.51k
    const BinlogOptions& write_binlog_opt() const { return _write_binlog_opt; }
345
};
346
347
inline segment_v2::HistoricalRowRetrieverContext
348
94
RowsetWriterContext::make_historical_row_retriever_context() {
349
94
    return segment_v2::HistoricalRowRetrieverContext {
350
94
            .tablet = tablet,
351
94
            .tablet_schema = tablet_schema,
352
94
            .rowset_writer_ctx = this,
353
94
            .partial_update_info = partial_update_info,
354
94
            .is_transient_rowset_writer = is_transient_rowset_writer,
355
94
            .write_type = write_type};
356
94
}
357
358
} // namespace doris