Coverage Report

Created: 2026-06-10 19:55

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