Coverage Report

Created: 2026-07-06 17:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/load/group_commit/group_commit_mgr.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/group_commit/group_commit_mgr.h"
19
20
#include <gen_cpp/Types_types.h>
21
#include <glog/logging.h>
22
23
#include <chrono>
24
25
#include "cloud/config.h"
26
#include "common/compiler_util.h"
27
#include "common/config.h"
28
#include "common/status.h"
29
#include "exec/pipeline/dependency.h"
30
#include "runtime/exec_env.h"
31
#include "runtime/fragment_mgr.h"
32
#include "runtime/memory/mem_tracker_limiter.h"
33
#include "runtime/thread_context.h"
34
#include "util/client_cache.h"
35
#include "util/debug_points.h"
36
#include "util/thrift_rpc_helper.h"
37
#include "util/time.h"
38
39
namespace doris {
40
41
bvar::Adder<uint64_t> group_commit_block_by_memory_counter("group_commit_block_by_memory_counter");
42
43
0
std::string LoadBlockQueue::_get_load_ids() {
44
0
    std::stringstream ss;
45
0
    ss << "[";
46
0
    for (auto& id : _load_ids_to_write_dep) {
47
0
        ss << id.first.to_string() << ", ";
48
0
    }
49
0
    ss << "]";
50
0
    return ss.str();
51
0
}
52
53
Status LoadBlockQueue::add_block(RuntimeState* runtime_state, std::shared_ptr<Block> block,
54
0
                                 bool write_wal, UniqueId& load_id) {
55
0
    DBUG_EXECUTE_IF("LoadBlockQueue.add_block.failed",
56
0
                    { return Status::InternalError("LoadBlockQueue.add_block.failed"); });
57
0
    DBUG_EXECUTE_IF("LoadBlockQueue.add_block.block_reuse_second", {
58
0
        int seq = _debug_add_block_seq.fetch_add(1);
59
0
        if (seq >= 1) {
60
0
            LOG(INFO) << "debug hold reuse 2nd+ add_block, label=" << label
61
0
                      << ", load_id=" << load_id.to_string();
62
0
            int64_t waited_ms = 0;
63
0
            while (waited_ms < 10000 && DebugPoints::instance()->is_enable(
64
0
                                                "LoadBlockQueue.add_block.block_reuse_second")) {
65
0
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
66
0
                waited_ms += 10;
67
0
            }
68
0
            LOG(INFO) << "debug release reuse 2nd+ add_block, label=" << label
69
0
                      << ", load_id=" << load_id.to_string() << ", waited_ms=" << waited_ms;
70
0
        }
71
0
    });
72
0
    std::unique_lock l(mutex);
73
0
    RETURN_IF_ERROR(status);
74
0
    if (UNLIKELY(runtime_state->is_cancelled())) {
75
0
        return runtime_state->cancel_reason();
76
0
    }
77
0
    RETURN_IF_ERROR(status);
78
0
    LOG(INFO) << "query_id: " << print_id(runtime_state->query_id())
79
0
              << ", add block rows=" << block->rows() << ", use group_commit label=" << label;
80
0
    DBUG_EXECUTE_IF("LoadBlockQueue.add_block.block", DBUG_BLOCK);
81
0
    if (block->rows() > 0) {
82
0
        if (!config::group_commit_wait_replay_wal_finish) {
83
0
            _block_queue.emplace_back(block);
84
0
            _data_bytes += block->bytes();
85
0
            size_t before_block_queues_bytes = _all_block_queues_bytes->load();
86
0
            _all_block_queues_bytes->fetch_add(block->bytes(), std::memory_order_relaxed);
87
0
            VLOG_DEBUG << "[Group Commit Debug] (LoadBlockQueue::add_block). "
88
0
                       << "Cur block rows=" << block->rows() << ", bytes=" << block->bytes()
89
0
                       << ". all block queues bytes from " << before_block_queues_bytes << " to  "
90
0
                       << _all_block_queues_bytes->load() << ", queue size=" << _block_queue.size()
91
0
                       << ". txn_id=" << txn_id << ", label=" << label
92
0
                       << ", instance_id=" << load_instance_id << ", load_ids=" << _get_load_ids();
93
0
        }
94
0
        if (write_wal || config::group_commit_wait_replay_wal_finish) {
95
0
            auto st = _v_wal_writer->write_wal(block.get());
96
0
            if (!st.ok()) {
97
0
                _cancel_without_lock(st);
98
0
                return st;
99
0
            }
100
0
        }
101
0
        if (!runtime_state->is_cancelled() && status.ok() &&
102
0
            _all_block_queues_bytes->load(std::memory_order_relaxed) >=
103
0
                    config::group_commit_queue_mem_limit) {
104
0
            group_commit_block_by_memory_counter << 1;
105
0
            auto dep_it = _load_ids_to_write_dep.find(load_id);
106
0
            DCHECK(dep_it != _load_ids_to_write_dep.end());
107
0
            if (dep_it != _load_ids_to_write_dep.end() && dep_it->second) {
108
0
                dep_it->second->block();
109
0
                VLOG_DEBUG << "block add_block for load_id=" << load_id << ", memory="
110
0
                           << _all_block_queues_bytes->load(std::memory_order_relaxed)
111
0
                           << ". inner load_id=" << load_instance_id << ", label=" << label;
112
0
            }
113
0
        }
114
0
    }
115
0
    if (!_need_commit.load()) {
116
0
        if (_data_bytes >= _group_commit_data_bytes) {
117
0
            VLOG_DEBUG << "group commit meets commit condition for data size, label=" << label
118
0
                       << ", instance_id=" << load_instance_id << ", data_bytes=" << _data_bytes;
119
0
            _need_commit.store(true);
120
0
            data_size_condition = true;
121
0
        }
122
0
        if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() -
123
0
                                                                  _start_time)
124
0
                    .count() >= _group_commit_interval_ms) {
125
0
            VLOG_DEBUG << "group commit meets commit condition for time interval, label=" << label
126
0
                       << ", instance_id=" << load_instance_id << ", data_bytes=" << _data_bytes;
127
0
            _need_commit.store(true);
128
0
        }
129
0
    }
130
0
    for (auto read_dep : _read_deps) {
131
0
        read_dep->set_ready();
132
0
        VLOG_DEBUG << "set ready for inner load_id=" << load_instance_id;
133
0
    }
134
0
    return Status::OK();
135
0
}
136
137
Status LoadBlockQueue::get_block(RuntimeState* runtime_state, Block* block, bool* find_block,
138
0
                                 bool* eos, std::shared_ptr<Dependency> get_block_dep) {
139
0
    *find_block = false;
140
0
    *eos = false;
141
0
    std::unique_lock l(mutex);
142
0
    if (runtime_state->is_cancelled() || !status.ok()) {
143
0
        auto st = runtime_state->cancel_reason();
144
0
        _cancel_without_lock(st);
145
0
        return status;
146
0
    }
147
0
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
148
0
                            std::chrono::steady_clock::now() - _start_time)
149
0
                            .count();
150
0
    if (!_need_commit.load() && duration >= _group_commit_interval_ms) {
151
0
        _need_commit.store(true);
152
0
    }
153
0
    if (_block_queue.empty()) {
154
0
        if (_need_commit.load() && duration >= 10 * _group_commit_interval_ms) {
155
0
            auto last_print_duration = std::chrono::duration_cast<std::chrono::milliseconds>(
156
0
                                               std::chrono::steady_clock::now() - _last_print_time)
157
0
                                               .count();
158
0
            if (last_print_duration >= 10000) {
159
0
                _last_print_time = std::chrono::steady_clock::now();
160
0
                LOG(INFO) << "find one group_commit need to commit, txn_id=" << txn_id
161
0
                          << ", label=" << label << ", instance_id=" << load_instance_id
162
0
                          << ", duration=" << duration << ", load_ids=" << _get_load_ids();
163
0
            }
164
0
        }
165
0
        VLOG_DEBUG << "get_block for inner load_id=" << load_instance_id << ", but queue is empty";
166
0
        if (!_need_commit.load()) {
167
0
            get_block_dep->block();
168
0
            VLOG_DEBUG << "block get_block for inner load_id=" << load_instance_id;
169
0
        }
170
0
    } else {
171
0
        const BlockData block_data = _block_queue.front();
172
0
        block->swap(*block_data.block);
173
0
        *find_block = true;
174
0
        _block_queue.pop_front();
175
0
        size_t before_block_queues_bytes = _all_block_queues_bytes->load();
176
0
        _all_block_queues_bytes->fetch_sub(block_data.block_bytes, std::memory_order_relaxed);
177
0
        VLOG_DEBUG << "[Group Commit Debug] (LoadBlockQueue::get_block). "
178
0
                   << "Cur block rows=" << block->rows() << ", bytes=" << block->bytes()
179
0
                   << ". all block queues bytes from " << before_block_queues_bytes << " to  "
180
0
                   << _all_block_queues_bytes->load() << ", queue size=" << _block_queue.size()
181
0
                   << ". txn_id=" << txn_id << ", label=" << label
182
0
                   << ", instance_id=" << load_instance_id << ", load_ids=" << _get_load_ids();
183
0
    }
184
0
    if (_block_queue.empty() && _need_commit.load() && _load_ids_to_write_dep.empty()) {
185
0
        *eos = true;
186
0
    } else {
187
0
        *eos = false;
188
0
    }
189
0
    if (_all_block_queues_bytes->load(std::memory_order_relaxed) <
190
0
        config::group_commit_queue_mem_limit) {
191
0
        for (auto& id : _load_ids_to_write_dep) {
192
0
            id.second->set_ready();
193
0
        }
194
0
        VLOG_DEBUG << "set ready for load_ids=" << _get_load_ids()
195
0
                   << ". inner load_id=" << load_instance_id << ", label=" << label;
196
0
    }
197
0
    return Status::OK();
198
0
}
199
200
0
Status LoadBlockQueue::remove_load_id(const UniqueId& load_id) {
201
0
    std::unique_lock l(mutex);
202
0
    if (_load_ids_to_write_dep.find(load_id) != _load_ids_to_write_dep.end()) {
203
0
        _load_ids_to_write_dep[load_id]->set_always_ready();
204
0
        _load_ids_to_write_dep.erase(load_id);
205
0
        for (auto read_dep : _read_deps) {
206
0
            read_dep->set_ready();
207
0
        }
208
0
        VLOG_DEBUG << "set ready for load_id=" << load_id << ", inner load_id=" << load_instance_id;
209
0
        return Status::OK();
210
0
    }
211
0
    return Status::NotFound<false>("load_id=" + load_id.to_string() +
212
0
                                   " not in block queue, label=" + label);
213
0
}
214
215
0
bool LoadBlockQueue::contain_load_id(const UniqueId& load_id) {
216
0
    std::unique_lock l(mutex);
217
0
    return _load_ids_to_write_dep.find(load_id) != _load_ids_to_write_dep.end();
218
0
}
219
220
Status LoadBlockQueue::add_load_id(const UniqueId& load_id,
221
0
                                   const std::shared_ptr<Dependency> put_block_dep) {
222
0
    std::unique_lock l(mutex);
223
0
    if (_need_commit.load() || !status.ok() || process_finish.load()) {
224
0
        return Status::InternalError<false>(
225
0
                "block queue cannot add load id, id=" + load_instance_id.to_string() +
226
0
                ", need_commit=" + (_need_commit.load() ? "true" : "false") +
227
0
                ", process_finish=" + (process_finish.load() ? "true" : "false") +
228
0
                ", queue_status=" + status.to_string());
229
0
    }
230
0
    _load_ids_to_write_dep[load_id] = put_block_dep;
231
0
    group_commit_load_count.fetch_add(1);
232
0
    return Status::OK();
233
0
}
234
235
0
void LoadBlockQueue::cancel(const Status& st) {
236
0
    DCHECK(!st.ok());
237
0
    std::unique_lock l(mutex);
238
0
    _cancel_without_lock(st);
239
0
}
240
241
0
void LoadBlockQueue::_cancel_without_lock(const Status& st) {
242
0
    LOG(INFO) << "cancel group_commit, instance_id=" << load_instance_id << ", label=" << label
243
0
              << ", status=" << st.to_string();
244
0
    status =
245
0
            Status::Cancelled("cancel group_commit, label=" + label + ", status=" + st.to_string());
246
0
    size_t before_block_queues_bytes = _all_block_queues_bytes->load();
247
0
    while (!_block_queue.empty()) {
248
0
        const BlockData& block_data = _block_queue.front();
249
0
        _all_block_queues_bytes->fetch_sub(block_data.block_bytes, std::memory_order_relaxed);
250
0
        _block_queue.pop_front();
251
0
    }
252
0
    VLOG_DEBUG << "[Group Commit Debug] (LoadBlockQueue::_cancel_without_block). "
253
0
               << "all block queues bytes from " << before_block_queues_bytes << " to "
254
0
               << _all_block_queues_bytes->load() << ", queue size=" << _block_queue.size()
255
0
               << ", txn_id=" << txn_id << ", label=" << label
256
0
               << ", instance_id=" << load_instance_id << ", load_ids=" << _get_load_ids();
257
0
    for (auto& id : _load_ids_to_write_dep) {
258
0
        id.second->set_always_ready();
259
0
    }
260
0
    for (auto read_dep : _read_deps) {
261
0
        read_dep->set_ready();
262
0
    }
263
0
    VLOG_DEBUG << "set ready for load_ids=" << _get_load_ids()
264
0
               << ", inner load_id=" << load_instance_id;
265
0
}
266
267
Status GroupCommitTable::get_first_block_load_queue(
268
        int64_t table_id, int64_t base_schema_version, int64_t index_size, const UniqueId& load_id,
269
        std::shared_ptr<LoadBlockQueue>& load_block_queue, int be_exe_version,
270
0
        std::shared_ptr<Dependency> create_plan_dep, std::shared_ptr<Dependency> put_block_dep) {
271
0
    DCHECK(table_id == _table_id);
272
0
    std::unique_lock l(_lock);
273
0
    auto try_to_get_matched_queue = [&]() -> Status {
274
0
        for (const auto& [_, inner_block_queue] : _load_block_queues) {
275
0
            if (inner_block_queue->contain_load_id(load_id)) {
276
0
                load_block_queue = inner_block_queue;
277
0
                return Status::OK();
278
0
            }
279
0
        }
280
0
        for (const auto& [_, inner_block_queue] : _load_block_queues) {
281
0
            if (!inner_block_queue->need_commit()) {
282
0
                if (base_schema_version == inner_block_queue->schema_version &&
283
0
                    index_size == inner_block_queue->index_size) {
284
0
                    if (inner_block_queue->add_load_id(load_id, put_block_dep).ok()) {
285
0
                        load_block_queue = inner_block_queue;
286
0
                        return Status::OK();
287
0
                    }
288
0
                } else {
289
0
                    return Status::DataQualityError<false>(
290
0
                            "schema version not match, maybe a schema change is in process. "
291
0
                            "Please retry this load manually.");
292
0
                }
293
0
            }
294
0
        }
295
0
        return Status::InternalError<false>("can not get a block queue for table_id: " +
296
0
                                            std::to_string(_table_id) + _create_plan_failed_reason);
297
0
    };
298
299
0
    if (try_to_get_matched_queue().ok()) {
300
0
        return Status::OK();
301
0
    }
302
0
    create_plan_dep->block();
303
0
    _create_plan_be_exe_version = be_exe_version;
304
0
    if (_create_plan_deps.empty()) {
305
0
        _create_plan_start_time_ms = MonotonicMillis();
306
0
    }
307
0
    _create_plan_deps.emplace(load_id, std::make_tuple(create_plan_dep, put_block_dep,
308
0
                                                       base_schema_version, index_size));
309
0
    [[maybe_unused]] auto submit_st = _submit_create_group_commit_load();
310
0
    return try_to_get_matched_queue();
311
0
}
312
313
0
Status GroupCommitTable::submit_create_group_commit_load() {
314
0
    std::unique_lock l(_lock);
315
0
    if (_create_plan_deps.empty()) {
316
0
        return Status::OK();
317
0
    }
318
0
    return _submit_create_group_commit_load();
319
0
}
320
321
0
Status GroupCommitTable::_submit_create_group_commit_load() {
322
0
    if (_is_creating_plan_fragment) {
323
0
        return Status::OK();
324
0
    }
325
326
0
    int64_t timeout_ms = config::group_commit_create_plan_timeout_ms;
327
0
    if (timeout_ms > 0 && !_create_plan_deps.empty()) {
328
0
        int64_t now_ms = MonotonicMillis();
329
0
        if (_create_plan_start_time_ms > 0 && now_ms - _create_plan_start_time_ms > timeout_ms) {
330
0
            std::string last_create_plan_failed_reason = _create_plan_failed_reason;
331
0
            _create_plan_failed_reason =
332
0
                    ". group commit create plan timeout after " + std::to_string(timeout_ms) + "ms";
333
0
            if (!last_create_plan_failed_reason.empty()) {
334
0
                _create_plan_failed_reason +=
335
0
                        ", last create plan error: " + last_create_plan_failed_reason;
336
0
            }
337
0
            for (const auto& [id, load_info] : _create_plan_deps) {
338
0
                std::get<0>(load_info)->set_ready();
339
0
            }
340
0
            _create_plan_deps.clear();
341
0
            _create_plan_start_time_ms = 0;
342
0
            return Status::OK();
343
0
        }
344
0
    }
345
346
0
    auto mem_tracker = _group_commit_mgr->group_commit_mem_tracker();
347
0
    int be_exe_version = _create_plan_be_exe_version;
348
0
    _is_creating_plan_fragment = true;
349
0
    auto submit_st = _thread_pool->submit_func([&, be_exe_version, mem_tracker] {
350
0
        std::shared_ptr<LoadBlockQueue> created_load_block_queue;
351
0
        Status create_group_commit_st = Status::OK();
352
0
        std::string create_plan_failed_reason;
353
0
        Defer defer {[&]() {
354
0
            bool need_resubmit = !create_group_commit_st.ok();
355
0
            std::unique_lock l(_lock);
356
0
            _is_creating_plan_fragment = false;
357
0
            _create_plan_failed_reason = create_plan_failed_reason;
358
0
            if (created_load_block_queue && create_group_commit_st.ok() &&
359
0
                !created_load_block_queue->need_commit()) {
360
0
                std::vector<UniqueId> success_load_ids;
361
0
                for (const auto& [id, load_info] : _create_plan_deps) {
362
0
                    auto create_dep = std::get<0>(load_info);
363
0
                    auto put_dep = std::get<1>(load_info);
364
0
                    if (created_load_block_queue->schema_version == std::get<2>(load_info) &&
365
0
                        created_load_block_queue->index_size == std::get<3>(load_info)) {
366
0
                        auto st = created_load_block_queue->add_load_id(id, put_dep);
367
0
                        if (!st.ok()) {
368
0
                            LOG(WARNING) << "failed to add pending load_id into created "
369
0
                                            "group commit queue, load_id="
370
0
                                         << id << ", label=" << created_load_block_queue->label
371
0
                                         << ", status=" << st.to_string();
372
0
                            need_resubmit = true;
373
0
                        } else {
374
0
                            create_dep->set_ready();
375
0
                            success_load_ids.emplace_back(id);
376
0
                        }
377
0
                    } else if (created_load_block_queue->schema_version > std::get<2>(load_info) ||
378
0
                               (created_load_block_queue->schema_version ==
379
0
                                        std::get<2>(load_info) &&
380
0
                                created_load_block_queue->index_size != std::get<3>(load_info))) {
381
                        // schema version mismatch:
382
                        //   1. the schema version of created load block queue is newer than the load request
383
                        //   2. the index size is not equal
384
                        // set ready for the load request to let it fail
385
0
                        create_dep->set_ready();
386
0
                        success_load_ids.emplace_back(id);
387
0
                    }
388
0
                }
389
0
                for (const auto& id : success_load_ids) {
390
0
                    _create_plan_deps.erase(id);
391
0
                }
392
0
                if (_create_plan_deps.empty()) {
393
0
                    _create_plan_start_time_ms = 0;
394
0
                }
395
0
            }
396
0
            if (!_create_plan_deps.empty()) {
397
0
                need_resubmit = true;
398
0
            }
399
0
            if (need_resubmit && _group_commit_mgr) {
400
0
                LOG(INFO) << "resubmit create group commit load task for table: " << _table_id;
401
0
                _group_commit_mgr->add_need_create_plan_table(_table_id);
402
0
            }
403
0
        }};
404
0
        create_group_commit_st =
405
0
                _create_group_commit_load(be_exe_version, mem_tracker, created_load_block_queue);
406
0
        if (!create_group_commit_st.ok()) {
407
0
            LOG(WARNING) << "create group commit load error: "
408
0
                         << create_group_commit_st.to_string();
409
0
            create_plan_failed_reason = ". create group commit load error: " +
410
0
                                        create_group_commit_st.to_string().substr(0, 300);
411
0
        } else {
412
0
            create_plan_failed_reason = "";
413
0
        }
414
0
    });
415
0
    if (!submit_st.ok()) {
416
0
        _is_creating_plan_fragment = false;
417
0
        _create_plan_failed_reason =
418
0
                ". create group commit load error: submit create group commit load task failed: " +
419
0
                submit_st.to_string().substr(0, 300);
420
0
        for (const auto& [id, load_info] : _create_plan_deps) {
421
0
            std::get<0>(load_info)->set_ready();
422
0
        }
423
0
        _create_plan_deps.clear();
424
0
        LOG(WARNING) << "submit create group commit load task for table: " << _table_id
425
0
                     << ", error: " << submit_st.to_string();
426
0
    }
427
0
    return submit_st;
428
0
}
429
430
0
void GroupCommitTable::remove_load_id(const UniqueId& load_id) {
431
0
    std::unique_lock l(_lock);
432
0
    if (_create_plan_deps.find(load_id) != _create_plan_deps.end()) {
433
0
        _create_plan_deps.erase(load_id);
434
0
        return;
435
0
    }
436
0
    for (const auto& [_, inner_block_queue] : _load_block_queues) {
437
0
        if (inner_block_queue->remove_load_id(load_id).ok()) {
438
0
            return;
439
0
        }
440
0
    }
441
0
}
442
443
Status GroupCommitTable::_create_group_commit_load(
444
        int be_exe_version, const std::shared_ptr<MemTrackerLimiter>& mem_tracker,
445
0
        std::shared_ptr<LoadBlockQueue>& created_load_block_queue) {
446
0
    Status st = Status::OK();
447
0
    TStreamLoadPutResult result;
448
0
    std::string label;
449
0
    int64_t txn_id;
450
0
    TUniqueId instance_id;
451
0
    {
452
0
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(mem_tracker);
453
0
        UniqueId load_id = UniqueId::gen_uid();
454
0
        TUniqueId tload_id;
455
0
        tload_id.__set_hi(load_id.hi);
456
0
        tload_id.__set_lo(load_id.lo);
457
0
        std::regex reg("-");
458
0
        label = "group_commit_" + std::regex_replace(load_id.to_string(), reg, "_");
459
0
        std::stringstream ss;
460
0
        ss << "insert into doris_internal_table_id(" << _table_id << ") WITH LABEL " << label
461
0
           << " select * from group_commit(\"table_id\"=\"" << _table_id << "\")";
462
0
        TStreamLoadPutRequest request;
463
0
        request.__set_load_sql(ss.str());
464
0
        request.__set_loadId(tload_id);
465
0
        request.__set_label(label);
466
0
        request.__set_token("group_commit"); // this is a fake, fe not check it now
467
0
        request.__set_max_filter_ratio(1.0);
468
0
        request.__set_strictMode(false);
469
0
        request.__set_partial_update(false);
470
        // this is an internal interface, use admin to pass the auth check
471
0
        request.__set_user("admin");
472
0
        if (_exec_env->cluster_info()->backend_id != 0) {
473
0
            request.__set_backend_id(_exec_env->cluster_info()->backend_id);
474
0
        } else {
475
0
            LOG(WARNING) << "_exec_env->cluster_info not set backend_id";
476
0
        }
477
0
        TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
478
0
        st = ThriftRpcHelper::rpc<FrontendServiceClient>(
479
0
                master_addr.hostname, master_addr.port,
480
0
                [&result, &request](FrontendServiceConnection& client) {
481
0
                    client->streamLoadPut(result, request);
482
0
                },
483
0
                10000L);
484
0
        if (!st.ok()) {
485
0
            LOG(WARNING) << "create group commit load rpc error, st=" << st.to_string();
486
0
            return st;
487
0
        }
488
0
        st = Status::create<false>(result.status);
489
0
        if (st.ok() && !result.__isset.pipeline_params) {
490
0
            st = Status::InternalError("Non-pipeline is disabled!");
491
0
        }
492
0
        if (!st.ok()) {
493
0
            LOG(WARNING) << "create group commit load error, st=" << st.to_string();
494
0
            return st;
495
0
        }
496
0
        auto& pipeline_params = result.pipeline_params;
497
0
        auto schema_version = pipeline_params.fragment.output_sink.olap_table_sink.schema.version;
498
0
        auto index_size =
499
0
                pipeline_params.fragment.output_sink.olap_table_sink.schema.indexes.size();
500
0
        DCHECK(pipeline_params.fragment.output_sink.olap_table_sink.db_id == _db_id);
501
0
        txn_id = pipeline_params.txn_conf.txn_id;
502
0
        DCHECK(pipeline_params.local_params.size() == 1);
503
0
        instance_id = pipeline_params.local_params[0].fragment_instance_id;
504
0
        VLOG_DEBUG << "create plan fragment, db_id=" << _db_id << ", table=" << _table_id
505
0
                   << ", schema version=" << schema_version << ", index size=" << index_size
506
0
                   << ", label=" << label << ", txn_id=" << txn_id
507
0
                   << ", instance_id=" << print_id(instance_id);
508
0
        {
509
0
            auto load_block_queue = std::make_shared<LoadBlockQueue>(
510
0
                    instance_id, label, txn_id, schema_version, index_size, _all_block_queues_bytes,
511
0
                    result.wait_internal_group_commit_finish, result.group_commit_interval_ms,
512
0
                    result.group_commit_data_bytes);
513
0
            RETURN_IF_ERROR(load_block_queue->create_wal(
514
0
                    _db_id, _table_id, txn_id, label, _exec_env->wal_mgr(),
515
0
                    pipeline_params.fragment.output_sink.olap_table_sink.schema.slot_descs,
516
0
                    be_exe_version));
517
0
            created_load_block_queue = load_block_queue;
518
519
0
            std::unique_lock l(_lock);
520
0
            _load_block_queues.emplace(instance_id, load_block_queue);
521
0
            std::vector<UniqueId> success_load_ids;
522
0
            for (const auto& [id, load_info] : _create_plan_deps) {
523
0
                auto create_dep = std::get<0>(load_info);
524
0
                auto put_dep = std::get<1>(load_info);
525
0
                if (load_block_queue->schema_version == std::get<2>(load_info) &&
526
0
                    load_block_queue->index_size == std::get<3>(load_info)) {
527
0
                    if (load_block_queue->add_load_id(id, put_dep).ok()) {
528
0
                        create_dep->set_ready();
529
0
                        success_load_ids.emplace_back(id);
530
0
                    }
531
0
                } else if (load_block_queue->schema_version > std::get<2>(load_info) ||
532
0
                           (load_block_queue->schema_version == std::get<2>(load_info) &&
533
0
                            load_block_queue->index_size != std::get<3>(load_info))) {
534
                    // schema version mismatch:
535
                    //   1. the schema version of created load block queue is newer than the load request
536
                    //   2. the index size is not equal
537
                    // set ready for the load request to let it fail
538
0
                    create_dep->set_ready();
539
0
                    success_load_ids.emplace_back(id);
540
0
                }
541
0
            }
542
0
            for (const auto& id : success_load_ids) {
543
0
                _create_plan_deps.erase(id);
544
0
            }
545
0
            if (_create_plan_deps.empty()) {
546
0
                _create_plan_start_time_ms = 0;
547
0
            }
548
0
        }
549
0
    }
550
0
    st = _exec_plan_fragment(_db_id, _table_id, label, txn_id, result.pipeline_params);
551
0
    if (!st.ok()) {
552
0
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(mem_tracker);
553
0
        auto finish_st = _finish_group_commit_load(_db_id, _table_id, label, txn_id, instance_id,
554
0
                                                   st, nullptr);
555
0
        if (!finish_st.ok()) {
556
0
            LOG(WARNING) << "finish group commit error, label=" << label
557
0
                         << ", st=" << finish_st.to_string();
558
0
        }
559
0
    }
560
0
    return st;
561
0
}
562
563
Status GroupCommitTable::_finish_group_commit_load(int64_t db_id, int64_t table_id,
564
                                                   const std::string& label, int64_t txn_id,
565
                                                   const TUniqueId& instance_id, Status& status,
566
0
                                                   RuntimeState* state) {
567
0
    Status st;
568
0
    Status result_status;
569
0
    DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.err_status", {
570
0
        status = Status::InternalError("LoadBlockQueue._finish_group_commit_load.err_status");
571
0
    });
572
0
    DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.load_error",
573
0
                    { status = Status::InternalError("load_error"); });
574
0
    if (status.ok()) {
575
0
        DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.commit_error", {
576
0
            status = Status::InternalError("LoadBlockQueue._finish_group_commit_load.commit_error");
577
0
        });
578
        // commit txn
579
0
        TLoadTxnCommitRequest request;
580
        // deprecated and should be removed in 3.1, use token instead
581
0
        request.__set_auth_code(0);
582
0
        request.__set_token(_exec_env->cluster_info()->curr_auth_token);
583
0
        request.__set_db_id(db_id);
584
0
        request.__set_table_id(table_id);
585
0
        request.__set_txnId(txn_id);
586
0
        request.__set_thrift_rpc_timeout_ms(config::txn_commit_rpc_timeout_ms);
587
0
        request.__set_groupCommit(true);
588
0
        request.__set_receiveBytes(state->num_bytes_load_total());
589
0
        if (_exec_env->cluster_info()->backend_id != 0) {
590
0
            request.__set_backendId(_exec_env->cluster_info()->backend_id);
591
0
        } else {
592
0
            LOG(WARNING) << "_exec_env->cluster_info not set backend_id";
593
0
        }
594
0
        if (state) {
595
0
            request.__set_commitInfos(state->tablet_commit_infos());
596
0
        }
597
0
        TLoadTxnCommitResult result;
598
0
        TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
599
0
        int retry_times = 0;
600
0
        while (retry_times < config::mow_stream_load_commit_retry_times) {
601
0
            st = ThriftRpcHelper::rpc<FrontendServiceClient>(
602
0
                    master_addr.hostname, master_addr.port,
603
0
                    [&request, &result](FrontendServiceConnection& client) {
604
0
                        client->loadTxnCommit(result, request);
605
0
                    },
606
0
                    config::txn_commit_rpc_timeout_ms);
607
0
            if (st.ok()) {
608
0
                result_status = Status::create(result.status);
609
                // DELETE_BITMAP_LOCK_ERROR will be retried
610
0
                if (result_status.ok() ||
611
0
                    !result_status.is<ErrorCode::DELETE_BITMAP_LOCK_ERROR>()) {
612
0
                    break;
613
0
                }
614
0
                LOG_WARNING("Failed to commit txn on group commit")
615
0
                        .tag("label", label)
616
0
                        .tag("txn_id", txn_id)
617
0
                        .tag("retry_times", retry_times)
618
0
                        .error(result_status);
619
0
            } else {
620
0
                LOG_WARNING("Failed to commit txn on group commit")
621
0
                        .tag("label", label)
622
0
                        .tag("txn_id", txn_id)
623
0
                        .tag("retry_times", retry_times)
624
0
                        .error(st);
625
0
            }
626
0
            retry_times++;
627
0
        }
628
0
        DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.commit_success_and_rpc_error",
629
0
                        { result_status = Status::InternalError("commit_success_and_rpc_error"); });
630
0
    } else {
631
        // abort txn
632
0
        TLoadTxnRollbackRequest request;
633
        // deprecated and should be removed in 3.1, use token instead
634
0
        request.__set_auth_code(0);
635
0
        request.__set_token(_exec_env->cluster_info()->curr_auth_token);
636
0
        request.__set_db_id(db_id);
637
0
        request.__set_txnId(txn_id);
638
0
        request.__set_reason(status.to_string());
639
0
        TLoadTxnRollbackResult result;
640
0
        TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
641
0
        st = ThriftRpcHelper::rpc<FrontendServiceClient>(
642
0
                master_addr.hostname, master_addr.port,
643
0
                [&request, &result](FrontendServiceConnection& client) {
644
0
                    client->loadTxnRollback(result, request);
645
0
                });
646
0
        if (st.ok()) {
647
0
            result_status = Status::create<false>(result.status);
648
0
        }
649
0
        DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.err_status", {
650
0
            std ::string msg = "abort txn";
651
0
            LOG(INFO) << "debug promise set: " << msg;
652
0
            ExecEnv::GetInstance()->group_commit_mgr()->debug_promise.set_value(
653
0
                    Status ::InternalError(msg));
654
0
        });
655
0
    }
656
0
    std::shared_ptr<LoadBlockQueue> load_block_queue;
657
0
    {
658
0
        std::lock_guard<std::mutex> l(_lock);
659
0
        auto it = _load_block_queues.find(instance_id);
660
0
        if (it != _load_block_queues.end()) {
661
0
            load_block_queue = it->second;
662
0
            if (!status.ok()) {
663
0
                load_block_queue->cancel(status);
664
0
            }
665
            //close wal
666
0
            RETURN_IF_ERROR(load_block_queue->close_wal());
667
            // notify sync mode loads
668
0
            {
669
0
                std::unique_lock l2(load_block_queue->mutex);
670
0
                load_block_queue->process_finish = true;
671
0
                for (auto dep : load_block_queue->dependencies) {
672
0
                    dep->set_always_ready();
673
0
                }
674
0
            }
675
0
        }
676
0
        _load_block_queues.erase(instance_id);
677
0
    }
678
0
    if (!load_block_queue) {
679
0
        LOG(WARNING) << "finish group commit can not find load block queue, label=" << label
680
0
                     << ", txn_id=" << txn_id << ", instance_id=" << print_id(instance_id);
681
0
    }
682
    // status: exec_plan_fragment result
683
    // st: commit txn rpc status
684
    // result_status: commit txn result
685
0
    DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.err_st", {
686
0
        st = Status::InternalError("LoadBlockQueue._finish_group_commit_load.err_st");
687
0
    });
688
0
    if (status.ok() && st.ok() &&
689
0
        (result_status.ok() || result_status.is<ErrorCode::PUBLISH_TIMEOUT>())) {
690
0
        if (!config::group_commit_wait_replay_wal_finish) {
691
0
            auto delete_st = _exec_env->wal_mgr()->delete_wal(table_id, txn_id);
692
0
            if (!delete_st.ok()) {
693
0
                LOG(WARNING) << "fail to delete wal " << txn_id << ", st=" << delete_st.to_string();
694
0
            }
695
0
        }
696
0
    } else {
697
0
        std::string wal_path;
698
0
        RETURN_IF_ERROR(_exec_env->wal_mgr()->get_wal_path(txn_id, wal_path));
699
0
        RETURN_IF_ERROR(_exec_env->wal_mgr()->add_recover_wal(db_id, table_id, txn_id, wal_path));
700
0
    }
701
0
    std::stringstream ss;
702
0
    ss << "finish group commit, db_id=" << db_id << ", table_id=" << table_id << ", label=" << label
703
0
       << ", txn_id=" << txn_id << ", instance_id=" << print_id(instance_id)
704
0
       << ", exec_plan_fragment status=" << status.to_string()
705
0
       << ", commit/abort txn rpc status=" << st.to_string()
706
0
       << ", commit/abort txn status=" << result_status.to_string();
707
0
    if (load_block_queue) {
708
0
        ss << ", this group commit includes " << load_block_queue->group_commit_load_count
709
0
           << " loads, flush because meet "
710
0
           << (load_block_queue->data_size_condition ? "data size " : "time ") << "condition";
711
0
    } else {
712
0
        ss << ", load block queue is missing when finishing group commit";
713
0
    }
714
0
    ss << ", wal space info:" << ExecEnv::GetInstance()->wal_mgr()->get_wal_dirs_info_string();
715
0
    if (state) {
716
0
        if (!state->get_error_log_file_path().empty()) {
717
0
            ss << ", error_url=" << state->get_error_log_file_path();
718
0
        }
719
0
        if (!state->get_first_error_msg().empty()) {
720
0
            ss << ", first_error_msg=" << state->get_first_error_msg();
721
0
        }
722
0
        ss << ", rows=" << state->num_rows_load_success();
723
0
    }
724
0
    LOG(INFO) << ss.str();
725
0
    DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.get_wal_back_pressure_msg", {
726
0
        if (dp->param<int64_t>("table_id", -1) == table_id) {
727
0
            std ::string msg = _exec_env->wal_mgr()->get_wal_dirs_info_string();
728
0
            LOG(INFO) << "table_id" << std::to_string(table_id) << " set debug promise: " << msg;
729
0
            ExecEnv::GetInstance()->group_commit_mgr()->debug_promise.set_value(
730
0
                    Status ::InternalError(msg));
731
0
        }
732
0
    };);
733
0
    return st;
734
0
}
735
736
Status GroupCommitTable::_exec_plan_fragment(int64_t db_id, int64_t table_id,
737
                                             const std::string& label, int64_t txn_id,
738
0
                                             const TPipelineFragmentParams& pipeline_params) {
739
0
    auto finish_cb = [db_id, table_id, label, txn_id, this](RuntimeState* state, Status* status) {
740
0
        DCHECK(state);
741
0
        auto finish_st = _finish_group_commit_load(db_id, table_id, label, txn_id,
742
0
                                                   state->fragment_instance_id(), *status, state);
743
0
        if (!finish_st.ok()) {
744
0
            LOG(WARNING) << "finish group commit error, label=" << label
745
0
                         << ", st=" << finish_st.to_string();
746
0
        }
747
0
    };
748
749
0
    TPipelineFragmentParamsList mocked;
750
0
    return _exec_env->fragment_mgr()->exec_plan_fragment(
751
0
            pipeline_params, QuerySource::GROUP_COMMIT_LOAD, finish_cb, mocked);
752
0
}
753
754
Status GroupCommitTable::get_load_block_queue(const TUniqueId& instance_id,
755
                                              std::shared_ptr<LoadBlockQueue>& load_block_queue,
756
0
                                              std::shared_ptr<Dependency> get_block_dep) {
757
0
    std::unique_lock l(_lock);
758
0
    auto it = _load_block_queues.find(instance_id);
759
0
    if (it == _load_block_queues.end()) {
760
0
        return Status::InternalError("group commit load instance " + print_id(instance_id) +
761
0
                                     " not found");
762
0
    }
763
0
    load_block_queue = it->second;
764
0
    load_block_queue->append_read_dependency(get_block_dep);
765
0
    return Status::OK();
766
0
}
767
768
0
GroupCommitMgr::GroupCommitMgr(ExecEnv* exec_env) : _exec_env(exec_env) {
769
0
    static_cast<void>(ThreadPoolBuilder("GroupCommitThreadPool")
770
0
                              .set_min_threads(1)
771
0
                              .set_max_threads(config::group_commit_insert_threads)
772
0
                              .build(&_thread_pool));
773
0
    _all_block_queues_bytes = std::make_shared<std::atomic_size_t>(0);
774
0
    _group_commit_mem_tracker =
775
0
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::LOAD, "GroupCommit");
776
0
    _create_plan_thread = std::thread(&GroupCommitMgr::_create_plan_worker, this);
777
0
}
778
779
0
GroupCommitMgr::~GroupCommitMgr() {
780
0
    stop();
781
0
    LOG(INFO) << "GroupCommitMgr is destoried";
782
0
}
783
784
0
void GroupCommitMgr::stop() {
785
0
    {
786
0
        std::lock_guard<std::mutex> l(_need_create_plan_lock);
787
0
        if (_stopped) {
788
0
            return;
789
0
        }
790
0
        _stopped = true;
791
0
    }
792
0
    _need_create_plan_cv.notify_all();
793
0
    if (_create_plan_thread.joinable()) {
794
0
        _create_plan_thread.join();
795
0
    }
796
0
    _thread_pool->shutdown();
797
0
    LOG(INFO) << "GroupCommitMgr is stopped";
798
0
}
799
800
0
void GroupCommitMgr::add_need_create_plan_table(int64_t table_id) {
801
0
    {
802
0
        std::lock_guard<std::mutex> l(_need_create_plan_lock);
803
0
        if (_stopped) {
804
0
            return;
805
0
        }
806
0
        _need_create_plan_tables.insert(table_id);
807
0
    }
808
0
    _need_create_plan_cv.notify_one();
809
0
}
810
811
0
void GroupCommitMgr::_create_plan_worker() {
812
0
    SCOPED_INIT_THREAD_CONTEXT();
813
0
    while (true) {
814
0
        std::set<int64_t> need_create_plan_tables;
815
0
        {
816
0
            std::unique_lock<std::mutex> l(_need_create_plan_lock);
817
0
            _need_create_plan_cv.wait(
818
0
                    l, [this] { return _stopped || !_need_create_plan_tables.empty(); });
819
0
            if (_stopped && _need_create_plan_tables.empty()) {
820
0
                return;
821
0
            }
822
0
            need_create_plan_tables.swap(_need_create_plan_tables);
823
0
        }
824
0
        for (const auto table_id : need_create_plan_tables) {
825
0
            std::shared_ptr<GroupCommitTable> group_commit_table;
826
0
            {
827
0
                std::lock_guard<std::mutex> l(_lock);
828
0
                auto it = _table_map.find(table_id);
829
0
                if (it == _table_map.end()) {
830
0
                    continue;
831
0
                }
832
0
                group_commit_table = it->second;
833
0
            }
834
0
            auto st = group_commit_table->submit_create_group_commit_load();
835
0
            if (!st.ok()) {
836
0
                LOG(WARNING) << "submit create group commit load task from worker for table: "
837
0
                             << table_id << ", error: " << st.to_string();
838
0
            }
839
0
        }
840
0
    }
841
0
}
842
843
Status GroupCommitMgr::get_first_block_load_queue(int64_t db_id, int64_t table_id,
844
                                                  int64_t base_schema_version, int64_t index_size,
845
                                                  const UniqueId& load_id,
846
                                                  std::shared_ptr<LoadBlockQueue>& load_block_queue,
847
                                                  int be_exe_version,
848
                                                  std::shared_ptr<Dependency> create_plan_dep,
849
0
                                                  std::shared_ptr<Dependency> put_block_dep) {
850
0
    std::shared_ptr<GroupCommitTable> group_commit_table;
851
0
    {
852
0
        std::lock_guard wlock(_lock);
853
0
        if (_table_map.find(table_id) == _table_map.end()) {
854
0
            _table_map.emplace(table_id, std::make_shared<GroupCommitTable>(
855
0
                                                 _exec_env, _thread_pool.get(), db_id, table_id,
856
0
                                                 _all_block_queues_bytes, this));
857
0
        }
858
0
        group_commit_table = _table_map[table_id];
859
0
    }
860
0
    RETURN_IF_ERROR(group_commit_table->get_first_block_load_queue(
861
0
            table_id, base_schema_version, index_size, load_id, load_block_queue, be_exe_version,
862
0
            create_plan_dep, put_block_dep));
863
0
    return Status::OK();
864
0
}
865
866
Status GroupCommitMgr::get_load_block_queue(int64_t table_id, const TUniqueId& instance_id,
867
                                            std::shared_ptr<LoadBlockQueue>& load_block_queue,
868
0
                                            std::shared_ptr<Dependency> get_block_dep) {
869
0
    std::shared_ptr<GroupCommitTable> group_commit_table;
870
0
    {
871
0
        std::lock_guard<std::mutex> l(_lock);
872
0
        auto it = _table_map.find(table_id);
873
0
        if (it == _table_map.end()) {
874
0
            return Status::NotFound("table_id: " + std::to_string(table_id) +
875
0
                                    ", instance_id: " + print_id(instance_id) + " dose not exist");
876
0
        }
877
0
        group_commit_table = it->second;
878
0
    }
879
0
    return group_commit_table->get_load_block_queue(instance_id, load_block_queue, get_block_dep);
880
0
}
881
882
0
void GroupCommitMgr::remove_load_id(int64_t table_id, const UniqueId& load_id) {
883
0
    std::lock_guard wlock(_lock);
884
0
    if (_table_map.find(table_id) != _table_map.end()) {
885
0
        _table_map.find(table_id)->second->remove_load_id(load_id);
886
0
    }
887
0
}
888
889
Status LoadBlockQueue::create_wal(int64_t db_id, int64_t tb_id, int64_t wal_id,
890
                                  const std::string& import_label, WalManager* wal_manager,
891
0
                                  std::vector<TSlotDescriptor>& slot_desc, int be_exe_version) {
892
0
    std::string real_label = config::group_commit_wait_replay_wal_finish
893
0
                                     ? import_label + "_test_wait"
894
0
                                     : import_label;
895
0
    RETURN_IF_ERROR(ExecEnv::GetInstance()->wal_mgr()->create_wal_path(
896
0
            db_id, tb_id, wal_id, real_label, _wal_base_path, WAL_VERSION));
897
0
    _v_wal_writer = std::make_shared<VWalWriter>(db_id, tb_id, wal_id, real_label, wal_manager,
898
0
                                                 slot_desc, be_exe_version);
899
0
    return _v_wal_writer->init();
900
0
}
901
902
0
Status LoadBlockQueue::close_wal() {
903
0
    if (_v_wal_writer != nullptr) {
904
0
        RETURN_IF_ERROR(_v_wal_writer->close());
905
0
    }
906
0
    return Status::OK();
907
0
}
908
909
0
void LoadBlockQueue::append_dependency(std::shared_ptr<Dependency> finish_dep) {
910
0
    std::lock_guard<std::mutex> lock(mutex);
911
    // If not finished, dependencies should be blocked.
912
0
    if (!process_finish) {
913
0
        finish_dep->block();
914
0
        dependencies.push_back(finish_dep);
915
0
    }
916
0
}
917
918
0
void LoadBlockQueue::append_read_dependency(std::shared_ptr<Dependency> read_dep) {
919
0
    std::lock_guard<std::mutex> lock(mutex);
920
0
    _read_deps.push_back(read_dep);
921
0
}
922
923
0
bool LoadBlockQueue::has_enough_wal_disk_space(size_t estimated_wal_bytes) {
924
0
    DBUG_EXECUTE_IF("LoadBlockQueue.has_enough_wal_disk_space.low_space", { return false; });
925
0
    auto* wal_mgr = ExecEnv::GetInstance()->wal_mgr();
926
0
    size_t available_bytes = 0;
927
0
    {
928
0
        Status st = wal_mgr->get_wal_dir_available_size(_wal_base_path, &available_bytes);
929
0
        if (!st.ok()) {
930
0
            LOG(WARNING) << "get wal dir available size failed, st=" << st.to_string();
931
0
        }
932
0
    }
933
0
    if (estimated_wal_bytes < available_bytes) {
934
0
        Status st =
935
0
                wal_mgr->update_wal_dir_estimated_wal_bytes(_wal_base_path, estimated_wal_bytes, 0);
936
0
        if (!st.ok()) {
937
0
            LOG(WARNING) << "update wal dir estimated_wal_bytes failed, reason: " << st.to_string();
938
0
        }
939
0
        return true;
940
0
    } else {
941
0
        return false;
942
0
    }
943
0
}
944
945
} // namespace doris