Coverage Report

Created: 2025-05-06 13:10

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