Coverage Report

Created: 2026-07-08 18:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/load/memtable/memtable_writer.cpp
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
#include "load/memtable/memtable_writer.h"
19
20
#include <fmt/format.h>
21
22
#include <filesystem>
23
#include <ostream>
24
#include <string>
25
#include <utility>
26
27
#include "common/compiler_util.h" // IWYU pragma: keep
28
#include "common/config.h"
29
#include "common/logging.h"
30
#include "common/status.h"
31
#include "core/block/block.h"
32
#include "io/fs/file_writer.h" // IWYU pragma: keep
33
#include "load/memtable/memtable.h"
34
#include "load/memtable/memtable_flush_executor.h"
35
#include "load/memtable/memtable_memory_limiter.h"
36
#include "runtime/exec_env.h"
37
#include "runtime/memory/mem_tracker.h"
38
#include "service/backend_options.h"
39
#include "storage/rowset/beta_rowset_writer.h"
40
#include "storage/rowset/group_rowset_writer.h"
41
#include "storage/rowset/rowset_writer.h"
42
#include "storage/schema_change/schema_change.h"
43
#include "storage/storage_engine.h"
44
#include "storage/tablet/tablet_schema.h"
45
#include "storage/tablet_info.h"
46
#include "util/mem_info.h"
47
#include "util/stopwatch.hpp"
48
49
namespace doris {
50
bvar::Adder<uint64_t> g_flush_cuz_rowscnt_oveflow("flush_cuz_rowscnt_oveflow");
51
52
using namespace ErrorCode;
53
54
264k
MemTableWriter::MemTableWriter(const WriteRequest& req) : _req(req) {}
55
56
264k
MemTableWriter::~MemTableWriter() {
57
264k
    if (!_is_init) {
58
90.8k
        return;
59
90.8k
    }
60
173k
    if (_flush_token != nullptr) {
61
        // cancel and wait all memtables in flush queue to be finished
62
173k
        _flush_token->cancel();
63
173k
    }
64
173k
    _mem_table.reset();
65
173k
}
66
67
Status MemTableWriter::init(std::shared_ptr<RowsetWriter> rowset_writer,
68
                            TabletSchemaSPtr tablet_schema,
69
                            std::shared_ptr<PartialUpdateInfo> partial_update_info,
70
172k
                            std::shared_ptr<WorkloadGroup> wg_sptr, bool unique_key_mow) {
71
172k
    _rowset_writer = rowset_writer;
72
172k
    _tablet_schema = tablet_schema;
73
172k
    _unique_key_mow = unique_key_mow;
74
172k
    _partial_update_info = partial_update_info;
75
172k
    _resource_ctx = thread_context()->resource_ctx();
76
77
172k
    _reset_mem_table();
78
79
    // create flush handler
80
    // by assigning segment_id to memtable before submiting to flush executor,
81
    // we can make sure same keys sort in the same order in all replicas.
82
172k
    RETURN_IF_ERROR(
83
172k
            ExecEnv::GetInstance()->storage_engine().memtable_flush_executor()->create_flush_token(
84
172k
                    _flush_token, _rowset_writer, _req.is_high_priority, wg_sptr,
85
172k
                    _req.table_schema_param));
86
87
172k
    _is_init = true;
88
172k
    return Status::OK();
89
172k
}
90
91
Status MemTableWriter::write(const Block* block, const DorisVector<uint32_t>& row_idxs,
92
114k
                             bool* memtable_flushed) {
93
114k
    if (memtable_flushed != nullptr) {
94
114k
        *memtable_flushed = false;
95
114k
    }
96
114k
    if (UNLIKELY(row_idxs.empty())) {
97
0
        return Status::OK();
98
0
    }
99
114k
    _lock_watch.start();
100
114k
    std::lock_guard<std::mutex> l(_lock);
101
114k
    _lock_watch.stop();
102
114k
    if (_is_cancelled) {
103
0
        return _cancel_status;
104
0
    }
105
114k
    if (!_is_init) {
106
0
        return Status::Error<NOT_INITIALIZED>("delta segment writer has not been initialized");
107
0
    }
108
114k
    if (_is_closed) {
109
0
        return Status::Error<ALREADY_CLOSED>("write block after closed tablet_id={}, load_id={}-{}",
110
0
                                             _req.tablet_id, _req.load_id.hi(), _req.load_id.lo());
111
0
    }
112
113
    // Flush and reset memtable if it is raw rows great than int32_t.
114
114k
    int64_t raw_rows = _mem_table->raw_rows();
115
114k
    DBUG_EXECUTE_IF("MemTableWriter.too_many_raws",
116
114k
                    { raw_rows = std::numeric_limits<int32_t>::max(); });
117
114k
    if (raw_rows + row_idxs.size() > std::numeric_limits<int32_t>::max()) {
118
0
        g_flush_cuz_rowscnt_oveflow << 1;
119
0
        RETURN_IF_ERROR(_flush_memtable());
120
0
        if (memtable_flushed != nullptr) {
121
0
            *memtable_flushed = true;
122
0
        }
123
0
    }
124
125
114k
    _total_received_rows += row_idxs.size();
126
114k
    auto st = _mem_table->insert(block, row_idxs);
127
128
    // Reset memtable immediately after insert failure to prevent potential flush operations.
129
    // This is a defensive measure because:
130
    // 1. When insert fails (e.g., memory allocation failure during add_rows),
131
    //    the memtable is in an inconsistent state and should not be flushed
132
    // 2. However, memory pressure might trigger a flush operation on this failed memtable
133
    // 3. By resetting here, we ensure the failed memtable won't be included in any subsequent flush,
134
    //    thus preventing potential crashes
135
114k
    DBUG_EXECUTE_IF("MemTableWriter.write.random_insert_error", {
136
114k
        if (rand() % 100 < (100 * dp->param("percent", 0.3))) {
137
114k
            st = Status::InternalError<false>("write memtable random failed for debug");
138
114k
        }
139
114k
    });
140
114k
    if (!st.ok()) [[unlikely]] {
141
0
        _reset_mem_table();
142
0
        return st;
143
0
    }
144
145
114k
    if (UNLIKELY(_mem_table->need_agg() && config::enable_shrink_memory)) {
146
0
        _mem_table->shrink_memtable_by_agg();
147
0
    }
148
114k
    if (UNLIKELY(_mem_table->need_flush())) {
149
0
        RETURN_IF_ERROR(_flush_memtable());
150
0
        if (memtable_flushed != nullptr) {
151
0
            *memtable_flushed = true;
152
0
        }
153
0
    }
154
155
114k
    return Status::OK();
156
114k
}
157
158
0
Status MemTableWriter::_flush_memtable() {
159
0
    auto s = _flush_memtable_async();
160
0
    _reset_mem_table();
161
0
    if (UNLIKELY(!s.ok())) {
162
0
        return s;
163
0
    }
164
0
    return Status::OK();
165
0
}
166
167
173k
Status MemTableWriter::_flush_memtable_async() {
168
173k
    DCHECK(_flush_token != nullptr);
169
173k
    std::shared_ptr<MemTable> memtable;
170
173k
    {
171
173k
        std::lock_guard<std::mutex> l(_mem_table_ptr_lock);
172
173k
        memtable = _mem_table;
173
173k
        _mem_table = nullptr;
174
173k
        memtable->update_mem_type(MemType::WRITE_FINISHED);
175
173k
        _freezed_mem_tables.push_back(memtable);
176
173k
    }
177
173k
    return _flush_token->submit(memtable);
178
173k
}
179
180
0
Status MemTableWriter::flush_async() {
181
0
    std::lock_guard<std::mutex> l(_lock);
182
    // Three calling paths:
183
    // 1. call by local, from `VTabletWriterV2::_write_memtable`.
184
    // 2. call by remote, from `LoadChannelMgr::_get_load_channel`.
185
    // 3. call by daemon thread, from `handle_paused_queries` -> `flush_workload_group_memtables`.
186
0
    if (!_is_init || _is_closed) {
187
        // This writer is uninitialized or closed before flushing, do nothing.
188
        // We return OK instead of NOT_INITIALIZED or ALREADY_CLOSED.
189
        // Because this method maybe called when trying to reduce mem consumption,
190
        // and at that time, the writer may not be initialized yet and that is a normal case.
191
0
        return Status::OK();
192
0
    }
193
194
0
    if (_is_cancelled) {
195
0
        return _cancel_status;
196
0
    }
197
198
0
    DCHECK(_resource_ctx != nullptr);
199
0
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_resource_ctx->memory_context()->mem_tracker());
200
201
0
    VLOG_NOTICE << "flush memtable to reduce mem consumption. memtable size: "
202
0
                << PrettyPrinter::print_bytes(_mem_table->memory_usage())
203
0
                << ", tablet: " << _req.tablet_id << ", load id: " << print_id(_req.load_id);
204
0
    auto s = _flush_memtable_async();
205
0
    _reset_mem_table();
206
0
    return s;
207
0
}
208
209
77
Status MemTableWriter::wait_flush() {
210
77
    {
211
77
        std::lock_guard<std::mutex> l(_lock);
212
77
        if (!_is_init || _is_closed) {
213
            // return OK instead of NOT_INITIALIZED or ALREADY_CLOSED for same reason
214
            // as described in flush_async()
215
77
            return Status::OK();
216
77
        }
217
0
        if (_is_cancelled) {
218
0
            return _cancel_status;
219
0
        }
220
0
    }
221
0
    SCOPED_RAW_TIMER(&_wait_flush_time_ns);
222
0
    RETURN_IF_ERROR(_flush_token->wait());
223
0
    return Status::OK();
224
0
}
225
226
172k
void MemTableWriter::_reset_mem_table() {
227
172k
    {
228
172k
        std::lock_guard<std::mutex> l(_mem_table_ptr_lock);
229
172k
        _mem_table.reset(new MemTable(_req.tablet_id, _tablet_schema, _req.slots, _req.tuple_desc,
230
172k
                                      _unique_key_mow, _partial_update_info.get(), _resource_ctx));
231
172k
    }
232
233
172k
    _segment_num++;
234
172k
}
235
236
173k
Status MemTableWriter::close() {
237
173k
    _lock_watch.start();
238
173k
    std::lock_guard<std::mutex> l(_lock);
239
173k
    _lock_watch.stop();
240
173k
    if (_is_cancelled) {
241
0
        return _cancel_status;
242
0
    }
243
173k
    if (!_is_init) {
244
0
        return Status::Error<NOT_INITIALIZED>("delta segment writer has not been initialized");
245
0
    }
246
173k
    if (_is_closed) {
247
0
        LOG(WARNING) << "close after closed tablet_id=" << _req.tablet_id
248
0
                     << " load_id=" << _req.load_id;
249
0
        return Status::OK();
250
0
    }
251
252
173k
    auto s = _flush_memtable_async();
253
173k
    {
254
173k
        std::lock_guard<std::mutex> lm(_mem_table_ptr_lock);
255
173k
        _mem_table.reset();
256
173k
    }
257
173k
    _is_closed = true;
258
173k
    if (UNLIKELY(!s.ok())) {
259
0
        return s;
260
173k
    } else {
261
173k
        return Status::OK();
262
173k
    }
263
173k
}
264
265
173k
Status MemTableWriter::_do_close_wait() {
266
173k
    SCOPED_RAW_TIMER(&_close_wait_time_ns);
267
173k
    std::lock_guard<std::mutex> l(_lock);
268
18.4E
    DCHECK(_is_init)
269
18.4E
            << "delta writer is supposed be to initialized before close_wait() being called";
270
271
173k
    if (_is_cancelled) {
272
0
        return _cancel_status;
273
0
    }
274
275
173k
    Status st;
276
    // return error if previous flush failed
277
173k
    {
278
173k
        SCOPED_RAW_TIMER(&_wait_flush_time_ns);
279
173k
        st = _flush_token->wait();
280
173k
    }
281
173k
    if (UNLIKELY(!st.ok())) {
282
43
        LOG(WARNING) << "previous flush failed tablet " << _req.tablet_id;
283
43
        return st;
284
43
    }
285
286
173k
    if (_rowset_writer->num_rows() + _flush_token->memtable_stat().merged_rows !=
287
173k
        _total_received_rows) {
288
0
        LOG(WARNING) << "the rows number written doesn't match, rowset num rows written to file: "
289
0
                     << _rowset_writer->num_rows()
290
0
                     << ", merged_rows: " << _flush_token->memtable_stat().merged_rows
291
0
                     << ", total received rows: " << _total_received_rows;
292
0
        return Status::InternalError("rows number written by delta writer dosen't match");
293
0
    }
294
295
    // print slow log if wait more than 1s
296
173k
    if (_wait_flush_time_ns > 1000UL * 1000 * 1000) {
297
514
        LOG(INFO) << "close delta writer for tablet: " << _req.tablet_id
298
514
                  << ", load id: " << print_id(_req.load_id) << ", wait close for "
299
514
                  << _wait_flush_time_ns << "(ns), stats: " << _flush_token->get_stats();
300
514
    }
301
302
173k
    return Status::OK();
303
173k
}
304
305
49
void MemTableWriter::_update_profile(RuntimeProfile* profile) {
306
49
    if (!profile) {
307
0
        return;
308
0
    }
309
    // NOTE: MemTableWriter may be accessed when profile is out of scope, in MemTableMemoryLimiter.
310
    // To avoid accessing dangling pointers, we cannot make profile as a member of MemTableWriter.
311
49
    auto child =
312
49
            profile->create_child(fmt::format("MemTableWriter {}", _req.tablet_id), true, true);
313
49
    auto lock_timer = ADD_TIMER(child, "LockTime");
314
49
    auto sort_timer = ADD_TIMER(child, "MemTableSortTime");
315
49
    auto agg_timer = ADD_TIMER(child, "MemTableAggTime");
316
49
    auto memtable_duration_timer = ADD_TIMER(child, "MemTableDurationTime");
317
49
    auto segment_writer_timer = ADD_TIMER(child, "SegmentWriterTime");
318
49
    auto wait_flush_timer = ADD_TIMER(child, "MemTableWaitFlushTime");
319
49
    auto put_into_output_timer = ADD_TIMER(child, "MemTablePutIntoOutputTime");
320
49
    auto delete_bitmap_timer = ADD_TIMER(child, "DeleteBitmapTime");
321
49
    auto close_wait_timer = ADD_TIMER(child, "CloseWaitTime");
322
49
    auto sort_times = ADD_COUNTER(child, "MemTableSortTimes", TUnit::UNIT);
323
49
    auto agg_times = ADD_COUNTER(child, "MemTableAggTimes", TUnit::UNIT);
324
49
    auto segment_num = ADD_COUNTER(child, "SegmentNum", TUnit::UNIT);
325
49
    auto raw_rows_num = ADD_COUNTER(child, "RawRowNum", TUnit::UNIT);
326
49
    auto merged_rows_num = ADD_COUNTER(child, "MergedRowNum", TUnit::UNIT);
327
328
49
    COUNTER_UPDATE(lock_timer, _lock_watch.elapsed_time());
329
49
    COUNTER_SET(delete_bitmap_timer, _rowset_writer->delete_bitmap_ns());
330
49
    COUNTER_SET(segment_writer_timer, _rowset_writer->segment_writer_ns());
331
49
    COUNTER_SET(wait_flush_timer, _wait_flush_time_ns);
332
49
    COUNTER_SET(close_wait_timer, _close_wait_time_ns);
333
49
    COUNTER_SET(segment_num, _segment_num);
334
49
    const auto& memtable_stat = _flush_token->memtable_stat();
335
49
    COUNTER_SET(sort_timer, memtable_stat.sort_ns);
336
49
    COUNTER_SET(agg_timer, memtable_stat.agg_ns);
337
49
    COUNTER_SET(memtable_duration_timer, memtable_stat.duration_ns);
338
49
    COUNTER_SET(put_into_output_timer, memtable_stat.put_into_output_ns);
339
49
    COUNTER_SET(sort_times, memtable_stat.sort_times);
340
49
    COUNTER_SET(agg_times, memtable_stat.agg_times);
341
49
    COUNTER_SET(raw_rows_num, memtable_stat.raw_rows);
342
49
    COUNTER_SET(merged_rows_num, memtable_stat.merged_rows);
343
49
}
344
345
173k
Status MemTableWriter::cancel() {
346
173k
    return cancel_with_status(Status::Cancelled("already cancelled"));
347
173k
}
348
349
263k
Status MemTableWriter::cancel_with_status(const Status& st) {
350
263k
    std::lock_guard<std::mutex> l(_lock);
351
263k
    if (_is_cancelled) {
352
11
        return Status::OK();
353
11
    }
354
263k
    {
355
263k
        std::lock_guard<std::mutex> lm(_mem_table_ptr_lock);
356
263k
        _mem_table.reset();
357
263k
    }
358
263k
    if (_flush_token != nullptr) {
359
        // cancel and wait all memtables in flush queue to be finished
360
173k
        _flush_token->cancel();
361
173k
    }
362
263k
    _is_cancelled = true;
363
263k
    _cancel_status = st;
364
263k
    return Status::OK();
365
263k
}
366
367
173k
const FlushStatistic& MemTableWriter::get_flush_token_stats() {
368
173k
    return _flush_token->get_stats();
369
173k
}
370
371
114k
uint64_t MemTableWriter::flush_running_count() const {
372
114k
    return _flush_token == nullptr ? 0 : _flush_token->get_stats().flush_running_count.load();
373
114k
}
374
375
258k
int64_t MemTableWriter::table_id() const {
376
258k
    DORIS_CHECK(_req.table_schema_param != nullptr);
377
258k
    return _req.table_schema_param->table_id();
378
258k
}
379
380
25.9k
int64_t MemTableWriter::flush_pending_memtable_count() {
381
25.9k
    std::lock_guard<std::mutex> l(_mem_table_ptr_lock);
382
25.9k
    int64_t memtable_count = 0;
383
25.9k
    for (const auto& mem_table : _freezed_mem_tables) {
384
10
        auto mem_table_sptr = mem_table.lock();
385
10
        if (mem_table_sptr == nullptr) {
386
9
            continue;
387
9
        }
388
1
        auto mem_type = mem_table_sptr->get_mem_type();
389
1
        if (mem_type == MemType::WRITE_FINISHED || mem_type == MemType::FLUSH) {
390
1
            memtable_count++;
391
1
        }
392
1
    }
393
25.9k
    return memtable_count;
394
25.9k
}
395
396
8.80M
int64_t MemTableWriter::mem_consumption(MemType mem) {
397
8.80M
    if (!_is_init) {
398
        // This method may be called before this writer is initialized.
399
        // So _flush_token may be null.
400
126
        return 0;
401
126
    }
402
8.80M
    int64_t mem_usage = 0;
403
8.80M
    {
404
8.80M
        std::lock_guard<std::mutex> l(_mem_table_ptr_lock);
405
8.80M
        for (const auto& mem_table : _freezed_mem_tables) {
406
4.24M
            auto mem_table_sptr = mem_table.lock();
407
4.24M
            if (mem_table_sptr != nullptr && mem_table_sptr->get_mem_type() == mem) {
408
635k
                mem_usage += mem_table_sptr->memory_usage();
409
635k
            }
410
4.24M
        }
411
8.80M
    }
412
8.80M
    return mem_usage;
413
8.80M
}
414
415
4.40M
int64_t MemTableWriter::active_memtable_mem_consumption() {
416
4.40M
    std::lock_guard<std::mutex> l(_mem_table_ptr_lock);
417
4.40M
    return _mem_table != nullptr ? _mem_table->memory_usage() : 0;
418
4.40M
}
419
420
} // namespace doris