Coverage Report

Created: 2026-08-27 20:56

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