Coverage Report

Created: 2026-04-16 21:18

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 "util/client_cache.h"
33
#include "util/debug_points.h"
34
#include "util/thrift_rpc_helper.h"
35
36
namespace doris {
37
38
bvar::Adder<uint64_t> group_commit_block_by_memory_counter("group_commit_block_by_memory_counter");
39
40
0
std::string LoadBlockQueue::_get_load_ids() {
41
0
    std::stringstream ss;
42
0
    ss << "[";
43
0
    for (auto& id : _load_ids_to_write_dep) {
44
0
        ss << id.first.to_string() << ", ";
45
0
    }
46
0
    ss << "]";
47
0
    return ss.str();
48
0
}
49
50
Status LoadBlockQueue::add_block(RuntimeState* runtime_state, std::shared_ptr<Block> block,
51
0
                                 bool write_wal, UniqueId& load_id) {
52
0
    DBUG_EXECUTE_IF("LoadBlockQueue.add_block.failed",
53
0
                    { return Status::InternalError("LoadBlockQueue.add_block.failed"); });
54
0
    std::unique_lock l(mutex);
55
0
    RETURN_IF_ERROR(status);
56
0
    if (UNLIKELY(runtime_state->is_cancelled())) {
57
0
        return runtime_state->cancel_reason();
58
0
    }
59
0
    RETURN_IF_ERROR(status);
60
0
    LOG(INFO) << "query_id: " << print_id(runtime_state->query_id())
61
0
              << ", add block rows=" << block->rows() << ", use group_commit label=" << label;
62
0
    DBUG_EXECUTE_IF("LoadBlockQueue.add_block.block", DBUG_BLOCK);
63
0
    if (block->rows() > 0) {
64
0
        if (!config::group_commit_wait_replay_wal_finish) {
65
0
            _block_queue.emplace_back(block);
66
0
            _data_bytes += block->bytes();
67
0
            size_t before_block_queues_bytes = _all_block_queues_bytes->load();
68
0
            _all_block_queues_bytes->fetch_add(block->bytes(), std::memory_order_relaxed);
69
0
            VLOG_DEBUG << "[Group Commit Debug] (LoadBlockQueue::add_block). "
70
0
                       << "Cur block rows=" << block->rows() << ", bytes=" << block->bytes()
71
0
                       << ". all block queues bytes from " << before_block_queues_bytes << " to  "
72
0
                       << _all_block_queues_bytes->load() << ", queue size=" << _block_queue.size()
73
0
                       << ". txn_id=" << txn_id << ", label=" << label
74
0
                       << ", instance_id=" << load_instance_id << ", load_ids=" << _get_load_ids();
75
0
        }
76
0
        if (write_wal || config::group_commit_wait_replay_wal_finish) {
77
0
            auto st = _v_wal_writer->write_wal(block.get());
78
0
            if (!st.ok()) {
79
0
                _cancel_without_lock(st);
80
0
                return st;
81
0
            }
82
0
        }
83
0
        if (!runtime_state->is_cancelled() && status.ok() &&
84
0
            _all_block_queues_bytes->load(std::memory_order_relaxed) >=
85
0
                    config::group_commit_queue_mem_limit) {
86
0
            group_commit_block_by_memory_counter << 1;
87
0
            DCHECK(_load_ids_to_write_dep.find(load_id) != _load_ids_to_write_dep.end());
88
0
            _load_ids_to_write_dep[load_id]->block();
89
0
            VLOG_DEBUG << "block add_block for load_id=" << load_id
90
0
                       << ", memory=" << _all_block_queues_bytes->load(std::memory_order_relaxed)
91
0
                       << ". inner load_id=" << load_instance_id << ", label=" << label;
92
0
        }
93
0
    }
94
0
    if (!_need_commit) {
95
0
        if (_data_bytes >= _group_commit_data_bytes) {
96
0
            VLOG_DEBUG << "group commit meets commit condition for data size, label=" << label
97
0
                       << ", instance_id=" << load_instance_id << ", data_bytes=" << _data_bytes;
98
0
            _need_commit = true;
99
0
            data_size_condition = true;
100
0
        }
101
0
        if (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() -
102
0
                                                                  _start_time)
103
0
                    .count() >= _group_commit_interval_ms) {
104
0
            VLOG_DEBUG << "group commit meets commit condition for time interval, label=" << label
105
0
                       << ", instance_id=" << load_instance_id << ", data_bytes=" << _data_bytes;
106
0
            _need_commit = true;
107
0
        }
108
0
    }
109
0
    for (auto read_dep : _read_deps) {
110
0
        read_dep->set_ready();
111
0
        VLOG_DEBUG << "set ready for inner load_id=" << load_instance_id;
112
0
    }
113
0
    return Status::OK();
114
0
}
115
116
Status LoadBlockQueue::get_block(RuntimeState* runtime_state, Block* block, bool* find_block,
117
0
                                 bool* eos, std::shared_ptr<Dependency> get_block_dep) {
118
0
    *find_block = false;
119
0
    *eos = false;
120
0
    std::unique_lock l(mutex);
121
0
    if (runtime_state->is_cancelled() || !status.ok()) {
122
0
        auto st = runtime_state->cancel_reason();
123
0
        _cancel_without_lock(st);
124
0
        return status;
125
0
    }
126
0
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
127
0
                            std::chrono::steady_clock::now() - _start_time)
128
0
                            .count();
129
0
    if (!_need_commit && duration >= _group_commit_interval_ms) {
130
0
        _need_commit = true;
131
0
    }
132
0
    if (_block_queue.empty()) {
133
0
        if (_need_commit && duration >= 10 * _group_commit_interval_ms) {
134
0
            auto last_print_duration = std::chrono::duration_cast<std::chrono::milliseconds>(
135
0
                                               std::chrono::steady_clock::now() - _last_print_time)
136
0
                                               .count();
137
0
            if (last_print_duration >= 10000) {
138
0
                _last_print_time = std::chrono::steady_clock::now();
139
0
                LOG(INFO) << "find one group_commit need to commit, txn_id=" << txn_id
140
0
                          << ", label=" << label << ", instance_id=" << load_instance_id
141
0
                          << ", duration=" << duration << ", load_ids=" << _get_load_ids();
142
0
            }
143
0
        }
144
0
        VLOG_DEBUG << "get_block for inner load_id=" << load_instance_id << ", but queue is empty";
145
0
        if (!_need_commit) {
146
0
            get_block_dep->block();
147
0
            VLOG_DEBUG << "block get_block for inner load_id=" << load_instance_id;
148
0
        }
149
0
    } else {
150
0
        const BlockData block_data = _block_queue.front();
151
0
        block->swap(*block_data.block);
152
0
        *find_block = true;
153
0
        _block_queue.pop_front();
154
0
        size_t before_block_queues_bytes = _all_block_queues_bytes->load();
155
0
        _all_block_queues_bytes->fetch_sub(block_data.block_bytes, std::memory_order_relaxed);
156
0
        VLOG_DEBUG << "[Group Commit Debug] (LoadBlockQueue::get_block). "
157
0
                   << "Cur block rows=" << block->rows() << ", bytes=" << block->bytes()
158
0
                   << ". all block queues bytes from " << before_block_queues_bytes << " to  "
159
0
                   << _all_block_queues_bytes->load() << ", queue size=" << _block_queue.size()
160
0
                   << ". txn_id=" << txn_id << ", label=" << label
161
0
                   << ", instance_id=" << load_instance_id << ", load_ids=" << _get_load_ids();
162
0
    }
163
0
    if (_block_queue.empty() && _need_commit && _load_ids_to_write_dep.empty()) {
164
0
        *eos = true;
165
0
    } else {
166
0
        *eos = false;
167
0
    }
168
0
    if (_all_block_queues_bytes->load(std::memory_order_relaxed) <
169
0
        config::group_commit_queue_mem_limit) {
170
0
        for (auto& id : _load_ids_to_write_dep) {
171
0
            id.second->set_ready();
172
0
        }
173
0
        VLOG_DEBUG << "set ready for load_ids=" << _get_load_ids()
174
0
                   << ". inner load_id=" << load_instance_id << ", label=" << label;
175
0
    }
176
0
    return Status::OK();
177
0
}
178
179
0
Status LoadBlockQueue::remove_load_id(const UniqueId& load_id) {
180
0
    std::unique_lock l(mutex);
181
0
    if (_load_ids_to_write_dep.find(load_id) != _load_ids_to_write_dep.end()) {
182
0
        _load_ids_to_write_dep[load_id]->set_always_ready();
183
0
        _load_ids_to_write_dep.erase(load_id);
184
0
        for (auto read_dep : _read_deps) {
185
0
            read_dep->set_ready();
186
0
        }
187
0
        VLOG_DEBUG << "set ready for load_id=" << load_id << ", inner load_id=" << load_instance_id;
188
0
        return Status::OK();
189
0
    }
190
0
    return Status::NotFound<false>("load_id=" + load_id.to_string() +
191
0
                                   " not in block queue, label=" + label);
192
0
}
193
194
0
bool LoadBlockQueue::contain_load_id(const UniqueId& load_id) {
195
0
    std::unique_lock l(mutex);
196
0
    return _load_ids_to_write_dep.find(load_id) != _load_ids_to_write_dep.end();
197
0
}
198
199
Status LoadBlockQueue::add_load_id(const UniqueId& load_id,
200
0
                                   const std::shared_ptr<Dependency> put_block_dep) {
201
0
    std::unique_lock l(mutex);
202
0
    if (_need_commit) {
203
0
        return Status::InternalError<false>("block queue is set need commit, id=" +
204
0
                                            load_instance_id.to_string());
205
0
    }
206
0
    _load_ids_to_write_dep[load_id] = put_block_dep;
207
0
    group_commit_load_count.fetch_add(1);
208
0
    return Status::OK();
209
0
}
210
211
0
void LoadBlockQueue::cancel(const Status& st) {
212
0
    DCHECK(!st.ok());
213
0
    std::unique_lock l(mutex);
214
0
    _cancel_without_lock(st);
215
0
}
216
217
0
void LoadBlockQueue::_cancel_without_lock(const Status& st) {
218
0
    LOG(INFO) << "cancel group_commit, instance_id=" << load_instance_id << ", label=" << label
219
0
              << ", status=" << st.to_string();
220
0
    status =
221
0
            Status::Cancelled("cancel group_commit, label=" + label + ", status=" + st.to_string());
222
0
    size_t before_block_queues_bytes = _all_block_queues_bytes->load();
223
0
    while (!_block_queue.empty()) {
224
0
        const BlockData& block_data = _block_queue.front().block;
225
0
        _all_block_queues_bytes->fetch_sub(block_data.block_bytes, std::memory_order_relaxed);
226
0
        _block_queue.pop_front();
227
0
    }
228
0
    VLOG_DEBUG << "[Group Commit Debug] (LoadBlockQueue::_cancel_without_block). "
229
0
               << "all block queues bytes from " << before_block_queues_bytes << " to "
230
0
               << _all_block_queues_bytes->load() << ", queue size=" << _block_queue.size()
231
0
               << ", txn_id=" << txn_id << ", label=" << label
232
0
               << ", instance_id=" << load_instance_id << ", load_ids=" << _get_load_ids();
233
0
    for (auto& id : _load_ids_to_write_dep) {
234
0
        id.second->set_always_ready();
235
0
    }
236
0
    for (auto read_dep : _read_deps) {
237
0
        read_dep->set_ready();
238
0
    }
239
0
    VLOG_DEBUG << "set ready for load_ids=" << _get_load_ids()
240
0
               << ", inner load_id=" << load_instance_id;
241
0
}
242
243
Status GroupCommitTable::get_first_block_load_queue(
244
        int64_t table_id, int64_t base_schema_version, int64_t index_size, const UniqueId& load_id,
245
        std::shared_ptr<LoadBlockQueue>& load_block_queue, int be_exe_version,
246
        std::shared_ptr<MemTrackerLimiter> mem_tracker, std::shared_ptr<Dependency> create_plan_dep,
247
0
        std::shared_ptr<Dependency> put_block_dep) {
248
0
    DCHECK(table_id == _table_id);
249
0
    std::unique_lock l(_lock);
250
0
    auto try_to_get_matched_queue = [&]() -> Status {
251
0
        for (const auto& [_, inner_block_queue] : _load_block_queues) {
252
0
            if (inner_block_queue->contain_load_id(load_id)) {
253
0
                load_block_queue = inner_block_queue;
254
0
                return Status::OK();
255
0
            }
256
0
        }
257
0
        for (const auto& [_, inner_block_queue] : _load_block_queues) {
258
0
            if (!inner_block_queue->need_commit()) {
259
0
                if (base_schema_version == inner_block_queue->schema_version &&
260
0
                    index_size == inner_block_queue->index_size) {
261
0
                    if (inner_block_queue->add_load_id(load_id, put_block_dep).ok()) {
262
0
                        load_block_queue = inner_block_queue;
263
0
                        return Status::OK();
264
0
                    }
265
0
                } else {
266
0
                    return Status::DataQualityError<false>(
267
0
                            "schema version not match, maybe a schema change is in process. "
268
0
                            "Please retry this load manually.");
269
0
                }
270
0
            }
271
0
        }
272
0
        return Status::InternalError<false>("can not get a block queue for table_id: " +
273
0
                                            std::to_string(_table_id) + _create_plan_failed_reason);
274
0
    };
275
276
0
    if (try_to_get_matched_queue().ok()) {
277
0
        return Status::OK();
278
0
    }
279
0
    create_plan_dep->block();
280
0
    _create_plan_deps.emplace(load_id, std::make_tuple(create_plan_dep, put_block_dep,
281
0
                                                       base_schema_version, index_size));
282
0
    if (!_is_creating_plan_fragment) {
283
0
        _is_creating_plan_fragment = true;
284
0
        RETURN_IF_ERROR(
285
0
                _thread_pool->submit_func([&, be_exe_version, mem_tracker, dep = create_plan_dep] {
286
0
                    Defer defer {[&, dep = dep]() {
287
0
                        std::unique_lock l(_lock);
288
0
                        for (auto it : _create_plan_deps) {
289
0
                            std::get<0>(it.second)->set_ready();
290
0
                        }
291
0
                        _create_plan_deps.clear();
292
0
                        _is_creating_plan_fragment = false;
293
0
                    }};
294
0
                    auto st = _create_group_commit_load(be_exe_version, mem_tracker);
295
0
                    if (!st.ok()) {
296
0
                        LOG(WARNING) << "create group commit load error: " << st.to_string();
297
0
                        _create_plan_failed_reason = ". create group commit load error: " +
298
0
                                                     st.to_string().substr(0, 300);
299
0
                    } else {
300
0
                        _create_plan_failed_reason = "";
301
0
                    }
302
0
                }));
303
0
    }
304
0
    return try_to_get_matched_queue();
305
0
}
306
307
0
void GroupCommitTable::remove_load_id(const UniqueId& load_id) {
308
0
    std::unique_lock l(_lock);
309
0
    if (_create_plan_deps.find(load_id) != _create_plan_deps.end()) {
310
0
        _create_plan_deps.erase(load_id);
311
0
        return;
312
0
    }
313
0
    for (const auto& [_, inner_block_queue] : _load_block_queues) {
314
0
        if (inner_block_queue->remove_load_id(load_id).ok()) {
315
0
            return;
316
0
        }
317
0
    }
318
0
}
319
320
Status GroupCommitTable::_create_group_commit_load(int be_exe_version,
321
0
                                                   std::shared_ptr<MemTrackerLimiter> mem_tracker) {
322
0
    Status st = Status::OK();
323
0
    TStreamLoadPutResult result;
324
0
    std::string label;
325
0
    int64_t txn_id;
326
0
    TUniqueId instance_id;
327
0
    {
328
0
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(mem_tracker);
329
0
        UniqueId load_id = UniqueId::gen_uid();
330
0
        TUniqueId tload_id;
331
0
        tload_id.__set_hi(load_id.hi);
332
0
        tload_id.__set_lo(load_id.lo);
333
0
        std::regex reg("-");
334
0
        label = "group_commit_" + std::regex_replace(load_id.to_string(), reg, "_");
335
0
        std::stringstream ss;
336
0
        ss << "insert into doris_internal_table_id(" << _table_id << ") WITH LABEL " << label
337
0
           << " select * from group_commit(\"table_id\"=\"" << _table_id << "\")";
338
0
        TStreamLoadPutRequest request;
339
0
        request.__set_load_sql(ss.str());
340
0
        request.__set_loadId(tload_id);
341
0
        request.__set_label(label);
342
0
        request.__set_token("group_commit"); // this is a fake, fe not check it now
343
0
        request.__set_max_filter_ratio(1.0);
344
0
        request.__set_strictMode(false);
345
0
        request.__set_partial_update(false);
346
        // this is an internal interface, use admin to pass the auth check
347
0
        request.__set_user("admin");
348
0
        if (_exec_env->cluster_info()->backend_id != 0) {
349
0
            request.__set_backend_id(_exec_env->cluster_info()->backend_id);
350
0
        } else {
351
0
            LOG(WARNING) << "_exec_env->cluster_info not set backend_id";
352
0
        }
353
0
        TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
354
0
        st = ThriftRpcHelper::rpc<FrontendServiceClient>(
355
0
                master_addr.hostname, master_addr.port,
356
0
                [&result, &request](FrontendServiceConnection& client) {
357
0
                    client->streamLoadPut(result, request);
358
0
                },
359
0
                10000L);
360
0
        if (!st.ok()) {
361
0
            LOG(WARNING) << "create group commit load rpc error, st=" << st.to_string();
362
0
            return st;
363
0
        }
364
0
        st = Status::create<false>(result.status);
365
0
        if (st.ok() && !result.__isset.pipeline_params) {
366
0
            st = Status::InternalError("Non-pipeline is disabled!");
367
0
        }
368
0
        if (!st.ok()) {
369
0
            LOG(WARNING) << "create group commit load error, st=" << st.to_string();
370
0
            return st;
371
0
        }
372
0
        auto& pipeline_params = result.pipeline_params;
373
0
        auto schema_version = pipeline_params.fragment.output_sink.olap_table_sink.schema.version;
374
0
        auto index_size =
375
0
                pipeline_params.fragment.output_sink.olap_table_sink.schema.indexes.size();
376
0
        DCHECK(pipeline_params.fragment.output_sink.olap_table_sink.db_id == _db_id);
377
0
        txn_id = pipeline_params.txn_conf.txn_id;
378
0
        DCHECK(pipeline_params.local_params.size() == 1);
379
0
        instance_id = pipeline_params.local_params[0].fragment_instance_id;
380
0
        VLOG_DEBUG << "create plan fragment, db_id=" << _db_id << ", table=" << _table_id
381
0
                   << ", schema version=" << schema_version << ", index size=" << index_size
382
0
                   << ", label=" << label << ", txn_id=" << txn_id
383
0
                   << ", instance_id=" << print_id(instance_id);
384
0
        {
385
0
            auto load_block_queue = std::make_shared<LoadBlockQueue>(
386
0
                    instance_id, label, txn_id, schema_version, index_size, _all_block_queues_bytes,
387
0
                    result.wait_internal_group_commit_finish, result.group_commit_interval_ms,
388
0
                    result.group_commit_data_bytes);
389
0
            RETURN_IF_ERROR(load_block_queue->create_wal(
390
0
                    _db_id, _table_id, txn_id, label, _exec_env->wal_mgr(),
391
0
                    pipeline_params.fragment.output_sink.olap_table_sink.schema.slot_descs,
392
0
                    be_exe_version));
393
394
0
            std::unique_lock l(_lock);
395
0
            _load_block_queues.emplace(instance_id, load_block_queue);
396
0
            std::vector<UniqueId> success_load_ids;
397
0
            for (const auto& [id, load_info] : _create_plan_deps) {
398
0
                auto create_dep = std::get<0>(load_info);
399
0
                auto put_dep = std::get<1>(load_info);
400
0
                if (load_block_queue->schema_version == std::get<2>(load_info) &&
401
0
                    load_block_queue->index_size == std::get<3>(load_info)) {
402
0
                    if (load_block_queue->add_load_id(id, put_dep).ok()) {
403
0
                        create_dep->set_ready();
404
0
                        success_load_ids.emplace_back(id);
405
0
                    }
406
0
                }
407
0
            }
408
0
            for (const auto& id : success_load_ids) {
409
0
                _create_plan_deps.erase(id);
410
0
            }
411
0
        }
412
0
    }
413
0
    st = _exec_plan_fragment(_db_id, _table_id, label, txn_id, result.pipeline_params);
414
0
    if (!st.ok()) {
415
0
        SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(mem_tracker);
416
0
        auto finish_st = _finish_group_commit_load(_db_id, _table_id, label, txn_id, instance_id,
417
0
                                                   st, nullptr);
418
0
        if (!finish_st.ok()) {
419
0
            LOG(WARNING) << "finish group commit error, label=" << label
420
0
                         << ", st=" << finish_st.to_string();
421
0
        }
422
0
    }
423
0
    return st;
424
0
}
425
426
Status GroupCommitTable::_finish_group_commit_load(int64_t db_id, int64_t table_id,
427
                                                   const std::string& label, int64_t txn_id,
428
                                                   const TUniqueId& instance_id, Status& status,
429
0
                                                   RuntimeState* state) {
430
0
    Status st;
431
0
    Status result_status;
432
0
    DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.err_status", {
433
0
        status = Status::InternalError("LoadBlockQueue._finish_group_commit_load.err_status");
434
0
    });
435
0
    DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.load_error",
436
0
                    { status = Status::InternalError("load_error"); });
437
0
    if (status.ok()) {
438
0
        DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.commit_error", {
439
0
            status = Status::InternalError("LoadBlockQueue._finish_group_commit_load.commit_error");
440
0
        });
441
        // commit txn
442
0
        TLoadTxnCommitRequest request;
443
        // deprecated and should be removed in 3.1, use token instead
444
0
        request.__set_auth_code(0);
445
0
        request.__set_token(_exec_env->cluster_info()->curr_auth_token);
446
0
        request.__set_db_id(db_id);
447
0
        request.__set_table_id(table_id);
448
0
        request.__set_txnId(txn_id);
449
0
        request.__set_thrift_rpc_timeout_ms(config::txn_commit_rpc_timeout_ms);
450
0
        request.__set_groupCommit(true);
451
0
        request.__set_receiveBytes(state->num_bytes_load_total());
452
0
        if (_exec_env->cluster_info()->backend_id != 0) {
453
0
            request.__set_backendId(_exec_env->cluster_info()->backend_id);
454
0
        } else {
455
0
            LOG(WARNING) << "_exec_env->cluster_info not set backend_id";
456
0
        }
457
0
        if (state) {
458
0
            request.__set_commitInfos(state->tablet_commit_infos());
459
0
        }
460
0
        TLoadTxnCommitResult result;
461
0
        TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
462
0
        int retry_times = 0;
463
0
        while (retry_times < config::mow_stream_load_commit_retry_times) {
464
0
            st = ThriftRpcHelper::rpc<FrontendServiceClient>(
465
0
                    master_addr.hostname, master_addr.port,
466
0
                    [&request, &result](FrontendServiceConnection& client) {
467
0
                        client->loadTxnCommit(result, request);
468
0
                    },
469
0
                    config::txn_commit_rpc_timeout_ms);
470
0
            result_status = Status::create(result.status);
471
            // DELETE_BITMAP_LOCK_ERROR will be retried
472
0
            if (result_status.ok() || !result_status.is<ErrorCode::DELETE_BITMAP_LOCK_ERROR>()) {
473
0
                break;
474
0
            }
475
0
            LOG_WARNING("Failed to commit txn on group commit")
476
0
                    .tag("label", label)
477
0
                    .tag("txn_id", txn_id)
478
0
                    .tag("retry_times", retry_times)
479
0
                    .error(result_status);
480
0
            retry_times++;
481
0
        }
482
0
        DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.commit_success_and_rpc_error",
483
0
                        { result_status = Status::InternalError("commit_success_and_rpc_error"); });
484
0
    } else {
485
        // abort txn
486
0
        TLoadTxnRollbackRequest request;
487
        // deprecated and should be removed in 3.1, use token instead
488
0
        request.__set_auth_code(0);
489
0
        request.__set_token(_exec_env->cluster_info()->curr_auth_token);
490
0
        request.__set_db_id(db_id);
491
0
        request.__set_txnId(txn_id);
492
0
        request.__set_reason(status.to_string());
493
0
        TLoadTxnRollbackResult result;
494
0
        TNetworkAddress master_addr = _exec_env->cluster_info()->master_fe_addr;
495
0
        st = ThriftRpcHelper::rpc<FrontendServiceClient>(
496
0
                master_addr.hostname, master_addr.port,
497
0
                [&request, &result](FrontendServiceConnection& client) {
498
0
                    client->loadTxnRollback(result, request);
499
0
                });
500
0
        result_status = Status::create<false>(result.status);
501
0
        DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.err_status", {
502
0
            std ::string msg = "abort txn";
503
0
            LOG(INFO) << "debug promise set: " << msg;
504
0
            ExecEnv::GetInstance()->group_commit_mgr()->debug_promise.set_value(
505
0
                    Status ::InternalError(msg));
506
0
        });
507
0
    }
508
0
    std::shared_ptr<LoadBlockQueue> load_block_queue;
509
0
    {
510
0
        std::lock_guard<std::mutex> l(_lock);
511
0
        auto it = _load_block_queues.find(instance_id);
512
0
        if (it != _load_block_queues.end()) {
513
0
            load_block_queue = it->second;
514
0
            if (!status.ok()) {
515
0
                load_block_queue->cancel(status);
516
0
            }
517
            //close wal
518
0
            RETURN_IF_ERROR(load_block_queue->close_wal());
519
            // notify sync mode loads
520
0
            {
521
0
                std::unique_lock l2(load_block_queue->mutex);
522
0
                load_block_queue->process_finish = true;
523
0
                for (auto dep : load_block_queue->dependencies) {
524
0
                    dep->set_always_ready();
525
0
                }
526
0
            }
527
0
        }
528
0
        _load_block_queues.erase(instance_id);
529
0
    }
530
    // status: exec_plan_fragment result
531
    // st: commit txn rpc status
532
    // result_status: commit txn result
533
0
    DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.err_st", {
534
0
        st = Status::InternalError("LoadBlockQueue._finish_group_commit_load.err_st");
535
0
    });
536
0
    if (status.ok() && st.ok() &&
537
0
        (result_status.ok() || result_status.is<ErrorCode::PUBLISH_TIMEOUT>())) {
538
0
        if (!config::group_commit_wait_replay_wal_finish) {
539
0
            auto delete_st = _exec_env->wal_mgr()->delete_wal(table_id, txn_id);
540
0
            if (!delete_st.ok()) {
541
0
                LOG(WARNING) << "fail to delete wal " << txn_id << ", st=" << delete_st.to_string();
542
0
            }
543
0
        }
544
0
    } else {
545
0
        std::string wal_path;
546
0
        RETURN_IF_ERROR(_exec_env->wal_mgr()->get_wal_path(txn_id, wal_path));
547
0
        RETURN_IF_ERROR(_exec_env->wal_mgr()->add_recover_wal(db_id, table_id, txn_id, wal_path));
548
0
    }
549
0
    std::stringstream ss;
550
0
    ss << "finish group commit, db_id=" << db_id << ", table_id=" << table_id << ", label=" << label
551
0
       << ", txn_id=" << txn_id << ", instance_id=" << print_id(instance_id)
552
0
       << ", exec_plan_fragment status=" << status.to_string()
553
0
       << ", commit/abort txn rpc status=" << st.to_string()
554
0
       << ", commit/abort txn status=" << result_status.to_string()
555
0
       << ", this group commit includes " << load_block_queue->group_commit_load_count << " loads"
556
0
       << ", flush because meet "
557
0
       << (load_block_queue->data_size_condition ? "data size " : "time ") << "condition"
558
0
       << ", wal space info:" << ExecEnv::GetInstance()->wal_mgr()->get_wal_dirs_info_string();
559
0
    if (state) {
560
0
        if (!state->get_error_log_file_path().empty()) {
561
0
            ss << ", error_url=" << state->get_error_log_file_path();
562
0
        }
563
0
        if (!state->get_first_error_msg().empty()) {
564
0
            ss << ", first_error_msg=" << state->get_first_error_msg();
565
0
        }
566
0
        ss << ", rows=" << state->num_rows_load_success();
567
0
    }
568
0
    LOG(INFO) << ss.str();
569
0
    DBUG_EXECUTE_IF("LoadBlockQueue._finish_group_commit_load.get_wal_back_pressure_msg", {
570
0
        if (dp->param<int64_t>("table_id", -1) == table_id) {
571
0
            std ::string msg = _exec_env->wal_mgr()->get_wal_dirs_info_string();
572
0
            LOG(INFO) << "table_id" << std::to_string(table_id) << " set debug promise: " << msg;
573
0
            ExecEnv::GetInstance()->group_commit_mgr()->debug_promise.set_value(
574
0
                    Status ::InternalError(msg));
575
0
        }
576
0
    };);
577
0
    return st;
578
0
}
579
580
Status GroupCommitTable::_exec_plan_fragment(int64_t db_id, int64_t table_id,
581
                                             const std::string& label, int64_t txn_id,
582
0
                                             const TPipelineFragmentParams& pipeline_params) {
583
0
    auto finish_cb = [db_id, table_id, label, txn_id, this](RuntimeState* state, Status* status) {
584
0
        DCHECK(state);
585
0
        auto finish_st = _finish_group_commit_load(db_id, table_id, label, txn_id,
586
0
                                                   state->fragment_instance_id(), *status, state);
587
0
        if (!finish_st.ok()) {
588
0
            LOG(WARNING) << "finish group commit error, label=" << label
589
0
                         << ", st=" << finish_st.to_string();
590
0
        }
591
0
    };
592
593
0
    TPipelineFragmentParamsList mocked;
594
0
    return _exec_env->fragment_mgr()->exec_plan_fragment(
595
0
            pipeline_params, QuerySource::GROUP_COMMIT_LOAD, finish_cb, mocked);
596
0
}
597
598
Status GroupCommitTable::get_load_block_queue(const TUniqueId& instance_id,
599
                                              std::shared_ptr<LoadBlockQueue>& load_block_queue,
600
0
                                              std::shared_ptr<Dependency> get_block_dep) {
601
0
    std::unique_lock l(_lock);
602
0
    auto it = _load_block_queues.find(instance_id);
603
0
    if (it == _load_block_queues.end()) {
604
0
        return Status::InternalError("group commit load instance " + print_id(instance_id) +
605
0
                                     " not found");
606
0
    }
607
0
    load_block_queue = it->second;
608
0
    load_block_queue->append_read_dependency(get_block_dep);
609
0
    return Status::OK();
610
0
}
611
612
0
GroupCommitMgr::GroupCommitMgr(ExecEnv* exec_env) : _exec_env(exec_env) {
613
0
    static_cast<void>(ThreadPoolBuilder("GroupCommitThreadPool")
614
0
                              .set_min_threads(1)
615
0
                              .set_max_threads(config::group_commit_insert_threads)
616
0
                              .build(&_thread_pool));
617
0
    _all_block_queues_bytes = std::make_shared<std::atomic_size_t>(0);
618
0
}
619
620
0
GroupCommitMgr::~GroupCommitMgr() {
621
0
    LOG(INFO) << "GroupCommitMgr is destoried";
622
0
}
623
624
0
void GroupCommitMgr::stop() {
625
0
    _thread_pool->shutdown();
626
0
    LOG(INFO) << "GroupCommitMgr is stopped";
627
0
}
628
629
Status GroupCommitMgr::get_first_block_load_queue(
630
        int64_t db_id, int64_t table_id, int64_t base_schema_version, int64_t index_size,
631
        const UniqueId& load_id, std::shared_ptr<LoadBlockQueue>& load_block_queue,
632
        int be_exe_version, std::shared_ptr<MemTrackerLimiter> mem_tracker,
633
0
        std::shared_ptr<Dependency> create_plan_dep, std::shared_ptr<Dependency> put_block_dep) {
634
0
    std::shared_ptr<GroupCommitTable> group_commit_table;
635
0
    {
636
0
        std::lock_guard wlock(_lock);
637
0
        if (_table_map.find(table_id) == _table_map.end()) {
638
0
            _table_map.emplace(table_id, std::make_shared<GroupCommitTable>(
639
0
                                                 _exec_env, _thread_pool.get(), db_id, table_id,
640
0
                                                 _all_block_queues_bytes));
641
0
        }
642
0
        group_commit_table = _table_map[table_id];
643
0
    }
644
0
    RETURN_IF_ERROR(group_commit_table->get_first_block_load_queue(
645
0
            table_id, base_schema_version, index_size, load_id, load_block_queue, be_exe_version,
646
0
            mem_tracker, create_plan_dep, put_block_dep));
647
0
    return Status::OK();
648
0
}
649
650
Status GroupCommitMgr::get_load_block_queue(int64_t table_id, const TUniqueId& instance_id,
651
                                            std::shared_ptr<LoadBlockQueue>& load_block_queue,
652
0
                                            std::shared_ptr<Dependency> get_block_dep) {
653
0
    std::shared_ptr<GroupCommitTable> group_commit_table;
654
0
    {
655
0
        std::lock_guard<std::mutex> l(_lock);
656
0
        auto it = _table_map.find(table_id);
657
0
        if (it == _table_map.end()) {
658
0
            return Status::NotFound("table_id: " + std::to_string(table_id) +
659
0
                                    ", instance_id: " + print_id(instance_id) + " dose not exist");
660
0
        }
661
0
        group_commit_table = it->second;
662
0
    }
663
0
    return group_commit_table->get_load_block_queue(instance_id, load_block_queue, get_block_dep);
664
0
}
665
666
0
void GroupCommitMgr::remove_load_id(int64_t table_id, const UniqueId& load_id) {
667
0
    std::lock_guard wlock(_lock);
668
0
    if (_table_map.find(table_id) != _table_map.end()) {
669
0
        _table_map.find(table_id)->second->remove_load_id(load_id);
670
0
    }
671
0
}
672
673
Status LoadBlockQueue::create_wal(int64_t db_id, int64_t tb_id, int64_t wal_id,
674
                                  const std::string& import_label, WalManager* wal_manager,
675
0
                                  std::vector<TSlotDescriptor>& slot_desc, int be_exe_version) {
676
0
    std::string real_label = config::group_commit_wait_replay_wal_finish
677
0
                                     ? import_label + "_test_wait"
678
0
                                     : import_label;
679
0
    RETURN_IF_ERROR(ExecEnv::GetInstance()->wal_mgr()->create_wal_path(
680
0
            db_id, tb_id, wal_id, real_label, _wal_base_path, WAL_VERSION));
681
0
    _v_wal_writer = std::make_shared<VWalWriter>(db_id, tb_id, wal_id, real_label, wal_manager,
682
0
                                                 slot_desc, be_exe_version);
683
0
    return _v_wal_writer->init();
684
0
}
685
686
0
Status LoadBlockQueue::close_wal() {
687
0
    if (_v_wal_writer != nullptr) {
688
0
        RETURN_IF_ERROR(_v_wal_writer->close());
689
0
    }
690
0
    return Status::OK();
691
0
}
692
693
0
void LoadBlockQueue::append_dependency(std::shared_ptr<Dependency> finish_dep) {
694
0
    std::lock_guard<std::mutex> lock(mutex);
695
    // If not finished, dependencies should be blocked.
696
0
    if (!process_finish) {
697
0
        finish_dep->block();
698
0
        dependencies.push_back(finish_dep);
699
0
    }
700
0
}
701
702
0
void LoadBlockQueue::append_read_dependency(std::shared_ptr<Dependency> read_dep) {
703
0
    std::lock_guard<std::mutex> lock(mutex);
704
0
    _read_deps.push_back(read_dep);
705
0
}
706
707
0
bool LoadBlockQueue::has_enough_wal_disk_space(size_t estimated_wal_bytes) {
708
0
    DBUG_EXECUTE_IF("LoadBlockQueue.has_enough_wal_disk_space.low_space", { return false; });
709
0
    auto* wal_mgr = ExecEnv::GetInstance()->wal_mgr();
710
0
    size_t available_bytes = 0;
711
0
    {
712
0
        Status st = wal_mgr->get_wal_dir_available_size(_wal_base_path, &available_bytes);
713
0
        if (!st.ok()) {
714
0
            LOG(WARNING) << "get wal dir available size failed, st=" << st.to_string();
715
0
        }
716
0
    }
717
0
    if (estimated_wal_bytes < available_bytes) {
718
0
        Status st =
719
0
                wal_mgr->update_wal_dir_estimated_wal_bytes(_wal_base_path, estimated_wal_bytes, 0);
720
0
        if (!st.ok()) {
721
0
            LOG(WARNING) << "update wal dir estimated_wal_bytes failed, reason: " << st.to_string();
722
0
        }
723
0
        return true;
724
0
    } else {
725
0
        return false;
726
0
    }
727
0
}
728
729
} // namespace doris