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