Coverage Report

Created: 2026-07-10 12:22

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