Coverage Report

Created: 2026-10-16 20:34

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