Coverage Report

Created: 2026-05-27 08:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/sink/writer/vtablet_writer.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exec/sink/writer/vtablet_writer.h"
19
20
#include <brpc/http_method.h>
21
#include <bthread/bthread.h>
22
#include <fmt/format.h>
23
#include <gen_cpp/DataSinks_types.h>
24
#include <gen_cpp/Descriptors_types.h>
25
#include <gen_cpp/Exprs_types.h>
26
#include <gen_cpp/FrontendService.h>
27
#include <gen_cpp/FrontendService_types.h>
28
#include <gen_cpp/HeartbeatService_types.h>
29
#include <gen_cpp/Metrics_types.h>
30
#include <gen_cpp/Types_types.h>
31
#include <gen_cpp/data.pb.h>
32
#include <gen_cpp/internal_service.pb.h>
33
#include <glog/logging.h>
34
#include <google/protobuf/stubs/common.h>
35
#include <sys/param.h>
36
37
#include <algorithm>
38
#include <initializer_list>
39
#include <memory>
40
#include <mutex>
41
#include <sstream>
42
#include <string>
43
#include <unordered_map>
44
#include <utility>
45
#include <vector>
46
47
#include "cloud/config.h"
48
#include "common/config.h"
49
#include "core/data_type/data_type.h"
50
#include "cpp/sync_point.h"
51
#include "exec/sink/vrow_distribution.h"
52
#include "exprs/vexpr_fwd.h"
53
#include "runtime/runtime_profile.h"
54
55
#ifdef DEBUG
56
#include <unordered_set>
57
#endif
58
59
#include "common/compiler_util.h" // IWYU pragma: keep
60
#include "common/logging.h"
61
#include "common/metrics/doris_metrics.h"
62
#include "common/object_pool.h"
63
#include "common/signal_handler.h"
64
#include "common/status.h"
65
#include "core/block/block.h"
66
#include "core/column/column.h"
67
#include "core/column/column_const.h"
68
#include "core/data_type/data_type_nullable.h"
69
#include "exec/sink/vtablet_block_convertor.h"
70
#include "exec/sink/vtablet_finder.h"
71
#include "exprs/vexpr.h"
72
#include "runtime/descriptors.h"
73
#include "runtime/exec_env.h"
74
#include "runtime/memory/memory_reclamation.h"
75
#include "runtime/query_context.h"
76
#include "runtime/runtime_state.h"
77
#include "runtime/thread_context.h"
78
#include "service/backend_options.h"
79
#include "storage/tablet_info.h"
80
#include "util/brpc_closure.h"
81
#include "util/debug_points.h"
82
#include "util/defer_op.h"
83
#include "util/mem_info.h"
84
#include "util/network_util.h"
85
#include "util/proto_util.h"
86
#include "util/threadpool.h"
87
#include "util/thrift_rpc_helper.h"
88
#include "util/thrift_util.h"
89
#include "util/time.h"
90
#include "util/uid_util.h"
91
92
namespace doris {
93
class TExpr;
94
95
bvar::Adder<int64_t> g_sink_write_bytes;
96
bvar::PerSecond<bvar::Adder<int64_t>> g_sink_write_bytes_per_second("sink_throughput_byte",
97
                                                                    &g_sink_write_bytes, 60);
98
bvar::Adder<int64_t> g_sink_write_rows;
99
bvar::PerSecond<bvar::Adder<int64_t>> g_sink_write_rows_per_second("sink_throughput_row",
100
                                                                   &g_sink_write_rows, 60);
101
bvar::Adder<int64_t> g_sink_load_back_pressure_version_time_ms(
102
        "load_back_pressure_version_time_ms");
103
104
Status IndexChannel::init(RuntimeState* state, const std::vector<TTabletWithPartition>& tablets,
105
45.6k
                          bool incremental) {
106
45.6k
    SCOPED_CONSUME_MEM_TRACKER(_index_channel_tracker.get());
107
363k
    for (const auto& tablet : tablets) {
108
        // First find the location BEs of this tablet
109
363k
        auto* tablet_locations = _parent->_location->find_tablet(tablet.tablet_id);
110
363k
        if (tablet_locations == nullptr) {
111
0
            return Status::InternalError("unknown tablet, tablet_id={}", tablet.tablet_id);
112
0
        }
113
363k
        std::vector<std::shared_ptr<VNodeChannel>> channels;
114
        // For tablet, deal with its' all replica (in some node).
115
364k
        for (auto& replica_node_id : tablet_locations->node_ids) {
116
364k
            std::shared_ptr<VNodeChannel> channel;
117
364k
            auto it = _node_channels.find(replica_node_id);
118
            // when we prepare for TableSink or incremental open tablet, we need init
119
364k
            if (it == _node_channels.end()) {
120
                // NodeChannel is not added to the _parent->_pool.
121
                // Because the deconstruction of NodeChannel may take a long time to wait rpc finish.
122
                // but the ObjectPool will hold a spin lock to delete objects.
123
46.5k
                channel =
124
46.5k
                        std::make_shared<VNodeChannel>(_parent, this, replica_node_id, incremental);
125
46.5k
                _node_channels.emplace(replica_node_id, channel);
126
                // incremental opened new node. when close we have use two-stage close.
127
46.5k
                if (incremental) {
128
0
                    _has_inc_node = true;
129
0
                }
130
46.5k
                VLOG_CRITICAL << "init new node for instance " << _parent->_sender_id
131
901
                              << ", node id:" << replica_node_id << ", incremantal:" << incremental;
132
317k
            } else {
133
317k
                channel = it->second;
134
317k
            }
135
364k
            channel->add_tablet(tablet);
136
364k
            if (_parent->_write_single_replica) {
137
0
                auto* slave_location = _parent->_slave_location->find_tablet(tablet.tablet_id);
138
0
                if (slave_location != nullptr) {
139
0
                    channel->add_slave_tablet_nodes(tablet.tablet_id, slave_location->node_ids);
140
0
                }
141
0
            }
142
364k
            channels.push_back(channel);
143
364k
            _tablets_by_channel[replica_node_id].insert(tablet.tablet_id);
144
364k
        }
145
363k
        _channels_by_tablet.emplace(tablet.tablet_id, std::move(channels));
146
363k
    }
147
46.5k
    for (auto& it : _node_channels) {
148
46.5k
        RETURN_IF_ERROR(it.second->init(state));
149
46.5k
    }
150
45.6k
    if (_where_clause != nullptr) {
151
33
        RETURN_IF_ERROR(_where_clause->prepare(state, *_parent->_output_row_desc));
152
33
        RETURN_IF_ERROR(_where_clause->open(state));
153
33
    }
154
155
45.6k
    return Status::OK();
156
45.6k
}
157
158
void IndexChannel::mark_as_failed(const VNodeChannel* node_channel, const std::string& err,
159
48
                                  int64_t tablet_id) {
160
48
    DCHECK(node_channel != nullptr);
161
48
    LOG(INFO) << "mark node_id:" << node_channel->channel_info() << " tablet_id: " << tablet_id
162
48
              << " as failed, err: " << err;
163
48
    auto node_id = node_channel->node_id();
164
48
    const auto& it = _tablets_by_channel.find(node_id);
165
48
    if (it == _tablets_by_channel.end()) {
166
0
        return;
167
0
    }
168
169
48
    {
170
48
        std::lock_guard<std::mutex> l(_fail_lock);
171
48
        if (tablet_id == -1) {
172
144
            for (const auto the_tablet_id : it->second) {
173
144
                _failed_channels[the_tablet_id].insert(node_id);
174
144
                _failed_channels_msgs.emplace(the_tablet_id,
175
144
                                              err + ", host: " + node_channel->host());
176
144
                if (_failed_channels[the_tablet_id].size() > _max_failed_replicas(the_tablet_id)) {
177
144
                    _intolerable_failure_status = Status::Error<ErrorCode::INTERNAL_ERROR, false>(
178
144
                            _failed_channels_msgs[the_tablet_id]);
179
144
                }
180
144
            }
181
48
        } else {
182
0
            _failed_channels[tablet_id].insert(node_id);
183
0
            _failed_channels_msgs.emplace(tablet_id, err + ", host: " + node_channel->host());
184
0
            if (_failed_channels[tablet_id].size() > _max_failed_replicas(tablet_id)) {
185
0
                _intolerable_failure_status = Status::Error<ErrorCode::INTERNAL_ERROR, false>(
186
0
                        _failed_channels_msgs[tablet_id]);
187
0
            }
188
0
        }
189
48
    }
190
48
}
191
192
144
int IndexChannel::_max_failed_replicas(int64_t tablet_id) {
193
144
    auto [total_replicas_num, load_required_replicas_num] =
194
144
            _parent->_tablet_replica_info[tablet_id];
195
144
    int max_failed_replicas = total_replicas_num == 0
196
144
                                      ? (_parent->_num_replicas - 1) / 2
197
144
                                      : total_replicas_num - load_required_replicas_num;
198
144
    return max_failed_replicas;
199
144
}
200
201
1.17M
int IndexChannel::_load_required_replicas_num(int64_t tablet_id) {
202
1.17M
    auto [total_replicas_num, load_required_replicas_num] =
203
1.17M
            _parent->_tablet_replica_info[tablet_id];
204
1.17M
    if (total_replicas_num == 0) {
205
0
        return (_parent->_num_replicas + 1) / 2;
206
0
    }
207
1.17M
    return load_required_replicas_num;
208
1.17M
}
209
210
136k
Status IndexChannel::check_intolerable_failure() {
211
136k
    std::lock_guard<std::mutex> l(_fail_lock);
212
136k
    return _intolerable_failure_status;
213
136k
}
214
215
46.5k
void IndexChannel::set_error_tablet_in_state(RuntimeState* state) {
216
46.5k
    std::vector<TErrorTabletInfo> error_tablet_infos;
217
218
46.5k
    {
219
46.5k
        std::lock_guard<std::mutex> l(_fail_lock);
220
46.5k
        for (const auto& it : _failed_channels_msgs) {
221
0
            TErrorTabletInfo error_info;
222
0
            error_info.__set_tabletId(it.first);
223
0
            error_info.__set_msg(it.second);
224
0
            error_tablet_infos.emplace_back(error_info);
225
0
        }
226
46.5k
    }
227
46.5k
    state->add_error_tablet_infos(error_tablet_infos);
228
46.5k
}
229
230
void IndexChannel::set_tablets_received_rows(
231
46.5k
        const std::vector<std::pair<int64_t, int64_t>>& tablets_received_rows, int64_t node_id) {
232
190k
    for (const auto& [tablet_id, rows_num] : tablets_received_rows) {
233
190k
        _tablets_received_rows[tablet_id].emplace_back(node_id, rows_num);
234
190k
    }
235
46.5k
}
236
237
void IndexChannel::set_tablets_filtered_rows(
238
46.5k
        const std::vector<std::pair<int64_t, int64_t>>& tablets_filtered_rows, int64_t node_id) {
239
190k
    for (const auto& [tablet_id, rows_num] : tablets_filtered_rows) {
240
190k
        _tablets_filtered_rows[tablet_id].emplace_back(node_id, rows_num);
241
190k
    }
242
46.5k
}
243
244
0
Status IndexChannel::check_tablet_received_rows_consistency() {
245
0
    for (auto& tablet : _tablets_received_rows) {
246
0
        for (size_t i = 0; i < tablet.second.size(); i++) {
247
0
            VLOG_NOTICE << "check_tablet_received_rows_consistency, load_id: " << _parent->_load_id
248
0
                        << ", txn_id: " << std::to_string(_parent->_txn_id)
249
0
                        << ", tablet_id: " << tablet.first
250
0
                        << ", node_id: " << tablet.second[i].first
251
0
                        << ", rows_num: " << tablet.second[i].second;
252
0
            if (i == 0) {
253
0
                continue;
254
0
            }
255
0
            if (tablet.second[i].second != tablet.second[0].second) {
256
0
                return Status::InternalError(
257
0
                        "rows num written by multi replicas doest't match, load_id={}, txn_id={}, "
258
0
                        "tablt_id={}, node_id={}, rows_num={}, node_id={}, rows_num={}",
259
0
                        print_id(_parent->_load_id), _parent->_txn_id, tablet.first,
260
0
                        tablet.second[i].first, tablet.second[i].second, tablet.second[0].first,
261
0
                        tablet.second[0].second);
262
0
            }
263
0
        }
264
0
    }
265
0
    return Status::OK();
266
0
}
267
268
62
Status IndexChannel::check_tablet_filtered_rows_consistency() {
269
95
    for (auto& tablet : _tablets_filtered_rows) {
270
190
        for (size_t i = 0; i < tablet.second.size(); i++) {
271
95
            VLOG_NOTICE << "check_tablet_filtered_rows_consistency, load_id: " << _parent->_load_id
272
0
                        << ", txn_id: " << std::to_string(_parent->_txn_id)
273
0
                        << ", tablet_id: " << tablet.first
274
0
                        << ", node_id: " << tablet.second[i].first
275
0
                        << ", rows_num: " << tablet.second[i].second;
276
95
            if (i == 0) {
277
95
                continue;
278
95
            }
279
0
            if (tablet.second[i].second != tablet.second[0].second) {
280
0
                return Status::InternalError(
281
0
                        "rows num filtered by multi replicas doest't match, load_id={}, txn_id={}, "
282
0
                        "tablt_id={}, node_id={}, rows_num={}, node_id={}, rows_num={}",
283
0
                        print_id(_parent->_load_id), _parent->_txn_id, tablet.first,
284
0
                        tablet.second[i].first, tablet.second[i].second, tablet.second[0].first,
285
0
                        tablet.second[0].second);
286
0
            }
287
0
        }
288
95
    }
289
62
    return Status::OK();
290
62
}
291
292
static Status cancel_channel_and_check_intolerable_failure(Status status,
293
                                                           const std::string& err_msg,
294
48
                                                           IndexChannel& ich, VNodeChannel& nch) {
295
48
    LOG(WARNING) << nch.channel_info() << ", close channel failed, err: " << err_msg;
296
48
    ich.mark_as_failed(&nch, err_msg, -1);
297
    // cancel the node channel in best effort
298
48
    nch.cancel(err_msg);
299
300
    // check if index has intolerable failure
301
48
    if (Status index_st = ich.check_intolerable_failure(); !index_st.ok()) {
302
48
        status = std::move(index_st);
303
48
    } else if (Status receive_st = ich.check_tablet_received_rows_consistency(); !receive_st.ok()) {
304
0
        status = std::move(receive_st);
305
0
    } else if (Status filter_st = ich.check_tablet_filtered_rows_consistency(); !filter_st.ok()) {
306
0
        status = std::move(filter_st);
307
0
    }
308
48
    return status;
309
48
}
310
311
Status IndexChannel::close_wait(
312
        RuntimeState* state, WriterStats* writer_stats,
313
        std::unordered_map<int64_t, AddBatchCounter>* node_add_batch_counter_map,
314
        std::unordered_set<int64_t> unfinished_node_channel_ids,
315
46.6k
        bool need_wait_after_quorum_success) {
316
46.6k
    DBUG_EXECUTE_IF("IndexChannel.close_wait.timeout",
317
46.6k
                    { return Status::TimedOut("injected timeout"); });
318
46.6k
    Status status = Status::OK();
319
    // 1. wait quorum success
320
46.6k
    std::unordered_set<int64_t> need_finish_tablets;
321
46.6k
    auto partition_ids = _parent->_tablet_finder->partition_ids();
322
61.1k
    for (const auto& part : _parent->_vpartition->get_partitions()) {
323
61.1k
        if (partition_ids.contains(part->id)) {
324
52.0k
            for (const auto& index : part->indexes) {
325
274k
                for (const auto& tablet_id : index.tablets) {
326
274k
                    need_finish_tablets.insert(tablet_id);
327
274k
                }
328
52.0k
            }
329
35.4k
        }
330
61.1k
    }
331
1.03M
    while (true) {
332
1.03M
        RETURN_IF_ERROR(check_each_node_channel_close(
333
1.03M
                &unfinished_node_channel_ids, node_add_batch_counter_map, writer_stats, status));
334
1.03M
        bool quorum_success = _quorum_success(unfinished_node_channel_ids, need_finish_tablets);
335
1.03M
        if (unfinished_node_channel_ids.empty() || quorum_success) {
336
46.5k
            LOG(INFO) << "quorum_success: " << quorum_success
337
46.5k
                      << ", is all finished: " << unfinished_node_channel_ids.empty()
338
46.5k
                      << ", txn_id: " << _parent->_txn_id
339
46.5k
                      << ", load_id: " << print_id(_parent->_load_id);
340
46.5k
            break;
341
46.5k
        }
342
991k
        bthread_usleep(1000 * 10);
343
991k
    }
344
345
    // 2. wait for all node channel to complete as much as possible
346
46.6k
    if (!unfinished_node_channel_ids.empty() && need_wait_after_quorum_success) {
347
0
        int64_t arrival_quorum_success_time = UnixMillis();
348
0
        int64_t max_wait_time_ms = _calc_max_wait_time_ms(unfinished_node_channel_ids);
349
0
        while (true) {
350
0
            RETURN_IF_ERROR(check_each_node_channel_close(&unfinished_node_channel_ids,
351
0
                                                          node_add_batch_counter_map, writer_stats,
352
0
                                                          status));
353
0
            if (unfinished_node_channel_ids.empty()) {
354
0
                break;
355
0
            }
356
0
            int64_t elapsed_ms = UnixMillis() - arrival_quorum_success_time;
357
0
            if (elapsed_ms > max_wait_time_ms ||
358
0
                _parent->_load_channel_timeout_s - elapsed_ms / 1000 <
359
0
                        config::quorum_success_remaining_timeout_seconds) {
360
                // cancel unfinished node channel
361
0
                std::stringstream unfinished_node_channel_host_str;
362
0
                for (auto& it : unfinished_node_channel_ids) {
363
0
                    unfinished_node_channel_host_str << _node_channels[it]->host() << ",";
364
0
                    _node_channels[it]->cancel("timeout");
365
0
                }
366
0
                LOG(WARNING) << "reach max wait time, max_wait_time_ms: " << max_wait_time_ms
367
0
                             << ", cancel unfinished node channel and finish close"
368
0
                             << ", load id: " << print_id(_parent->_load_id)
369
0
                             << ", txn_id: " << _parent->_txn_id << ", unfinished node channel: "
370
0
                             << unfinished_node_channel_host_str.str();
371
0
                break;
372
0
            }
373
0
            bthread_usleep(1000 * 10);
374
0
        }
375
0
    }
376
46.6k
    return status;
377
46.6k
}
378
379
Status IndexChannel::check_each_node_channel_close(
380
        std::unordered_set<int64_t>* unfinished_node_channel_ids,
381
        std::unordered_map<int64_t, AddBatchCounter>* node_add_batch_counter_map,
382
1.03M
        WriterStats* writer_stats, Status status) {
383
1.03M
    Status final_status = Status::OK();
384
1.03M
    for (auto& it : _node_channels) {
385
1.03M
        std::shared_ptr<VNodeChannel> node_channel = it.second;
386
        // If the node channel is not in the unfinished_node_channel_ids,
387
        // it means the node channel is already closed.
388
1.03M
        if (!unfinished_node_channel_ids->contains(it.first)) {
389
0
            continue;
390
0
        }
391
1.03M
        bool node_channel_closed = false;
392
1.03M
        auto close_status = it.second->close_wait(_parent->_state, &node_channel_closed);
393
1.03M
        if (node_channel_closed) {
394
46.6k
            close_status = it.second->after_close_handle(_parent->_state, writer_stats,
395
46.6k
                                                         node_add_batch_counter_map);
396
46.6k
            unfinished_node_channel_ids->erase(it.first);
397
46.6k
        }
398
1.03M
        DBUG_EXECUTE_IF("IndexChannel.check_each_node_channel_close.close_status_not_ok",
399
1.03M
                        { close_status = Status::InternalError("injected close status not ok"); });
400
1.03M
        if (!close_status.ok()) {
401
48
            final_status = cancel_channel_and_check_intolerable_failure(
402
48
                    std::move(final_status), close_status.to_string(), *this, *it.second);
403
48
        }
404
1.03M
    }
405
406
1.03M
    return final_status;
407
1.03M
}
408
409
bool IndexChannel::_quorum_success(const std::unordered_set<int64_t>& unfinished_node_channel_ids,
410
1.03M
                                   const std::unordered_set<int64_t>& need_finish_tablets) {
411
1.03M
    if (!config::enable_quorum_success_write) {
412
0
        return false;
413
0
    }
414
1.03M
    if (need_finish_tablets.empty()) [[unlikely]] {
415
28.9k
        return false;
416
28.9k
    }
417
418
    // 1. collect all write tablets and finished tablets
419
1.00M
    std::unordered_map<int64_t, int64_t> finished_tablets_replica;
420
1.00M
    for (const auto& [node_id, node_channel] : _node_channels) {
421
1.00M
        if (unfinished_node_channel_ids.contains(node_id) || !node_channel->check_status().ok()) {
422
974k
            continue;
423
974k
        }
424
282k
        for (const auto& tablet_id : _tablets_by_channel[node_id]) {
425
            // Only count non-gap backends for quorum success.
426
            // Gap backends' success doesn't count toward majority write.
427
282k
            auto gap_it = _parent->_tablet_version_gap_backends.find(tablet_id);
428
282k
            if (gap_it == _parent->_tablet_version_gap_backends.end() ||
429
282k
                gap_it->second.find(node_id) == gap_it->second.end()) {
430
282k
                finished_tablets_replica[tablet_id]++;
431
282k
            }
432
282k
        }
433
32.8k
    }
434
435
    // 2. check if quorum success
436
1.17M
    for (const auto& tablet_id : need_finish_tablets) {
437
1.17M
        if (finished_tablets_replica[tablet_id] < _load_required_replicas_num(tablet_id)) {
438
977k
            return false;
439
977k
        }
440
1.17M
    }
441
442
29.0k
    return true;
443
1.00M
}
444
445
int64_t IndexChannel::_calc_max_wait_time_ms(
446
0
        const std::unordered_set<int64_t>& unfinished_node_channel_ids) {
447
    // 1. calculate avg speed of all unfinished node channel
448
0
    int64_t elapsed_ms = UnixMillis() - _start_time;
449
0
    int64_t total_bytes = 0;
450
0
    int finished_count = 0;
451
0
    for (const auto& [node_id, node_channel] : _node_channels) {
452
0
        if (unfinished_node_channel_ids.contains(node_id)) {
453
0
            continue;
454
0
        }
455
0
        total_bytes += node_channel->write_bytes();
456
0
        finished_count++;
457
0
    }
458
    // no data loaded in index channel, return 0
459
0
    if (total_bytes == 0 || finished_count == 0) {
460
0
        return 0;
461
0
    }
462
    // if elapsed_ms is equal to 0, explain the loaded data is too small
463
0
    if (elapsed_ms <= 0) {
464
0
        return config::quorum_success_min_wait_seconds * 1000;
465
0
    }
466
0
    double avg_speed =
467
0
            static_cast<double>(total_bytes) / (static_cast<double>(elapsed_ms) * finished_count);
468
469
    // 2. calculate max wait time of each unfinished node channel and return the max value
470
0
    int64_t max_wait_time_ms = 0;
471
0
    for (int64_t id : unfinished_node_channel_ids) {
472
0
        int64_t bytes = _node_channels[id]->write_bytes();
473
0
        int64_t wait =
474
0
                avg_speed > 0 ? static_cast<int64_t>(static_cast<double>(bytes) / avg_speed) : 0;
475
0
        max_wait_time_ms = std::max(max_wait_time_ms, wait);
476
0
    }
477
478
    // 3. calculate max wait time
479
    // introduce quorum_success_min_wait_seconds to avoid jitter of small load
480
0
    max_wait_time_ms -= UnixMillis() - _start_time;
481
0
    max_wait_time_ms =
482
0
            std::max(static_cast<int64_t>(static_cast<double>(max_wait_time_ms) *
483
0
                                          (1.0 + config::quorum_success_max_wait_multiplier)),
484
0
                     config::quorum_success_min_wait_seconds * 1000);
485
486
0
    return max_wait_time_ms;
487
0
}
488
489
1.15M
static Status none_of(std::initializer_list<bool> vars) {
490
2.31M
    bool none = std::none_of(vars.begin(), vars.end(), [](bool var) { return var; });
491
1.15M
    Status st = Status::OK();
492
1.15M
    if (!none) {
493
48
        std::string vars_str;
494
48
        std::for_each(vars.begin(), vars.end(),
495
96
                      [&vars_str](bool var) -> void { vars_str += (var ? "1/" : "0/"); });
496
48
        if (!vars_str.empty()) {
497
48
            vars_str.pop_back(); // 0/1/0/ -> 0/1/0
498
48
        }
499
48
        st = Status::Uninitialized(vars_str);
500
48
    }
501
502
1.15M
    return st;
503
1.15M
}
504
505
VNodeChannel::VNodeChannel(VTabletWriter* parent, IndexChannel* index_channel, int64_t node_id,
506
                           bool is_incremental)
507
46.1k
        : _parent(parent),
508
46.1k
          _index_channel(index_channel),
509
46.1k
          _node_id(node_id),
510
46.1k
          _is_incremental(is_incremental) {
511
46.1k
    _cur_add_block_request = std::make_shared<PTabletWriterAddBlockRequest>();
512
46.1k
    _node_channel_tracker = std::make_shared<MemTracker>(
513
46.1k
            fmt::format("NodeChannel:indexID={}:threadId={}",
514
46.1k
                        std::to_string(_index_channel->_index_id), ThreadContext::get_thread_id()));
515
46.1k
    _load_mem_limit = MemInfo::mem_limit() * config::load_process_max_memory_limit_percent / 100;
516
46.1k
}
517
518
46.7k
VNodeChannel::~VNodeChannel() = default;
519
520
46.8k
void VNodeChannel::clear_all_blocks() {
521
46.8k
    std::lock_guard<std::mutex> lg(_pending_batches_lock);
522
46.8k
    std::queue<AddBlockReq> empty;
523
46.8k
    std::swap(_pending_blocks, empty);
524
46.8k
    _cur_mutable_block.reset();
525
46.8k
}
526
527
// we don't need to send tablet_writer_cancel rpc request when
528
// init failed, so set _is_closed to true.
529
// if "_cancelled" is set to true,
530
// no need to set _cancel_msg because the error will be
531
// returned directly via "TabletSink::prepare()" method.
532
46.5k
Status VNodeChannel::init(RuntimeState* state) {
533
46.5k
    if (_inited) {
534
184
        return Status::OK();
535
184
    }
536
537
46.3k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
538
46.3k
    _task_exec_ctx = state->get_task_execution_context();
539
46.3k
    _tuple_desc = _parent->_output_tuple_desc;
540
46.3k
    _state = state;
541
    // get corresponding BE node.
542
46.3k
    const auto* node = _parent->_nodes_info->find_node(_node_id);
543
46.3k
    if (node == nullptr) {
544
0
        _cancelled = true;
545
0
        _is_closed = true;
546
0
        return Status::InternalError("unknown node id, id={}", _node_id);
547
0
    }
548
46.3k
    _node_info = *node;
549
550
46.3k
    _load_info = "load_id=" + print_id(_parent->_load_id) +
551
46.3k
                 ", txn_id=" + std::to_string(_parent->_txn_id);
552
553
46.3k
    _row_desc = std::make_unique<RowDescriptor>(_tuple_desc);
554
46.3k
    _batch_size = state->batch_size();
555
556
46.3k
    _stub = state->exec_env()->brpc_internal_client_cache()->get_client(_node_info.host,
557
46.3k
                                                                        _node_info.brpc_port);
558
46.3k
    if (_stub == nullptr) {
559
0
        _cancelled = true;
560
0
        _is_closed = true;
561
0
        return Status::InternalError("Get rpc stub failed, host={}, port={}, info={}",
562
0
                                     _node_info.host, _node_info.brpc_port, channel_info());
563
0
    }
564
565
46.3k
    _rpc_timeout_ms = state->execution_timeout() * 1000;
566
46.3k
    _timeout_watch.start();
567
568
    // Initialize _cur_add_block_request
569
46.7k
    if (!_cur_add_block_request->has_id()) {
570
46.7k
        *(_cur_add_block_request->mutable_id()) = _parent->_load_id;
571
46.7k
    }
572
46.3k
    _cur_add_block_request->set_index_id(_index_channel->_index_id);
573
46.3k
    _cur_add_block_request->set_sender_id(_parent->_sender_id);
574
46.3k
    _cur_add_block_request->set_backend_id(_node_id);
575
46.3k
    _cur_add_block_request->set_eos(false);
576
577
    // add block closure
578
    // Has to using value to capture _task_exec_ctx because tablet writer may destroyed during callback.
579
46.3k
    _send_block_callback = WriteBlockCallback<PTabletWriterAddBlockResult>::create_shared();
580
46.3k
    _send_block_callback->addFailedHandler(
581
46.3k
            [&, task_exec_ctx = _task_exec_ctx](const WriteBlockCallbackContext& ctx) {
582
0
                std::shared_ptr<TaskExecutionContext> ctx_lock = task_exec_ctx.lock();
583
0
                if (ctx_lock == nullptr) {
584
0
                    return;
585
0
                }
586
0
                _add_block_failed_callback(ctx);
587
0
            });
588
589
46.3k
    _send_block_callback->addSuccessHandler(
590
46.3k
            [&, task_exec_ctx = _task_exec_ctx](const PTabletWriterAddBlockResult& result,
591
48.8k
                                                const WriteBlockCallbackContext& ctx) {
592
48.8k
                std::shared_ptr<TaskExecutionContext> ctx_lock = task_exec_ctx.lock();
593
48.8k
                if (ctx_lock == nullptr) {
594
0
                    return;
595
0
                }
596
48.8k
                _add_block_success_callback(result, ctx);
597
48.8k
            });
598
599
46.3k
    _name = fmt::format("VNodeChannel[{}-{}]", _index_channel->_index_id, _node_id);
600
    // The node channel will send _batch_size rows of data each rpc. When the
601
    // number of tablets is large, the number of data rows received by each
602
    // tablet is small, TabletsChannel need to traverse each tablet for import.
603
    // so the import performance is poor. Therefore, we set _batch_size to
604
    // a relatively large value to improve the import performance.
605
46.3k
    _batch_size = std::max(_batch_size, 8192);
606
607
46.4k
    if (_state) {
608
46.4k
        QueryContext* query_ctx = _state->get_query_ctx();
609
46.4k
        if (query_ctx) {
610
46.4k
            auto wg_ptr = query_ctx->workload_group();
611
46.7k
            if (wg_ptr) {
612
46.7k
                _wg_id = wg_ptr->id();
613
46.7k
            }
614
46.4k
        }
615
46.4k
    }
616
617
46.3k
    _inited = true;
618
46.3k
    return Status::OK();
619
46.3k
}
620
621
46.7k
void VNodeChannel::_open_internal(bool is_incremental) {
622
46.7k
    if (_tablets_wait_open.empty()) {
623
0
        return;
624
0
    }
625
46.7k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
626
46.7k
    auto request = std::make_shared<PTabletWriterOpenRequest>();
627
46.7k
    request->mutable_id()->CopyFrom(_parent->_load_id);
628
46.7k
    request->set_index_id(_index_channel->_index_id);
629
46.7k
    request->set_txn_id(_parent->_txn_id);
630
46.7k
    request->set_sender_id(_parent->_sender_id);
631
46.7k
    request->mutable_schema()->CopyFrom(*_parent->_schema->to_protobuf());
632
46.7k
    if (_parent->_t_sink.olap_table_sink.__isset.storage_vault_id) {
633
0
        request->set_storage_vault_id(_parent->_t_sink.olap_table_sink.storage_vault_id);
634
0
    }
635
46.7k
    std::set<int64_t> deduper;
636
363k
    for (auto& tablet : _tablets_wait_open) {
637
363k
        if (deduper.contains(tablet.tablet_id)) {
638
0
            continue;
639
0
        }
640
363k
        auto* ptablet = request->add_tablets();
641
363k
        ptablet->set_partition_id(tablet.partition_id);
642
363k
        ptablet->set_tablet_id(tablet.tablet_id);
643
363k
        deduper.insert(tablet.tablet_id);
644
363k
        _all_tablets.push_back(std::move(tablet));
645
363k
    }
646
46.7k
    _tablets_wait_open.clear();
647
648
46.7k
    request->set_num_senders(_parent->_num_senders);
649
46.7k
    request->set_need_gen_rollup(false); // Useless but it is a required field in pb
650
46.7k
    request->set_load_channel_timeout_s(_parent->_load_channel_timeout_s);
651
46.7k
    request->set_is_high_priority(_parent->_is_high_priority);
652
46.7k
    request->set_sender_ip(BackendOptions::get_localhost());
653
46.7k
    request->set_is_vectorized(true);
654
46.7k
    request->set_backend_id(_node_id);
655
46.7k
    request->set_enable_profile(_state->enable_profile());
656
46.7k
    request->set_is_incremental(is_incremental);
657
46.7k
    request->set_txn_expiration(_parent->_txn_expiration);
658
46.7k
    request->set_write_file_cache(_parent->_write_file_cache);
659
660
46.7k
    if (_wg_id > 0) {
661
46.3k
        request->set_workload_group_id(_wg_id);
662
46.3k
    }
663
664
46.7k
    auto open_callback = DummyBrpcCallback<PTabletWriterOpenResult>::create_shared();
665
46.7k
    auto open_closure = AutoReleaseClosure<
666
46.7k
            PTabletWriterOpenRequest,
667
46.7k
            DummyBrpcCallback<PTabletWriterOpenResult>>::create_unique(request, open_callback);
668
46.7k
    open_callback->cntl_->set_timeout_ms(config::tablet_writer_open_rpc_timeout_sec * 1000);
669
46.7k
    if (config::tablet_writer_ignore_eovercrowded) {
670
46.2k
        open_callback->cntl_->ignore_eovercrowded();
671
46.2k
    }
672
46.7k
    VLOG_DEBUG << fmt::format("txn {}: open NodeChannel to {}, incremental: {}, senders: {}",
673
676
                              _parent->_txn_id, _node_id, is_incremental, _parent->_num_senders);
674
    // the real transmission here. the corresponding BE's load mgr will open load channel for it.
675
46.7k
    _stub->tablet_writer_open(open_closure->cntl_.get(), open_closure->request_.get(),
676
46.7k
                              open_closure->response_.get(), open_closure.get());
677
46.7k
    open_closure.release();
678
46.7k
    _open_callbacks.push_back(open_callback);
679
46.7k
}
680
681
46.6k
void VNodeChannel::open() {
682
46.6k
    _open_internal(false);
683
46.6k
}
684
685
184
void VNodeChannel::incremental_open() {
686
184
    VLOG_DEBUG << "incremental opening node channel" << _node_id;
687
184
    _open_internal(true);
688
184
}
689
690
46.7k
Status VNodeChannel::open_wait() {
691
46.7k
    Status status;
692
47.0k
    for (auto& open_callback : _open_callbacks) {
693
        // because of incremental open, we will wait multi times. so skip the closures which have been checked and set to nullptr in previous rounds
694
47.0k
        if (open_callback == nullptr) {
695
0
            continue;
696
0
        }
697
698
47.0k
        open_callback->join();
699
47.0k
        SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
700
47.0k
        if (open_callback->cntl_->Failed()) {
701
0
            if (!ExecEnv::GetInstance()->brpc_internal_client_cache()->available(
702
0
                        _stub, _node_info.host, _node_info.brpc_port)) {
703
0
                ExecEnv::GetInstance()->brpc_internal_client_cache()->erase(
704
0
                        open_callback->cntl_->remote_side());
705
0
            }
706
0
            _cancelled = true;
707
0
            auto error_code = open_callback->cntl_->ErrorCode();
708
0
            auto error_text = open_callback->cntl_->ErrorText();
709
0
            if (error_text.find("Reached timeout") != std::string::npos) {
710
0
                LOG(WARNING) << "failed to open tablet writer may caused by timeout. increase BE "
711
0
                                "config `tablet_writer_open_rpc_timeout_sec` if you are sure that "
712
0
                                "your table building and data are reasonable.";
713
0
            }
714
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
715
0
                    "failed to open tablet writer, error={}, error_text={}, info={}",
716
0
                    berror(error_code), error_text, channel_info());
717
0
        }
718
47.0k
        status = Status::create(open_callback->response_->status());
719
720
47.0k
        if (!status.ok()) {
721
0
            _cancelled = true;
722
0
            return status;
723
0
        }
724
47.0k
    }
725
726
46.7k
    return status;
727
46.7k
}
728
729
40.2k
Status VNodeChannel::add_block(Block* block, const Payload* payload) {
730
40.2k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
731
40.2k
    if (payload->second.empty()) {
732
0
        return Status::OK();
733
0
    }
734
    // If add_block() when _eos_is_produced==true, there must be sth wrong, we can only mark this channel as failed.
735
40.2k
    auto st = none_of({_cancelled, _eos_is_produced});
736
40.2k
    if (!st.ok()) {
737
0
        if (_cancelled) {
738
0
            std::lock_guard<std::mutex> l(_cancel_msg_lock);
739
0
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("add row failed. {}",
740
0
                                                                   _cancel_msg);
741
0
        } else {
742
0
            return std::move(st.prepend("already stopped, can't add row. cancelled/eos: "));
743
0
        }
744
0
    }
745
746
    // We use OlapTableSink mem_tracker which has the same ancestor of _plan node,
747
    // so in the ideal case, mem limit is a matter for _plan node.
748
    // But there is still some unfinished things, we do mem limit here temporarily.
749
    // _cancelled may be set by rpc callback, and it's possible that _cancelled might be set in any of the steps below.
750
    // It's fine to do a fake add_block() and return OK, because we will check _cancelled in next add_block() or mark_close().
751
40.2k
    constexpr int64_t kBackPressureSleepMs = 10;
752
40.2k
    auto* memtable_limiter = ExecEnv::GetInstance()->memtable_memory_limiter();
753
40.2k
    while (true) {
754
40.2k
        bool is_exceed_soft_mem_limit = GlobalMemoryArbitrator::is_exceed_soft_mem_limit();
755
40.2k
        int64_t memtable_mem =
756
40.2k
                (memtable_limiter != nullptr && memtable_limiter->mem_tracker() != nullptr)
757
40.2k
                        ? memtable_limiter->mem_tracker()->consumption()
758
40.2k
                        : 0;
759
        // Note: Memtable memory is not included in load memory statistics (MemoryProfile::load_current_usage())
760
        // for performance and memory control complexity reasons. Therefore, we explicitly add memtable memory
761
        // consumption here to ensure accurate back pressure decisions and prevent OOM during heavy loads.
762
40.2k
        auto current_load_mem_value = MemoryProfile::load_current_usage() + memtable_mem;
763
40.2k
        bool mem_limit_exceeded = is_exceed_soft_mem_limit ||
764
40.2k
                                  current_load_mem_value > _load_mem_limit ||
765
40.2k
                                  _pending_batches_bytes > _max_pending_batches_bytes;
766
40.2k
        bool need_back_pressure = !_cancelled && !_state->is_cancelled() &&
767
40.2k
                                  _pending_batches_num > 0 && mem_limit_exceeded;
768
40.2k
        if (!need_back_pressure) {
769
40.2k
            break;
770
40.2k
        }
771
1
        SCOPED_RAW_TIMER(&_stat.mem_exceeded_block_ns);
772
1
        std::this_thread::sleep_for(std::chrono::milliseconds(kBackPressureSleepMs));
773
1
    }
774
775
40.2k
    if (UNLIKELY(!_cur_mutable_block)) {
776
32.5k
        _cur_mutable_block = MutableBlock::create_unique(block->clone_empty());
777
32.5k
    }
778
779
40.2k
    SCOPED_RAW_TIMER(&_stat.append_node_channel_ns);
780
40.2k
    st = block->append_to_block_by_selector(_cur_mutable_block.get(), *(payload->first));
781
40.2k
    if (!st.ok()) {
782
0
        _cancel_with_msg(fmt::format("{}, err: {}", channel_info(), st.to_string()));
783
0
        return st;
784
0
    }
785
35.8M
    for (auto tablet_id : payload->second) {
786
35.8M
        _cur_add_block_request->add_tablet_ids(tablet_id);
787
35.8M
    }
788
40.2k
    _write_bytes.fetch_add(_cur_mutable_block->bytes());
789
790
40.2k
    if (_cur_mutable_block->rows() >= _batch_size ||
791
40.2k
        _cur_mutable_block->bytes() > config::doris_scanner_row_bytes) {
792
2.19k
        {
793
2.19k
            SCOPED_ATOMIC_TIMER(&_queue_push_lock_ns);
794
2.19k
            std::lock_guard<std::mutex> l(_pending_batches_lock);
795
            // To simplify the add_row logic, postpone adding block into req until the time of sending req
796
2.19k
            _pending_batches_bytes += _cur_mutable_block->allocated_bytes();
797
2.19k
            _cur_add_block_request->set_eos(
798
2.19k
                    false); // for multi-add, only when marking close we set it eos.
799
            // Copy the request to tmp request to add to pend block queue
800
2.19k
            auto tmp_add_block_request = std::make_shared<PTabletWriterAddBlockRequest>();
801
2.19k
            *tmp_add_block_request = *_cur_add_block_request;
802
2.19k
            _pending_blocks.emplace(std::move(_cur_mutable_block), tmp_add_block_request);
803
2.19k
            _pending_batches_num++;
804
2.19k
            VLOG_DEBUG << "VTabletWriter:" << _parent << " VNodeChannel:" << this
805
0
                       << " pending_batches_bytes:" << _pending_batches_bytes
806
0
                       << " jobid:" << std::to_string(_state->load_job_id())
807
0
                       << " loadinfo:" << _load_info;
808
2.19k
        }
809
2.19k
        _cur_mutable_block = MutableBlock::create_unique(block->clone_empty());
810
2.19k
        _cur_add_block_request->clear_tablet_ids();
811
2.19k
    }
812
813
40.2k
    return Status::OK();
814
40.2k
}
815
816
0
static void injection_full_gc_fn() {
817
0
    MemoryReclamation::revoke_process_memory("injection_full_gc_fn");
818
0
}
819
820
int VNodeChannel::try_send_and_fetch_status(RuntimeState* state,
821
17.4M
                                            std::unique_ptr<ThreadPoolToken>& thread_pool_token) {
822
17.4M
    DBUG_EXECUTE_IF("VNodeChannel.try_send_and_fetch_status_full_gc", {
823
17.4M
        std::thread t(injection_full_gc_fn);
824
17.4M
        t.join();
825
17.4M
    });
826
827
17.6M
    if (_cancelled || _send_finished) { // not run
828
1.01M
        return 0;
829
1.01M
    }
830
831
16.4M
    auto load_back_pressure_version_wait_time_ms = _load_back_pressure_version_wait_time_ms.load();
832
16.4M
    if (UNLIKELY(load_back_pressure_version_wait_time_ms > 0)) {
833
0
        std::this_thread::sleep_for(
834
0
                std::chrono::milliseconds(load_back_pressure_version_wait_time_ms));
835
0
        _load_back_pressure_version_block_ms.fetch_add(
836
0
                load_back_pressure_version_wait_time_ms); // already in milliseconds
837
0
        _load_back_pressure_version_wait_time_ms = 0;
838
0
    }
839
840
    // set closure for sending block.
841
16.4M
    if (!_send_block_callback->try_set_in_flight()) {
842
        // There is packet in flight, skip.
843
1.49M
        return _send_finished ? 0 : 1;
844
1.49M
    }
845
846
    // We are sure that try_send_batch is not running
847
14.9M
    if (_pending_batches_num > 0) {
848
48.8k
        auto s = thread_pool_token->submit_func([this, state] { try_send_pending_block(state); });
849
48.8k
        if (!s.ok()) {
850
0
            _cancel_with_msg("submit send_batch task to send_batch_thread_pool failed");
851
            // sending finished. clear in flight
852
0
            _send_block_callback->clear_in_flight();
853
0
        }
854
        // in_flight is cleared in closure::Run
855
14.8M
    } else {
856
        // sending finished. clear in flight
857
14.8M
        _send_block_callback->clear_in_flight();
858
14.8M
    }
859
14.9M
    return _send_finished ? 0 : 1;
860
16.4M
}
861
862
224
void VNodeChannel::_cancel_with_msg(const std::string& msg) {
863
224
    LOG(WARNING) << "cancel node channel " << channel_info() << ", error message: " << msg;
864
224
    {
865
224
        std::lock_guard<std::mutex> l(_cancel_msg_lock);
866
224
        if (_cancel_msg.empty()) {
867
176
            _cancel_msg = msg;
868
176
        }
869
224
    }
870
224
    _cancelled = true;
871
224
}
872
873
void VNodeChannel::_refresh_back_pressure_version_wait_time(
874
        const ::google::protobuf::RepeatedPtrField<::doris::PTabletLoadRowsetInfo>&
875
48.7k
                tablet_load_infos) {
876
48.7k
    int64_t max_rowset_num_gap = 0;
877
    // if any one tablet is under high load pressure, we would make the whole procedure
878
    // sleep to prevent the corresponding BE return -235
879
48.7k
    std::for_each(
880
48.7k
            tablet_load_infos.begin(), tablet_load_infos.end(),
881
48.7k
            [&max_rowset_num_gap](auto& load_info) {
882
0
                int64_t cur_rowset_num = load_info.current_rowset_nums();
883
0
                int64_t high_load_point = load_info.max_config_rowset_nums() *
884
0
                                          (config::load_back_pressure_version_threshold / 100);
885
0
                DCHECK(cur_rowset_num > high_load_point);
886
0
                max_rowset_num_gap = std::max(max_rowset_num_gap, cur_rowset_num - high_load_point);
887
0
            });
888
    // to slow down the high load pressure
889
    // we would use the rowset num gap to calculate one sleep time
890
    // for example:
891
    // if the max tablet version is 2000, there are 3 BE
892
    // A: ====================  1800
893
    // B: ===================   1700
894
    // C: ==================    1600
895
    //    ==================    1600
896
    //                      ^
897
    //                      the high load point
898
    // then then max gap is 1800 - (max tablet version * config::load_back_pressure_version_threshold / 100) = 200,
899
    // we would make the whole send procesure sleep
900
    // 1200ms for compaction to be done toe reduce the high pressure
901
48.7k
    auto max_time = config::max_load_back_pressure_version_wait_time_ms;
902
48.7k
    if (UNLIKELY(max_rowset_num_gap > 0)) {
903
0
        _load_back_pressure_version_wait_time_ms.store(
904
0
                std::min(max_rowset_num_gap + 1000, max_time));
905
0
        LOG(INFO) << "try to back pressure version, wait time(ms): "
906
0
                  << _load_back_pressure_version_wait_time_ms
907
0
                  << ", load id: " << print_id(_parent->_load_id)
908
0
                  << ", max_rowset_num_gap: " << max_rowset_num_gap;
909
0
    }
910
48.7k
}
911
912
48.8k
void VNodeChannel::try_send_pending_block(RuntimeState* state) {
913
48.8k
    SCOPED_ATTACH_TASK(state);
914
48.8k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker);
915
48.8k
    SCOPED_ATOMIC_TIMER(&_actual_consume_ns);
916
48.8k
    signal::set_signal_task_id(_parent->_load_id);
917
48.8k
    AddBlockReq send_block;
918
48.8k
    {
919
48.8k
        std::lock_guard<std::mutex> l(_pending_batches_lock);
920
48.8k
        DCHECK(!_pending_blocks.empty());
921
48.8k
        send_block = std::move(_pending_blocks.front());
922
48.8k
        _pending_blocks.pop();
923
48.8k
        _pending_batches_num--;
924
48.8k
        _pending_batches_bytes -= send_block.first->allocated_bytes();
925
48.8k
    }
926
927
48.8k
    auto mutable_block = std::move(send_block.first);
928
48.8k
    auto request = std::move(send_block.second); // doesn't need to be saved in heap
929
930
    // tablet_ids has already set when add row
931
48.8k
    request->set_packet_seq(_next_packet_seq);
932
48.8k
    auto block = mutable_block->to_block();
933
48.8k
    CHECK(block.rows() == request->tablet_ids_size())
934
19
            << "block rows: " << block.rows()
935
19
            << ", tablet_ids_size: " << request->tablet_ids_size();
936
48.8k
    if (block.rows() > 0) {
937
34.5k
        SCOPED_ATOMIC_TIMER(&_serialize_batch_ns);
938
34.5k
        size_t uncompressed_bytes = 0, compressed_bytes = 0;
939
34.5k
        int64_t compressed_time = 0;
940
34.5k
        Status st = block.serialize(state->be_exec_version(), request->mutable_block(),
941
34.5k
                                    &uncompressed_bytes, &compressed_bytes, &compressed_time,
942
34.5k
                                    state->fragement_transmission_compression_type(),
943
34.5k
                                    _parent->_transfer_large_data_by_brpc);
944
34.5k
        TEST_INJECTION_POINT_CALLBACK("VNodeChannel::try_send_block", &st);
945
34.5k
        if (!st.ok()) {
946
0
            cancel(fmt::format("{}, err: {}", channel_info(), st.to_string()));
947
0
            _send_block_callback->clear_in_flight();
948
0
            return;
949
0
        }
950
34.5k
        if (double(compressed_bytes) >= double(config::brpc_max_body_size) * 0.95F) {
951
0
            LOG(WARNING) << "send block too large, this rpc may failed. send size: "
952
0
                         << compressed_bytes << ", threshold: " << config::brpc_max_body_size
953
0
                         << ", " << channel_info();
954
0
        }
955
34.5k
    }
956
957
48.8k
    auto remain_ms = _rpc_timeout_ms - _timeout_watch.elapsed_time() / NANOS_PER_MILLIS;
958
48.8k
    if (UNLIKELY(remain_ms < config::min_load_rpc_timeout_ms)) {
959
10
        if (remain_ms <= 0 && !request->eos()) {
960
0
            cancel(fmt::format("{}, err: load timeout after {} ms", channel_info(),
961
0
                               _rpc_timeout_ms));
962
0
            _send_block_callback->clear_in_flight();
963
0
            return;
964
10
        } else {
965
10
            remain_ms = config::min_load_rpc_timeout_ms;
966
10
        }
967
10
    }
968
969
48.8k
    _send_block_callback->reset();
970
48.8k
    _send_block_callback->cntl_->set_timeout_ms(remain_ms);
971
48.8k
    if (config::tablet_writer_ignore_eovercrowded) {
972
48.8k
        _send_block_callback->cntl_->ignore_eovercrowded();
973
48.8k
    }
974
975
48.8k
    if (request->eos()) {
976
46.6k
        for (auto pid : _parent->_tablet_finder->partition_ids()) {
977
35.4k
            request->add_partition_ids(pid);
978
35.4k
        }
979
980
46.6k
        request->set_write_single_replica(_parent->_write_single_replica);
981
46.6k
        if (_parent->_write_single_replica) {
982
0
            for (auto& _slave_tablet_node : _slave_tablet_nodes) {
983
0
                PSlaveTabletNodes slave_tablet_nodes;
984
0
                for (auto node_id : _slave_tablet_node.second) {
985
0
                    const auto* node = _parent->_nodes_info->find_node(node_id);
986
0
                    DBUG_EXECUTE_IF("VNodeChannel.try_send_pending_block.slave_node_not_found", {
987
0
                        LOG(WARNING) << "trigger "
988
0
                                        "VNodeChannel.try_send_pending_block.slave_node_not_found "
989
0
                                        "debug point will set node to nullptr";
990
0
                        node = nullptr;
991
0
                    });
992
0
                    if (node == nullptr) {
993
0
                        LOG(WARNING) << "slave node not found, node_id=" << node_id;
994
0
                        cancel(fmt::format("slave node not found, node_id={}", node_id));
995
0
                        _send_block_callback->clear_in_flight();
996
0
                        return;
997
0
                    }
998
0
                    PNodeInfo* pnode = slave_tablet_nodes.add_slave_nodes();
999
0
                    pnode->set_id(node->id);
1000
0
                    pnode->set_option(node->option);
1001
0
                    pnode->set_host(node->host);
1002
0
                    pnode->set_async_internal_port(node->brpc_port);
1003
0
                }
1004
0
                request->mutable_slave_tablet_nodes()->insert(
1005
0
                        {_slave_tablet_node.first, slave_tablet_nodes});
1006
0
            }
1007
0
        }
1008
1009
        // eos request must be the last request-> it's a signal makeing callback function to set _add_batch_finished true.
1010
        // end_mark makes is_last_rpc true when rpc finished and call callbacks.
1011
46.6k
        _send_block_callback->end_mark();
1012
46.6k
        _send_finished = true;
1013
18.4E
        CHECK(_pending_batches_num == 0) << _pending_batches_num;
1014
46.6k
    }
1015
1016
48.8k
    auto send_block_closure = AutoReleaseClosure<
1017
48.8k
            PTabletWriterAddBlockRequest,
1018
48.8k
            WriteBlockCallback<PTabletWriterAddBlockResult>>::create_unique(request,
1019
48.8k
                                                                            _send_block_callback);
1020
48.8k
    if (_parent->_transfer_large_data_by_brpc && request->has_block() &&
1021
48.8k
        request->block().has_column_values() && request->ByteSizeLong() > MIN_HTTP_BRPC_SIZE) {
1022
0
        Status st = request_embed_attachment_contain_blockv2(send_block_closure->request_.get(),
1023
0
                                                             send_block_closure);
1024
0
        if (!st.ok()) {
1025
0
            cancel(fmt::format("{}, err: {}", channel_info(), st.to_string()));
1026
0
            _send_block_callback->clear_in_flight();
1027
0
            return;
1028
0
        }
1029
1030
0
        std::string host = _node_info.host;
1031
0
        auto dns_cache = ExecEnv::GetInstance()->dns_cache();
1032
0
        if (dns_cache == nullptr) {
1033
0
            LOG(WARNING) << "DNS cache is not initialized, skipping hostname resolve";
1034
0
        } else if (!is_valid_ip(_node_info.host)) {
1035
0
            Status status = dns_cache->get(_node_info.host, &host);
1036
0
            if (!status.ok()) {
1037
0
                LOG(WARNING) << "failed to get ip from host " << _node_info.host << ": "
1038
0
                             << status.to_string();
1039
0
                cancel(fmt::format("failed to get ip from host {}", _node_info.host));
1040
0
                _send_block_callback->clear_in_flight();
1041
0
                return;
1042
0
            }
1043
0
        }
1044
        //format an ipv6 address
1045
0
        std::string brpc_url = get_brpc_http_url(host, _node_info.brpc_port);
1046
0
        std::shared_ptr<PBackendService_Stub> _brpc_http_stub =
1047
0
                _state->exec_env()->brpc_internal_client_cache()->get_new_client_no_cache(brpc_url,
1048
0
                                                                                          "http");
1049
0
        if (_brpc_http_stub == nullptr) {
1050
0
            cancel(fmt::format("{}, failed to open brpc http client to {}", channel_info(),
1051
0
                               brpc_url));
1052
0
            _send_block_callback->clear_in_flight();
1053
0
            return;
1054
0
        }
1055
0
        _send_block_callback->cntl_->http_request().uri() =
1056
0
                brpc_url + "/PInternalServiceImpl/tablet_writer_add_block_by_http";
1057
0
        _send_block_callback->cntl_->http_request().set_method(brpc::HTTP_METHOD_POST);
1058
0
        _send_block_callback->cntl_->http_request().set_content_type("application/json");
1059
1060
0
        {
1061
0
            _brpc_http_stub->tablet_writer_add_block_by_http(
1062
0
                    send_block_closure->cntl_.get(), nullptr, send_block_closure->response_.get(),
1063
0
                    send_block_closure.get());
1064
0
            send_block_closure.release();
1065
0
        }
1066
48.8k
    } else {
1067
48.8k
        _send_block_callback->cntl_->http_request().Clear();
1068
48.8k
        {
1069
48.8k
            _stub->tablet_writer_add_block(
1070
48.8k
                    send_block_closure->cntl_.get(), send_block_closure->request_.get(),
1071
48.8k
                    send_block_closure->response_.get(), send_block_closure.get());
1072
48.8k
            send_block_closure.release();
1073
48.8k
        }
1074
48.8k
    }
1075
1076
48.8k
    _next_packet_seq++;
1077
48.8k
}
1078
1079
void VNodeChannel::_add_block_success_callback(const PTabletWriterAddBlockResult& result,
1080
48.8k
                                               const WriteBlockCallbackContext& ctx) {
1081
48.8k
    std::lock_guard<std::mutex> l(this->_closed_lock);
1082
48.8k
    if (this->_is_closed) {
1083
        // if the node channel is closed, no need to call the following logic,
1084
        // and notice that _index_channel may already be destroyed.
1085
1
        return;
1086
1
    }
1087
48.8k
    SCOPED_ATTACH_TASK(_state);
1088
48.8k
    Status status(Status::create(result.status()));
1089
48.8k
    if (status.ok()) {
1090
48.7k
        _refresh_back_pressure_version_wait_time(result.tablet_load_rowset_num_infos());
1091
        // if has error tablet, handle them first
1092
48.7k
        for (const auto& error : result.tablet_errors()) {
1093
0
            _index_channel->mark_as_failed(this, "tablet error: " + error.msg(), error.tablet_id());
1094
0
        }
1095
1096
48.7k
        Status st = _index_channel->check_intolerable_failure();
1097
48.7k
        if (!st.ok()) {
1098
0
            _cancel_with_msg(st.to_string());
1099
48.7k
        } else if (ctx._is_last_rpc) {
1100
46.6k
            bool skip_tablet_info = false;
1101
46.6k
            DBUG_EXECUTE_IF("VNodeChannel.add_block_success_callback.incomplete_commit_info",
1102
46.6k
                            { skip_tablet_info = true; });
1103
190k
            for (const auto& tablet : result.tablet_vec()) {
1104
190k
                DBUG_EXECUTE_IF("VNodeChannel.add_block_success_callback.incomplete_commit_info", {
1105
190k
                    if (skip_tablet_info) {
1106
190k
                        LOG(INFO) << "skip tablet info: " << tablet.tablet_id();
1107
190k
                        skip_tablet_info = false;
1108
190k
                        continue;
1109
190k
                    }
1110
190k
                });
1111
190k
                TTabletCommitInfo commit_info;
1112
190k
                commit_info.tabletId = tablet.tablet_id();
1113
190k
                commit_info.backendId = _node_id;
1114
190k
                _tablet_commit_infos.emplace_back(std::move(commit_info));
1115
190k
                if (tablet.has_received_rows()) {
1116
190k
                    _tablets_received_rows.emplace_back(tablet.tablet_id(), tablet.received_rows());
1117
190k
                }
1118
190k
                if (tablet.has_num_rows_filtered()) {
1119
190k
                    _tablets_filtered_rows.emplace_back(tablet.tablet_id(),
1120
190k
                                                        tablet.num_rows_filtered());
1121
190k
                }
1122
18.4E
                VLOG_CRITICAL << "master replica commit info: tabletId=" << tablet.tablet_id()
1123
18.4E
                              << ", backendId=" << _node_id
1124
18.4E
                              << ", master node id: " << this->node_id()
1125
18.4E
                              << ", host: " << this->host() << ", txn_id=" << _parent->_txn_id;
1126
190k
            }
1127
46.6k
            if (_parent->_write_single_replica) {
1128
0
                for (const auto& tablet_slave_node_ids : result.success_slave_tablet_node_ids()) {
1129
0
                    for (auto slave_node_id : tablet_slave_node_ids.second.slave_node_ids()) {
1130
0
                        TTabletCommitInfo commit_info;
1131
0
                        commit_info.tabletId = tablet_slave_node_ids.first;
1132
0
                        commit_info.backendId = slave_node_id;
1133
0
                        _tablet_commit_infos.emplace_back(std::move(commit_info));
1134
0
                        VLOG_CRITICAL
1135
0
                                << "slave replica commit info: tabletId="
1136
0
                                << tablet_slave_node_ids.first << ", backendId=" << slave_node_id
1137
0
                                << ", master node id: " << this->node_id()
1138
0
                                << ", host: " << this->host() << ", txn_id=" << _parent->_txn_id;
1139
0
                    }
1140
0
                }
1141
0
            }
1142
46.6k
            _add_batches_finished = true;
1143
46.6k
        }
1144
48.7k
    } else {
1145
69
        _cancel_with_msg(fmt::format("{}, add batch req success but status isn't ok, err: {}",
1146
69
                                     channel_info(), status.to_string()));
1147
69
    }
1148
1149
48.8k
    if (result.has_execution_time_us()) {
1150
48.8k
        _add_batch_counter.add_batch_execution_time_us += result.execution_time_us();
1151
48.8k
        _add_batch_counter.add_batch_wait_execution_time_us += result.wait_execution_time_us();
1152
48.8k
        _add_batch_counter.add_batch_num++;
1153
48.8k
    }
1154
48.8k
    if (result.has_load_channel_profile()) {
1155
10
        TRuntimeProfileTree tprofile;
1156
10
        const auto* buf = (const uint8_t*)result.load_channel_profile().data();
1157
10
        auto len = cast_set<uint32_t>(result.load_channel_profile().size());
1158
10
        auto st = deserialize_thrift_msg(buf, &len, false, &tprofile);
1159
10
        if (st.ok()) {
1160
10
            _state->load_channel_profile()->update(tprofile);
1161
10
        } else {
1162
0
            LOG(WARNING) << "load channel TRuntimeProfileTree deserialize failed, errmsg=" << st;
1163
0
        }
1164
10
    }
1165
48.8k
}
1166
1167
0
void VNodeChannel::_add_block_failed_callback(const WriteBlockCallbackContext& ctx) {
1168
0
    std::lock_guard<std::mutex> l(this->_closed_lock);
1169
0
    if (this->_is_closed) {
1170
        // if the node channel is closed, no need to call `mark_as_failed`,
1171
        // and notice that _index_channel may already be destroyed.
1172
0
        return;
1173
0
    }
1174
0
    SCOPED_ATTACH_TASK(_state);
1175
    // If rpc failed, mark all tablets on this node channel as failed
1176
0
    _index_channel->mark_as_failed(this,
1177
0
                                   fmt::format("rpc failed, error code:{}, error text:{}",
1178
0
                                               _send_block_callback->cntl_->ErrorCode(),
1179
0
                                               _send_block_callback->cntl_->ErrorText()),
1180
0
                                   -1);
1181
0
    if (_send_block_callback->cntl_->ErrorText().find("Reached timeout") != std::string::npos) {
1182
0
        LOG(WARNING) << "rpc failed may caused by timeout. increase BE config "
1183
0
                        "`min_load_rpc_timeout_ms` of to avoid this if you are sure that your "
1184
0
                        "table building and data are reasonable.";
1185
0
    }
1186
0
    Status st = _index_channel->check_intolerable_failure();
1187
0
    if (!st.ok()) {
1188
0
        _cancel_with_msg(fmt::format("{}, err: {}", channel_info(), st.to_string()));
1189
0
    } else if (ctx._is_last_rpc) {
1190
        // if this is last rpc, will must set _add_batches_finished. otherwise, node channel's close_wait
1191
        // will be blocked.
1192
0
        _add_batches_finished = true;
1193
0
    }
1194
0
}
1195
1196
// When _cancelled is true, we still need to send a tablet_writer_cancel
1197
// rpc request to truly release the load channel
1198
224
void VNodeChannel::cancel(const std::string& cancel_msg) {
1199
224
    if (_is_closed) {
1200
        // skip the channels that have been canceled or close_wait.
1201
48
        return;
1202
48
    }
1203
176
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
1204
    // set _is_closed to true finally
1205
176
    Defer set_closed {[&]() {
1206
176
        std::lock_guard<std::mutex> l(_closed_lock);
1207
176
        _is_closed = true;
1208
176
    }};
1209
    // we don't need to wait last rpc finished, cause closure's release/reset will join.
1210
    // But do we need brpc::StartCancel(call_id)?
1211
176
    _cancel_with_msg(cancel_msg);
1212
    // if not inited, _stub will be nullptr, skip sending cancel rpc
1213
176
    if (!_inited) {
1214
0
        return;
1215
0
    }
1216
1217
176
    auto request = std::make_shared<PTabletWriterCancelRequest>();
1218
176
    request->mutable_id()->CopyFrom(_parent->_load_id);
1219
176
    request->set_index_id(_index_channel->_index_id);
1220
176
    request->set_sender_id(_parent->_sender_id);
1221
176
    request->set_cancel_reason(cancel_msg);
1222
1223
    // cancel is already in post-processing, so error status could be ignored. so not keeping cancel_callback is acceptable.
1224
176
    auto cancel_callback = DummyBrpcCallback<PTabletWriterCancelResult>::create_shared();
1225
176
    auto closure = AutoReleaseClosure<
1226
176
            PTabletWriterCancelRequest,
1227
176
            DummyBrpcCallback<PTabletWriterCancelResult>>::create_unique(request, cancel_callback);
1228
1229
176
    auto remain_ms = _rpc_timeout_ms - _timeout_watch.elapsed_time() / NANOS_PER_MILLIS;
1230
176
    if (UNLIKELY(remain_ms < config::min_load_rpc_timeout_ms)) {
1231
0
        remain_ms = config::min_load_rpc_timeout_ms;
1232
0
    }
1233
176
    cancel_callback->cntl_->set_timeout_ms(remain_ms);
1234
176
    if (config::tablet_writer_ignore_eovercrowded) {
1235
176
        closure->cntl_->ignore_eovercrowded();
1236
176
    }
1237
176
    _stub->tablet_writer_cancel(closure->cntl_.get(), closure->request_.get(),
1238
176
                                closure->response_.get(), closure.get());
1239
176
    closure.release();
1240
176
}
1241
1242
1.03M
Status VNodeChannel::close_wait(RuntimeState* state, bool* is_closed) {
1243
1.03M
    DBUG_EXECUTE_IF("VNodeChannel.close_wait_full_gc", {
1244
1.03M
        std::thread t(injection_full_gc_fn);
1245
1.03M
        t.join();
1246
1.03M
    });
1247
1.03M
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
1248
1249
1.03M
    *is_closed = true;
1250
1251
1.03M
    auto st = none_of({_cancelled, !_eos_is_produced});
1252
1.03M
    if (!st.ok()) {
1253
48
        if (_cancelled) {
1254
48
            std::lock_guard<std::mutex> l(_cancel_msg_lock);
1255
48
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("wait close failed. {}",
1256
48
                                                                   _cancel_msg);
1257
48
        } else {
1258
0
            return std::move(
1259
0
                    st.prepend("already stopped, skip waiting for close. cancelled/!eos: "));
1260
0
        }
1261
48
    }
1262
1263
1.03M
    DBUG_EXECUTE_IF("VNodeChannel.close_wait.cancelled", {
1264
1.03M
        _cancelled = true;
1265
1.03M
        _cancel_msg = "injected cancel";
1266
1.03M
    });
1267
1268
1.03M
    if (state->is_cancelled()) {
1269
0
        _cancel_with_msg(state->cancel_reason().to_string());
1270
0
    }
1271
1272
    // Waiting for finished until _add_batches_finished changed by rpc's finished callback.
1273
    // it may take a long time, so we couldn't set a timeout
1274
    // For pipeline engine, the close is called in async writer's process block method,
1275
    // so that it will not block pipeline thread.
1276
1.03M
    if (!_add_batches_finished && !_cancelled && !state->is_cancelled()) {
1277
989k
        *is_closed = false;
1278
989k
        return Status::OK();
1279
989k
    }
1280
47.4k
    VLOG_CRITICAL << _parent->_sender_id << " close wait finished";
1281
47.4k
    return Status::OK();
1282
1.03M
}
1283
1284
Status VNodeChannel::after_close_handle(
1285
        RuntimeState* state, WriterStats* writer_stats,
1286
46.6k
        std::unordered_map<int64_t, AddBatchCounter>* node_add_batch_counter_map) {
1287
46.6k
    Status st = Status::Error<ErrorCode::INTERNAL_ERROR, false>(get_cancel_msg());
1288
46.6k
    _close_time_ms = UnixMillis() - _close_time_ms;
1289
1290
46.6k
    if (_add_batches_finished) {
1291
46.5k
        _close_check();
1292
46.5k
        _state->add_tablet_commit_infos(_tablet_commit_infos);
1293
1294
46.5k
        _index_channel->set_error_tablet_in_state(state);
1295
46.5k
        _index_channel->set_tablets_received_rows(_tablets_received_rows, _node_id);
1296
46.5k
        _index_channel->set_tablets_filtered_rows(_tablets_filtered_rows, _node_id);
1297
1298
46.5k
        std::lock_guard<std::mutex> l(_closed_lock);
1299
        // only when normal close, we set _is_closed to true.
1300
        // otherwise, we will set it to true in cancel().
1301
46.5k
        _is_closed = true;
1302
46.5k
        st = Status::OK();
1303
46.5k
    }
1304
1305
46.6k
    time_report(node_add_batch_counter_map, writer_stats);
1306
46.6k
    return st;
1307
46.6k
}
1308
1309
32.5k
Status VNodeChannel::check_status() {
1310
32.5k
    return none_of({_cancelled, !_eos_is_produced});
1311
32.5k
}
1312
1313
46.5k
void VNodeChannel::_close_check() {
1314
46.5k
    std::lock_guard<std::mutex> lg(_pending_batches_lock);
1315
18.4E
    CHECK(_pending_blocks.empty()) << name();
1316
18.4E
    CHECK(_cur_mutable_block == nullptr) << name();
1317
46.5k
}
1318
1319
46.6k
void VNodeChannel::mark_close(bool hang_wait) {
1320
46.6k
    auto st = none_of({_cancelled, _eos_is_produced});
1321
46.6k
    if (!st.ok()) {
1322
0
        return;
1323
0
    }
1324
1325
46.6k
    _cur_add_block_request->set_eos(true);
1326
46.6k
    _cur_add_block_request->set_hang_wait(hang_wait);
1327
46.6k
    {
1328
46.6k
        std::lock_guard<std::mutex> l(_pending_batches_lock);
1329
46.6k
        if (!_cur_mutable_block) [[unlikely]] {
1330
            // never had a block arrived. add a dummy block
1331
14.1k
            _cur_mutable_block = MutableBlock::create_unique();
1332
14.1k
        }
1333
46.6k
        auto tmp_add_block_request =
1334
46.6k
                std::make_shared<PTabletWriterAddBlockRequest>(*_cur_add_block_request);
1335
        // when prepare to close, add block to queue so that try_send_pending_block thread will send it.
1336
46.6k
        _pending_blocks.emplace(std::move(_cur_mutable_block), tmp_add_block_request);
1337
46.6k
        _pending_batches_num++;
1338
46.6k
        DCHECK(_pending_blocks.back().second->eos());
1339
46.6k
        _close_time_ms = UnixMillis();
1340
46.6k
        LOG(INFO) << channel_info()
1341
46.6k
                  << " mark closed, left pending batch size: " << _pending_blocks.size()
1342
46.6k
                  << " hang_wait: " << hang_wait;
1343
46.6k
    }
1344
1345
46.6k
    _eos_is_produced = true;
1346
46.6k
}
1347
1348
VTabletWriter::VTabletWriter(const TDataSink& t_sink, const VExprContextSPtrs& output_exprs,
1349
                             std::shared_ptr<Dependency> dep, std::shared_ptr<Dependency> fin_dep)
1350
45.4k
        : AsyncResultWriter(output_exprs, dep, fin_dep), _t_sink(t_sink) {
1351
45.4k
    _transfer_large_data_by_brpc = config::transfer_large_data_by_brpc;
1352
45.4k
}
1353
1354
45.6k
void VTabletWriter::_send_batch_process() {
1355
45.6k
    SCOPED_TIMER(_non_blocking_send_timer);
1356
45.6k
    SCOPED_ATTACH_TASK(_state);
1357
45.6k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
1358
1359
45.6k
    int sleep_time = int(config::olap_table_sink_send_interval_microseconds *
1360
45.6k
                         (_vpartition->is_auto_partition()
1361
45.6k
                                  ? config::olap_table_sink_send_interval_auto_partition_factor
1362
45.6k
                                  : 1));
1363
1364
13.2M
    while (true) {
1365
        // incremental open will temporarily make channels into abnormal state. stop checking when this.
1366
13.2M
        std::unique_lock<bthread::Mutex> l(_stop_check_channel);
1367
1368
13.2M
        int running_channels_num = 0;
1369
13.2M
        int opened_nodes = 0;
1370
17.6M
        for (const auto& index_channel : _channels) {
1371
17.6M
            index_channel->for_each_node_channel([&running_channels_num,
1372
17.6M
                                                  this](const std::shared_ptr<VNodeChannel>& ch) {
1373
                // if this channel all completed(cancelled), got 0. else 1.
1374
17.6M
                running_channels_num +=
1375
17.6M
                        ch->try_send_and_fetch_status(_state, this->_send_batch_thread_pool_token);
1376
17.6M
            });
1377
17.6M
            opened_nodes += index_channel->num_node_channels();
1378
17.6M
        }
1379
1380
        // auto partition table may have no node channel temporarily. wait to open.
1381
13.2M
        if (opened_nodes != 0 && running_channels_num == 0) {
1382
45.6k
            LOG(INFO) << "All node channels are stopped(maybe finished/offending/cancelled), "
1383
45.6k
                         "sender thread exit. "
1384
45.6k
                      << print_id(_load_id);
1385
45.6k
            return;
1386
45.6k
        }
1387
1388
        // for auto partition tables, there's a situation: we haven't open any node channel but decide to cancel the task.
1389
        // then the judge in front will never be true because opened_nodes won't increase. so we have to specially check wether we called close.
1390
        // we must RECHECK opened_nodes below, after got closed signal, because it may changed. Think of this:
1391
        //      checked opened_nodes = 0 ---> new block arrived ---> task finished, close() was called ---> we got _try_close here
1392
        // if we don't check again, we may lose the last package.
1393
13.2M
        if (_try_close.load(std::memory_order_acquire)) {
1394
235k
            opened_nodes = 0;
1395
235k
            std::ranges::for_each(_channels,
1396
2.15M
                                  [&opened_nodes](const std::shared_ptr<IndexChannel>& ich) {
1397
2.15M
                                      opened_nodes += ich->num_node_channels();
1398
2.15M
                                  });
1399
235k
            if (opened_nodes == 0) {
1400
0
                LOG(INFO) << "No node channel have ever opened but now we have to close. sender "
1401
0
                             "thread exit. "
1402
0
                          << print_id(_load_id);
1403
0
                return;
1404
0
            }
1405
235k
        }
1406
13.2M
        bthread_usleep(sleep_time);
1407
13.2M
    }
1408
45.6k
}
1409
1410
45.6k
static void* periodic_send_batch(void* writer) {
1411
45.6k
    auto* tablet_writer = (VTabletWriter*)(writer);
1412
45.6k
    tablet_writer->_send_batch_process();
1413
45.6k
    return nullptr;
1414
45.6k
}
1415
1416
45.6k
Status VTabletWriter::open(doris::RuntimeState* state, doris::RuntimeProfile* profile) {
1417
45.6k
    RETURN_IF_ERROR(_init(state, profile));
1418
45.6k
    signal::set_signal_task_id(_load_id);
1419
45.6k
    SCOPED_TIMER(profile->total_time_counter());
1420
45.6k
    SCOPED_TIMER(_open_timer);
1421
45.6k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker.get());
1422
1423
45.6k
    fmt::memory_buffer buf;
1424
46.6k
    for (const auto& index_channel : _channels) {
1425
46.6k
        fmt::format_to(buf, "index id:{}", index_channel->_index_id);
1426
46.6k
        index_channel->for_each_node_channel(
1427
46.6k
                [](const std::shared_ptr<VNodeChannel>& ch) { ch->open(); });
1428
46.6k
    }
1429
45.6k
    VLOG_DEBUG << "list of open index id = " << fmt::to_string(buf);
1430
1431
46.6k
    for (const auto& index_channel : _channels) {
1432
46.6k
        index_channel->set_start_time(UnixMillis());
1433
46.6k
        index_channel->for_each_node_channel([&index_channel](
1434
46.6k
                                                     const std::shared_ptr<VNodeChannel>& ch) {
1435
46.6k
            auto st = ch->open_wait();
1436
46.6k
            if (!st.ok()) {
1437
                // The open() phase is mainly to generate DeltaWriter instances on the nodes corresponding to each node channel.
1438
                // This phase will not fail due to a single tablet.
1439
                // Therefore, if the open() phase fails, all tablets corresponding to the node need to be marked as failed.
1440
0
                index_channel->mark_as_failed(
1441
0
                        ch.get(),
1442
0
                        fmt::format("{}, open failed, err: {}", ch->channel_info(), st.to_string()),
1443
0
                        -1);
1444
0
            }
1445
46.6k
        });
1446
1447
46.6k
        RETURN_IF_ERROR(index_channel->check_intolerable_failure());
1448
46.6k
    }
1449
45.6k
    _send_batch_thread_pool_token = state->exec_env()->send_batch_thread_pool()->new_token(
1450
45.6k
            ThreadPool::ExecutionMode::CONCURRENT, _send_batch_parallelism);
1451
1452
    // start to send batch continually. this must be called after _init
1453
45.6k
    if (bthread_start_background(&_sender_thread, nullptr, periodic_send_batch, (void*)this) != 0) {
1454
0
        return Status::Error<ErrorCode::INTERNAL_ERROR>("bthread_start_backgroud failed");
1455
0
    }
1456
45.6k
    return Status::OK();
1457
45.6k
}
1458
1459
184
Status VTabletWriter::on_partitions_created(TCreatePartitionResult* result) {
1460
    // add new tablet locations. it will use by address. so add to pool
1461
184
    auto* new_locations = _pool->add(new std::vector<TTabletLocation>(result->tablets));
1462
184
    _location->add_locations(*new_locations);
1463
184
    if (_write_single_replica) {
1464
0
        auto* slave_locations = _pool->add(new std::vector<TTabletLocation>(result->slave_tablets));
1465
0
        _slave_location->add_locations(*slave_locations);
1466
0
    }
1467
1468
    // update new node info
1469
184
    _nodes_info->add_nodes(result->nodes);
1470
1471
    // incremental open node channel
1472
184
    RETURN_IF_ERROR(_incremental_open_node_channel(result->partitions));
1473
1474
184
    return Status::OK();
1475
184
}
1476
1477
184
static Status on_partitions_created(void* writer, TCreatePartitionResult* result) {
1478
184
    return static_cast<VTabletWriter*>(writer)->on_partitions_created(result);
1479
184
}
1480
1481
45.2k
Status VTabletWriter::_init_row_distribution() {
1482
45.2k
    _row_distribution.init({.state = _state,
1483
45.2k
                            .block_convertor = _block_convertor.get(),
1484
45.2k
                            .tablet_finder = _tablet_finder.get(),
1485
45.2k
                            .vpartition = _vpartition,
1486
45.2k
                            .add_partition_request_timer = _add_partition_request_timer,
1487
45.2k
                            .txn_id = _txn_id,
1488
45.2k
                            .pool = _pool,
1489
45.2k
                            .location = _location,
1490
45.2k
                            .vec_output_expr_ctxs = &_vec_output_expr_ctxs,
1491
45.2k
                            .schema = _schema,
1492
45.2k
                            .caller = this,
1493
45.2k
                            .write_single_replica = _write_single_replica,
1494
45.2k
                            .create_partition_callback = &::doris::on_partitions_created});
1495
1496
45.2k
    return _row_distribution.open(_output_row_desc);
1497
45.2k
}
1498
1499
45.6k
Status VTabletWriter::_init(RuntimeState* state, RuntimeProfile* profile) {
1500
45.6k
    DCHECK(_t_sink.__isset.olap_table_sink);
1501
45.6k
    _pool = state->obj_pool();
1502
45.6k
    auto& table_sink = _t_sink.olap_table_sink;
1503
45.6k
    _load_id.set_hi(table_sink.load_id.hi);
1504
45.6k
    _load_id.set_lo(table_sink.load_id.lo);
1505
45.6k
    _txn_id = table_sink.txn_id;
1506
45.6k
    _num_replicas = table_sink.num_replicas;
1507
45.6k
    _tuple_desc_id = table_sink.tuple_id;
1508
45.6k
    _write_file_cache = table_sink.write_file_cache;
1509
45.6k
    _schema.reset(new OlapTableSchemaParam());
1510
45.6k
    RETURN_IF_ERROR(_schema->init(table_sink.schema));
1511
45.6k
    _schema->set_timestamp_ms(state->timestamp_ms());
1512
45.6k
    _schema->set_nano_seconds(state->nano_seconds());
1513
45.6k
    _schema->set_timezone(state->timezone());
1514
45.6k
    _location = _pool->add(new OlapTableLocationParam(table_sink.location));
1515
45.6k
    _nodes_info = _pool->add(new DorisNodesInfo(table_sink.nodes_info));
1516
45.6k
    if (table_sink.__isset.write_single_replica && table_sink.write_single_replica) {
1517
0
        _write_single_replica = true;
1518
0
        _slave_location = _pool->add(new OlapTableLocationParam(table_sink.slave_location));
1519
0
        if (!config::enable_single_replica_load) {
1520
0
            return Status::InternalError("single replica load is disabled on BE.");
1521
0
        }
1522
0
    }
1523
1524
45.6k
    if (config::is_cloud_mode() &&
1525
45.6k
        (!table_sink.__isset.txn_timeout_s || table_sink.txn_timeout_s <= 0)) {
1526
0
        return Status::InternalError("The txn_timeout_s of TDataSink is invalid");
1527
0
    }
1528
45.6k
    _txn_expiration = ::time(nullptr) + table_sink.txn_timeout_s;
1529
1530
45.6k
    if (table_sink.__isset.load_channel_timeout_s) {
1531
45.1k
        _load_channel_timeout_s = table_sink.load_channel_timeout_s;
1532
45.1k
    } else {
1533
524
        _load_channel_timeout_s = config::streaming_load_rpc_max_alive_time_sec;
1534
524
    }
1535
45.6k
    if (table_sink.__isset.send_batch_parallelism && table_sink.send_batch_parallelism > 1) {
1536
1
        _send_batch_parallelism = table_sink.send_batch_parallelism;
1537
1
    }
1538
    // if distributed column list is empty, we can ensure that tablet is with random distribution info
1539
    // and if load_to_single_tablet is set and set to true, we should find only one tablet in one partition
1540
    // for the whole olap table sink
1541
45.6k
    auto find_tablet_mode = OlapTabletFinder::FindTabletMode::FIND_TABLET_EVERY_ROW;
1542
45.6k
    if (table_sink.partition.distributed_columns.empty()) {
1543
9.11k
        if (table_sink.__isset.load_to_single_tablet && table_sink.load_to_single_tablet) {
1544
8
            find_tablet_mode = OlapTabletFinder::FindTabletMode::FIND_TABLET_EVERY_SINK;
1545
9.10k
        } else {
1546
9.10k
            find_tablet_mode = OlapTabletFinder::FindTabletMode::FIND_TABLET_EVERY_BATCH;
1547
9.10k
        }
1548
9.11k
    }
1549
45.6k
    _vpartition = _pool->add(new doris::VOlapTablePartitionParam(_schema, table_sink.partition));
1550
45.6k
    _tablet_finder = std::make_unique<OlapTabletFinder>(_vpartition, find_tablet_mode);
1551
45.6k
    RETURN_IF_ERROR(_vpartition->init());
1552
1553
45.6k
    _state = state;
1554
45.6k
    _operator_profile = profile;
1555
1556
45.6k
    _sender_id = state->per_fragment_instance_idx();
1557
45.6k
    _num_senders = state->num_per_fragment_instances();
1558
45.6k
    _is_high_priority =
1559
45.6k
            (state->execution_timeout() <= config::load_task_high_priority_threshold_second);
1560
45.6k
    DBUG_EXECUTE_IF("VTabletWriter._init.is_high_priority", { _is_high_priority = true; });
1561
    // profile must add to state's object pool
1562
45.6k
    _mem_tracker =
1563
45.6k
            std::make_shared<MemTracker>("OlapTableSink:" + std::to_string(state->load_job_id()));
1564
45.6k
    SCOPED_TIMER(profile->total_time_counter());
1565
45.6k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker.get());
1566
1567
    // get table's tuple descriptor
1568
45.6k
    _output_tuple_desc = state->desc_tbl().get_tuple_descriptor(_tuple_desc_id);
1569
45.6k
    if (_output_tuple_desc == nullptr) {
1570
0
        LOG(WARNING) << "unknown destination tuple descriptor, id=" << _tuple_desc_id;
1571
0
        return Status::InternalError("unknown destination tuple descriptor");
1572
0
    }
1573
1574
45.6k
    if (!_vec_output_expr_ctxs.empty() &&
1575
45.6k
        _output_tuple_desc->slots().size() != _vec_output_expr_ctxs.size()) {
1576
0
        LOG(WARNING) << "output tuple slot num should be equal to num of output exprs, "
1577
0
                     << "output_tuple_slot_num " << _output_tuple_desc->slots().size()
1578
0
                     << " output_expr_num " << _vec_output_expr_ctxs.size();
1579
0
        return Status::InvalidArgument(
1580
0
                "output_tuple_slot_num {} should be equal to output_expr_num {}",
1581
0
                _output_tuple_desc->slots().size(), _vec_output_expr_ctxs.size());
1582
0
    }
1583
1584
45.6k
    _block_convertor = std::make_unique<OlapTableBlockConvertor>(_output_tuple_desc);
1585
    // if partition_type is OLAP_TABLE_SINK_HASH_PARTITIONED, we handle the processing of auto_increment column
1586
    // on exchange node rather than on TabletWriter
1587
45.6k
    _block_convertor->init_autoinc_info(
1588
45.6k
            _schema->db_id(), _schema->table_id(), _state->batch_size(),
1589
45.6k
            _schema->is_fixed_partial_update() && !_schema->auto_increment_coulumn().empty(),
1590
45.6k
            _schema->auto_increment_column_unique_id());
1591
45.6k
    _output_row_desc = _pool->add(new RowDescriptor(_output_tuple_desc));
1592
1593
    // add all counter
1594
45.6k
    _input_rows_counter = ADD_COUNTER(profile, "RowsRead", TUnit::UNIT);
1595
45.6k
    _output_rows_counter = ADD_COUNTER(profile, "RowsProduced", TUnit::UNIT);
1596
45.6k
    _filtered_rows_counter = ADD_COUNTER(profile, "RowsFiltered", TUnit::UNIT);
1597
45.6k
    _send_data_timer = ADD_TIMER(profile, "SendDataTime");
1598
45.6k
    _wait_mem_limit_timer = ADD_CHILD_TIMER(profile, "WaitMemLimitTime", "SendDataTime");
1599
45.6k
    _row_distribution_timer = ADD_CHILD_TIMER(profile, "RowDistributionTime", "SendDataTime");
1600
45.6k
    _filter_timer = ADD_CHILD_TIMER(profile, "FilterTime", "SendDataTime");
1601
45.6k
    _where_clause_timer = ADD_CHILD_TIMER(profile, "WhereClauseTime", "SendDataTime");
1602
45.6k
    _append_node_channel_timer = ADD_CHILD_TIMER(profile, "AppendNodeChannelTime", "SendDataTime");
1603
45.6k
    _add_partition_request_timer =
1604
45.6k
            ADD_CHILD_TIMER(profile, "AddPartitionRequestTime", "SendDataTime");
1605
45.6k
    _validate_data_timer = ADD_TIMER(profile, "ValidateDataTime");
1606
45.6k
    _open_timer = ADD_TIMER(profile, "OpenTime");
1607
45.6k
    _close_timer = ADD_TIMER(profile, "CloseWaitTime");
1608
45.6k
    _non_blocking_send_timer = ADD_TIMER(profile, "NonBlockingSendTime");
1609
45.6k
    _non_blocking_send_work_timer =
1610
45.6k
            ADD_CHILD_TIMER(profile, "NonBlockingSendWorkTime", "NonBlockingSendTime");
1611
45.6k
    _serialize_batch_timer =
1612
45.6k
            ADD_CHILD_TIMER(profile, "SerializeBatchTime", "NonBlockingSendWorkTime");
1613
45.6k
    _total_add_batch_exec_timer = ADD_TIMER(profile, "TotalAddBatchExecTime");
1614
45.6k
    _max_add_batch_exec_timer = ADD_TIMER(profile, "MaxAddBatchExecTime");
1615
45.6k
    _total_wait_exec_timer = ADD_TIMER(profile, "TotalWaitExecTime");
1616
45.6k
    _max_wait_exec_timer = ADD_TIMER(profile, "MaxWaitExecTime");
1617
45.6k
    _add_batch_number = ADD_COUNTER(profile, "NumberBatchAdded", TUnit::UNIT);
1618
45.6k
    _num_node_channels = ADD_COUNTER(profile, "NumberNodeChannels", TUnit::UNIT);
1619
45.6k
    _load_back_pressure_version_time_ms = ADD_TIMER(profile, "LoadBackPressureVersionTimeMs");
1620
1621
#ifdef DEBUG
1622
    // check: tablet ids should be unique
1623
    {
1624
        std::unordered_set<int64_t> tablet_ids;
1625
        const auto& partitions = _vpartition->get_partitions();
1626
        for (int i = 0; i < _schema->indexes().size(); ++i) {
1627
            for (const auto& partition : partitions) {
1628
                for (const auto& tablet : partition->indexes[i].tablets) {
1629
                    CHECK(tablet_ids.count(tablet) == 0) << "found duplicate tablet id: " << tablet;
1630
                    tablet_ids.insert(tablet);
1631
                }
1632
            }
1633
        }
1634
    }
1635
#endif
1636
1637
    // open all channels
1638
45.6k
    const auto& partitions = _vpartition->get_partitions();
1639
91.4k
    for (int i = 0; i < _schema->indexes().size(); ++i) {
1640
        // collect all tablets belong to this rollup
1641
45.7k
        std::vector<TTabletWithPartition> tablets;
1642
45.7k
        auto* index = _schema->indexes()[i];
1643
60.5k
        for (const auto& part : partitions) {
1644
356k
            for (const auto& tablet : part->indexes[i].tablets) {
1645
356k
                TTabletWithPartition tablet_with_partition;
1646
356k
                tablet_with_partition.partition_id = part->id;
1647
356k
                tablet_with_partition.tablet_id = tablet;
1648
356k
                tablets.emplace_back(std::move(tablet_with_partition));
1649
356k
                _build_tablet_replica_info(tablet, part);
1650
356k
            }
1651
60.5k
        }
1652
45.7k
        if (tablets.empty() && !_vpartition->is_auto_partition()) {
1653
0
            LOG(WARNING) << "load job:" << state->load_job_id() << " index: " << index->index_id
1654
0
                         << " would open 0 tablet";
1655
0
        }
1656
45.7k
        _channels.emplace_back(new IndexChannel(this, index->index_id, index->where_clause));
1657
45.7k
        _index_id_to_channel[index->index_id] = _channels.back();
1658
45.7k
        RETURN_IF_ERROR(_channels.back()->init(state, tablets));
1659
45.7k
    }
1660
1661
45.6k
    RETURN_IF_ERROR(_init_row_distribution());
1662
1663
45.6k
    _inited = true;
1664
45.6k
    return Status::OK();
1665
45.6k
}
1666
1667
Status VTabletWriter::_incremental_open_node_channel(
1668
184
        const std::vector<TOlapTablePartition>& partitions) {
1669
    // do what we did in prepare() for partitions. indexes which don't change when we create new partition is orthogonal to partitions.
1670
184
    std::unique_lock<bthread::Mutex> _l(_stop_check_channel);
1671
368
    for (int i = 0; i < _schema->indexes().size(); ++i) {
1672
184
        const OlapTableIndexSchema* index = _schema->indexes()[i];
1673
184
        std::vector<TTabletWithPartition> tablets;
1674
381
        for (const auto& t_part : partitions) {
1675
381
            VOlapTablePartition* part = nullptr;
1676
381
            RETURN_IF_ERROR(_vpartition->generate_partition_from(t_part, part));
1677
6.64k
            for (const auto& tablet : part->indexes[i].tablets) {
1678
6.64k
                TTabletWithPartition tablet_with_partition;
1679
6.64k
                tablet_with_partition.partition_id = part->id;
1680
6.64k
                tablet_with_partition.tablet_id = tablet;
1681
6.64k
                tablets.emplace_back(std::move(tablet_with_partition));
1682
6.64k
                _build_tablet_replica_info(tablet, part);
1683
6.64k
            }
1684
381
            DCHECK(!tablets.empty()) << "incremental open got nothing!";
1685
381
        }
1686
        // update and reinit for existing channels.
1687
184
        std::shared_ptr<IndexChannel> channel = _index_id_to_channel[index->index_id];
1688
184
        DCHECK(channel != nullptr);
1689
184
        RETURN_IF_ERROR(channel->init(_state, tablets, true)); // add tablets into it
1690
184
    }
1691
1692
184
    fmt::memory_buffer buf;
1693
184
    for (auto& channel : _channels) {
1694
        // incremental open new partition's tablet on storage side
1695
184
        channel->for_each_node_channel(
1696
184
                [](const std::shared_ptr<VNodeChannel>& ch) { ch->incremental_open(); });
1697
184
        fmt::format_to(buf, "index id:{}", channel->_index_id);
1698
184
        VLOG_DEBUG << "list of open index id = " << fmt::to_string(buf);
1699
1700
184
        channel->for_each_node_channel([&channel](const std::shared_ptr<VNodeChannel>& ch) {
1701
184
            auto st = ch->open_wait();
1702
184
            if (!st.ok()) {
1703
                // The open() phase is mainly to generate DeltaWriter instances on the nodes corresponding to each node channel.
1704
                // This phase will not fail due to a single tablet.
1705
                // Therefore, if the open() phase fails, all tablets corresponding to the node need to be marked as failed.
1706
0
                channel->mark_as_failed(
1707
0
                        ch.get(),
1708
0
                        fmt::format("{}, open failed, err: {}", ch->channel_info(), st.to_string()),
1709
0
                        -1);
1710
0
            }
1711
184
        });
1712
1713
184
        RETURN_IF_ERROR(channel->check_intolerable_failure());
1714
184
    }
1715
1716
184
    return Status::OK();
1717
184
}
1718
1719
void VTabletWriter::_build_tablet_replica_info(const int64_t tablet_id,
1720
362k
                                               VOlapTablePartition* partition) {
1721
362k
    if (partition != nullptr) {
1722
362k
        int total_replicas_num =
1723
362k
                partition->total_replica_num == 0 ? _num_replicas : partition->total_replica_num;
1724
362k
        int load_required_replicas_num = partition->load_required_replica_num == 0
1725
362k
                                                 ? (_num_replicas + 1) / 2
1726
362k
                                                 : partition->load_required_replica_num;
1727
362k
        _tablet_replica_info.emplace(
1728
362k
                tablet_id, std::make_pair(total_replicas_num, load_required_replicas_num));
1729
        // Copy version gap backends info for this tablet
1730
362k
        if (auto it = partition->tablet_version_gap_backends.find(tablet_id);
1731
362k
            it != partition->tablet_version_gap_backends.end()) {
1732
0
            _tablet_version_gap_backends[tablet_id] = it->second;
1733
0
        }
1734
18.4E
    } else {
1735
18.4E
        _tablet_replica_info.emplace(tablet_id,
1736
18.4E
                                     std::make_pair(_num_replicas, (_num_replicas + 1) / 2));
1737
18.4E
    }
1738
362k
}
1739
1740
176
void VTabletWriter::_cancel_all_channel(Status status) {
1741
176
    for (const auto& index_channel : _channels) {
1742
176
        index_channel->for_each_node_channel([&status](const std::shared_ptr<VNodeChannel>& ch) {
1743
176
            ch->cancel(status.to_string());
1744
176
        });
1745
176
    }
1746
176
    LOG(INFO) << fmt::format(
1747
176
            "close olap table sink. load_id={}, txn_id={}, canceled all node channels due to "
1748
176
            "error: {}",
1749
176
            print_id(_load_id), _txn_id, status);
1750
176
}
1751
1752
85.0k
Status VTabletWriter::_send_new_partition_batch() {
1753
85.0k
    if (_row_distribution.need_deal_batching()) { // maybe try_close more than 1 time
1754
165
        RETURN_IF_ERROR(_row_distribution.automatic_create_partition());
1755
1756
165
        Block tmp_block = _row_distribution._batching_block->to_block(); // Borrow out, for lval ref
1757
1758
        // these order is unique.
1759
        //  1. clear batching stats(and flag goes true) so that we won't make a new batching process in dealing batched block.
1760
        //  2. deal batched block
1761
        //  3. now reuse the column of lval block. cuz write doesn't real adjust it. it generate a new block from that.
1762
165
        _row_distribution.clear_batching_stats();
1763
165
        Defer recover_batching_block([&]() {
1764
165
            _row_distribution._batching_block->set_mutable_columns(
1765
165
                    std::move(tmp_block).mutate_columns());
1766
165
            _row_distribution._batching_block->clear_column_data();
1767
165
        });
1768
165
        RETURN_IF_ERROR(this->write(_state, tmp_block));
1769
165
        _row_distribution._deal_batched = false;
1770
165
    }
1771
85.0k
    return Status::OK();
1772
85.0k
}
1773
1774
45.6k
void VTabletWriter::_do_try_close(RuntimeState* state, const Status& exec_status) {
1775
45.6k
    SCOPED_TIMER(_close_timer);
1776
45.6k
    Status status = exec_status;
1777
1778
    // must before set _try_close
1779
45.6k
    if (status.ok()) {
1780
45.5k
        SCOPED_TIMER(_operator_profile->total_time_counter());
1781
45.5k
        _row_distribution._deal_batched = true;
1782
45.5k
        status = _send_new_partition_batch();
1783
45.5k
    }
1784
1785
45.6k
    _try_close.store(true, std::memory_order_release); // will stop periodic thread
1786
45.6k
    if (status.ok()) {
1787
        // BE id -> add_batch method counter
1788
45.5k
        std::unordered_map<int64_t, AddBatchCounter> node_add_batch_counter_map;
1789
1790
        // only if status is ok can we call this _profile->total_time_counter().
1791
        // if status is not ok, this sink may not be prepared, so that _profile is null
1792
45.5k
        SCOPED_TIMER(_operator_profile->total_time_counter());
1793
46.6k
        for (const auto& index_channel : _channels) {
1794
            // two-step mark close. first we send close_origin to recievers to close all originly exist TabletsChannel.
1795
            // when they all closed, we are sure all Writer of instances called _do_try_close. that means no new channel
1796
            // will be opened. the refcount of recievers will be monotonically decreasing. then we are safe to close all
1797
            // our channels.
1798
46.6k
            if (index_channel->has_incremental_node_channel()) {
1799
0
                if (!status.ok()) {
1800
0
                    break;
1801
0
                }
1802
0
                VLOG_TRACE << _sender_id << " first stage close start " << _txn_id;
1803
0
                index_channel->for_init_node_channel(
1804
0
                        [&index_channel, &status, this](const std::shared_ptr<VNodeChannel>& ch) {
1805
0
                            if (!status.ok() || ch->is_closed()) {
1806
0
                                return;
1807
0
                            }
1808
0
                            VLOG_DEBUG << index_channel->_parent->_sender_id << "'s " << ch->host()
1809
0
                                       << "mark close1 for inits " << _txn_id;
1810
0
                            ch->mark_close(true);
1811
0
                            if (ch->is_cancelled()) {
1812
0
                                status = cancel_channel_and_check_intolerable_failure(
1813
0
                                        std::move(status), ch->get_cancel_msg(), *index_channel,
1814
0
                                        *ch);
1815
0
                            }
1816
0
                        });
1817
0
                if (!status.ok()) {
1818
0
                    break;
1819
0
                }
1820
                // Do not need to wait after quorum success,
1821
                // for first-stage close_wait only ensure incremental node channels load has been completed,
1822
                // unified waiting in the second-stage close_wait.
1823
0
                status = index_channel->close_wait(_state, nullptr, nullptr,
1824
0
                                                   index_channel->init_node_channel_ids(), false);
1825
0
                if (!status.ok()) {
1826
0
                    break;
1827
0
                }
1828
0
                VLOG_DEBUG << _sender_id << " first stage finished. closeing inc nodes " << _txn_id;
1829
0
                index_channel->for_inc_node_channel(
1830
0
                        [&index_channel, &status, this](const std::shared_ptr<VNodeChannel>& ch) {
1831
0
                            if (!status.ok() || ch->is_closed()) {
1832
0
                                return;
1833
0
                            }
1834
                            // only first try close, all node channels will mark_close()
1835
0
                            VLOG_DEBUG << index_channel->_parent->_sender_id << "'s " << ch->host()
1836
0
                                       << "mark close2 for inc " << _txn_id;
1837
0
                            ch->mark_close();
1838
0
                            if (ch->is_cancelled()) {
1839
0
                                status = cancel_channel_and_check_intolerable_failure(
1840
0
                                        std::move(status), ch->get_cancel_msg(), *index_channel,
1841
0
                                        *ch);
1842
0
                            }
1843
0
                        });
1844
46.6k
            } else { // not has_incremental_node_channel
1845
46.6k
                VLOG_TRACE << _sender_id << " has no incremental channels " << _txn_id;
1846
46.6k
                index_channel->for_each_node_channel(
1847
46.6k
                        [&index_channel, &status](const std::shared_ptr<VNodeChannel>& ch) {
1848
46.6k
                            if (!status.ok() || ch->is_closed()) {
1849
0
                                return;
1850
0
                            }
1851
                            // only first try close, all node channels will mark_close()
1852
46.6k
                            ch->mark_close();
1853
46.6k
                            if (ch->is_cancelled()) {
1854
0
                                status = cancel_channel_and_check_intolerable_failure(
1855
0
                                        std::move(status), ch->get_cancel_msg(), *index_channel,
1856
0
                                        *ch);
1857
0
                            }
1858
46.6k
                        });
1859
46.6k
            }
1860
46.6k
        } // end for index channels
1861
45.5k
    }
1862
1863
45.6k
    if (!status.ok()) {
1864
128
        _cancel_all_channel(status);
1865
128
        _close_status = status;
1866
128
    }
1867
45.6k
}
1868
1869
45.6k
Status VTabletWriter::close(Status exec_status) {
1870
45.6k
    if (!_inited) {
1871
0
        DCHECK(!exec_status.ok());
1872
0
        _cancel_all_channel(exec_status);
1873
0
        _close_status = exec_status;
1874
0
        return _close_status;
1875
0
    }
1876
1877
45.6k
    SCOPED_TIMER(_close_timer);
1878
45.6k
    SCOPED_TIMER(_operator_profile->total_time_counter());
1879
1880
    // will make the last batch of request-> close_wait will wait this finished.
1881
45.6k
    _do_try_close(_state, exec_status);
1882
45.6k
    TEST_INJECTION_POINT("VOlapTableSink::close");
1883
1884
45.6k
    DBUG_EXECUTE_IF("VTabletWriter.close.sleep", {
1885
45.6k
        auto sleep_sec = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
1886
45.6k
                "VTabletWriter.close.sleep", "sleep_sec", 1);
1887
45.6k
        std::this_thread::sleep_for(std::chrono::seconds(sleep_sec));
1888
45.6k
    });
1889
45.6k
    DBUG_EXECUTE_IF("VTabletWriter.close.close_status_not_ok",
1890
45.6k
                    { _close_status = Status::InternalError("injected close status not ok"); });
1891
1892
    // If _close_status is not ok, all nodes have been canceled in try_close.
1893
45.6k
    if (_close_status.ok()) {
1894
45.5k
        auto status = Status::OK();
1895
        // BE id -> add_batch method counter
1896
45.5k
        std::unordered_map<int64_t, AddBatchCounter> node_add_batch_counter_map;
1897
45.5k
        WriterStats writer_stats;
1898
1899
46.6k
        for (const auto& index_channel : _channels) {
1900
46.6k
            if (!status.ok()) {
1901
0
                break;
1902
0
            }
1903
46.6k
            int64_t add_batch_exec_time = 0;
1904
46.6k
            int64_t wait_exec_time = 0;
1905
46.6k
            status = index_channel->close_wait(_state, &writer_stats, &node_add_batch_counter_map,
1906
46.6k
                                               index_channel->each_node_channel_ids(), true);
1907
1908
            // Due to the non-determinism of compaction, the rowsets of each replica may be different from each other on different
1909
            // BE nodes. The number of rows filtered in SegmentWriter depends on the historical rowsets located in the correspoding
1910
            // BE node. So we check the number of rows filtered on each succeccful BE to ensure the consistency of the current load
1911
46.6k
            if (status.ok() && !_write_single_replica && _schema->is_strict_mode() &&
1912
46.6k
                _schema->is_partial_update()) {
1913
62
                if (Status st = index_channel->check_tablet_filtered_rows_consistency(); !st.ok()) {
1914
0
                    status = st;
1915
62
                } else {
1916
62
                    _state->set_num_rows_filtered_in_strict_mode_partial_update(
1917
62
                            index_channel->num_rows_filtered());
1918
62
                }
1919
62
            }
1920
1921
46.6k
            writer_stats.num_node_channels += index_channel->num_node_channels();
1922
46.6k
            writer_stats.max_add_batch_exec_time_ns =
1923
46.6k
                    std::max(add_batch_exec_time, writer_stats.max_add_batch_exec_time_ns);
1924
46.6k
            writer_stats.max_wait_exec_time_ns =
1925
46.6k
                    std::max(wait_exec_time, writer_stats.max_wait_exec_time_ns);
1926
46.6k
        } // end for index channels
1927
1928
45.5k
        if (status.ok()) {
1929
            // TODO need to be improved
1930
45.5k
            LOG(INFO) << "total mem_exceeded_block_ns="
1931
45.5k
                      << writer_stats.channel_stat.mem_exceeded_block_ns
1932
45.5k
                      << ", total queue_push_lock_ns=" << writer_stats.queue_push_lock_ns
1933
45.5k
                      << ", total actual_consume_ns=" << writer_stats.actual_consume_ns
1934
45.5k
                      << ", load id=" << print_id(_load_id) << ", txn_id=" << _txn_id;
1935
1936
45.5k
            COUNTER_SET(_input_rows_counter, _number_input_rows);
1937
45.5k
            COUNTER_SET(_output_rows_counter, _number_output_rows);
1938
45.5k
            COUNTER_SET(_filtered_rows_counter,
1939
45.5k
                        _block_convertor->num_filtered_rows() +
1940
45.5k
                                _tablet_finder->num_filtered_rows() +
1941
45.5k
                                _state->num_rows_filtered_in_strict_mode_partial_update());
1942
45.5k
            COUNTER_SET(_send_data_timer, _send_data_ns);
1943
45.5k
            COUNTER_SET(_row_distribution_timer, (int64_t)_row_distribution_watch.elapsed_time());
1944
45.5k
            COUNTER_SET(_filter_timer, _filter_ns);
1945
45.5k
            COUNTER_SET(_append_node_channel_timer,
1946
45.5k
                        writer_stats.channel_stat.append_node_channel_ns);
1947
45.5k
            COUNTER_SET(_where_clause_timer, writer_stats.channel_stat.where_clause_ns);
1948
45.5k
            COUNTER_SET(_wait_mem_limit_timer, writer_stats.channel_stat.mem_exceeded_block_ns);
1949
45.5k
            COUNTER_SET(_validate_data_timer, _block_convertor->validate_data_ns());
1950
45.5k
            COUNTER_SET(_serialize_batch_timer, writer_stats.serialize_batch_ns);
1951
45.5k
            COUNTER_SET(_non_blocking_send_work_timer, writer_stats.actual_consume_ns);
1952
45.5k
            COUNTER_SET(_total_add_batch_exec_timer, writer_stats.total_add_batch_exec_time_ns);
1953
45.5k
            COUNTER_SET(_max_add_batch_exec_timer, writer_stats.max_add_batch_exec_time_ns);
1954
45.5k
            COUNTER_SET(_total_wait_exec_timer, writer_stats.total_wait_exec_time_ns);
1955
45.5k
            COUNTER_SET(_max_wait_exec_timer, writer_stats.max_wait_exec_time_ns);
1956
45.5k
            COUNTER_SET(_add_batch_number, writer_stats.total_add_batch_num);
1957
45.5k
            COUNTER_SET(_num_node_channels, writer_stats.num_node_channels);
1958
45.5k
            COUNTER_SET(_load_back_pressure_version_time_ms,
1959
45.5k
                        writer_stats.load_back_pressure_version_time_ms);
1960
45.5k
            g_sink_load_back_pressure_version_time_ms
1961
45.5k
                    << writer_stats.load_back_pressure_version_time_ms;
1962
1963
            // _number_input_rows don't contain num_rows_load_filtered and num_rows_load_unselected in scan node
1964
45.5k
            int64_t num_rows_load_total = _number_input_rows + _state->num_rows_load_filtered() +
1965
45.5k
                                          _state->num_rows_load_unselected();
1966
45.5k
            _state->set_num_rows_load_total(num_rows_load_total);
1967
45.5k
            _state->update_num_rows_load_filtered(
1968
45.5k
                    _block_convertor->num_filtered_rows() + _tablet_finder->num_filtered_rows() +
1969
45.5k
                    _state->num_rows_filtered_in_strict_mode_partial_update());
1970
45.5k
            _state->update_num_rows_load_unselected(
1971
45.5k
                    _tablet_finder->num_immutable_partition_filtered_rows());
1972
1973
45.5k
            if (_state->enable_profile() && _state->profile_level() >= 2) {
1974
                // Output detailed profiling info for auto-partition requests
1975
6
                _row_distribution.output_profile_info(_operator_profile);
1976
6
            }
1977
1978
            // print log of add batch time of all node, for tracing load performance easily
1979
45.5k
            std::stringstream ss;
1980
45.5k
            ss << "finished to close olap table sink. load_id=" << print_id(_load_id)
1981
45.5k
               << ", txn_id=" << _txn_id
1982
45.5k
               << ", node add batch time(ms)/wait execution time(ms)/close time(ms)/num: ";
1983
45.5k
            for (auto const& pair : node_add_batch_counter_map) {
1984
45.5k
                ss << "{" << pair.first << ":(" << (pair.second.add_batch_execution_time_us / 1000)
1985
45.5k
                   << ")(" << (pair.second.add_batch_wait_execution_time_us / 1000) << ")("
1986
45.5k
                   << pair.second.close_wait_time_ms << ")(" << pair.second.add_batch_num << ")} ";
1987
45.5k
            }
1988
45.5k
            LOG(INFO) << ss.str();
1989
45.5k
        } else {
1990
45
            _cancel_all_channel(status);
1991
45
        }
1992
45.5k
        _close_status = status;
1993
45.5k
    }
1994
1995
    // Sender join() must put after node channels mark_close/cancel.
1996
    // But there is no specific sequence required between sender join() & close_wait().
1997
45.6k
    if (_sender_thread) {
1998
45.6k
        bthread_join(_sender_thread, nullptr);
1999
        // We have to wait all task in _send_batch_thread_pool_token finished,
2000
        // because it is difficult to handle concurrent problem if we just
2001
        // shutdown it.
2002
45.6k
        _send_batch_thread_pool_token->wait();
2003
45.6k
    }
2004
2005
    // We clear NodeChannels' batches here, cuz NodeChannels' batches destruction will use
2006
    // OlapTableSink::_mem_tracker and its parents.
2007
    // But their destructions are after OlapTableSink's.
2008
46.8k
    for (const auto& index_channel : _channels) {
2009
46.8k
        index_channel->for_each_node_channel(
2010
46.8k
                [](const std::shared_ptr<VNodeChannel>& ch) { ch->clear_all_blocks(); });
2011
46.8k
    }
2012
45.6k
    return _close_status;
2013
45.6k
}
2014
2015
void VTabletWriter::_generate_one_index_channel_payload(
2016
        RowPartTabletIds& row_part_tablet_id, int32_t index_idx,
2017
40.5k
        ChannelDistributionPayload& channel_payload) {
2018
40.5k
    auto& row_ids = row_part_tablet_id.row_ids;
2019
40.5k
    auto& tablet_ids = row_part_tablet_id.tablet_ids;
2020
2021
40.5k
    size_t row_cnt = row_ids.size();
2022
2023
35.7M
    for (size_t i = 0; i < row_ids.size(); i++) {
2024
        // (tablet_id, VNodeChannel) where this tablet locate
2025
35.7M
        auto it = _channels[index_idx]->_channels_by_tablet.find(tablet_ids[i]);
2026
18.4E
        DCHECK(it != _channels[index_idx]->_channels_by_tablet.end())
2027
18.4E
                << "unknown tablet, tablet_id=" << tablet_ids[i];
2028
2029
35.7M
        std::vector<std::shared_ptr<VNodeChannel>>& tablet_locations = it->second;
2030
35.7M
        for (const auto& locate_node : tablet_locations) {
2031
35.7M
            auto payload_it = channel_payload.find(locate_node.get()); // <VNodeChannel*, Payload>
2032
35.7M
            if (payload_it == channel_payload.end()) {
2033
40.2k
                auto [tmp_it, _] = channel_payload.emplace(
2034
40.2k
                        locate_node.get(),
2035
40.2k
                        Payload {std::make_unique<IColumn::Selector>(), std::vector<int64_t>()});
2036
40.2k
                payload_it = tmp_it;
2037
40.2k
                payload_it->second.first->reserve(row_cnt);
2038
40.2k
                payload_it->second.second.reserve(row_cnt);
2039
40.2k
            }
2040
35.7M
            payload_it->second.first->push_back(row_ids[i]);
2041
35.7M
            payload_it->second.second.push_back(tablet_ids[i]);
2042
35.7M
        }
2043
35.7M
    }
2044
40.5k
}
2045
2046
void VTabletWriter::_generate_index_channels_payloads(
2047
        std::vector<RowPartTabletIds>& row_part_tablet_ids,
2048
39.5k
        ChannelDistributionPayloadVec& payload) {
2049
80.1k
    for (int i = 0; i < _schema->indexes().size(); i++) {
2050
40.5k
        _generate_one_index_channel_payload(row_part_tablet_ids[i], i, payload[i]);
2051
40.5k
    }
2052
39.5k
}
2053
2054
39.5k
Status VTabletWriter::write(RuntimeState* state, doris::Block& input_block) {
2055
39.5k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker.get());
2056
39.5k
    Status status = Status::OK();
2057
2058
39.5k
    DCHECK(_state);
2059
39.5k
    DCHECK(_state->query_options().__isset.dry_run_query);
2060
39.5k
    if (_state->query_options().dry_run_query) {
2061
1
        return status;
2062
1
    }
2063
2064
    // check out of limit
2065
39.5k
    RETURN_IF_ERROR(_send_new_partition_batch());
2066
2067
39.5k
    auto rows = input_block.rows();
2068
39.5k
    auto bytes = input_block.bytes();
2069
39.5k
    if (UNLIKELY(rows == 0)) {
2070
0
        return status;
2071
0
    }
2072
39.5k
    SCOPED_TIMER(_operator_profile->total_time_counter());
2073
39.5k
    SCOPED_RAW_TIMER(&_send_data_ns);
2074
2075
39.5k
    std::shared_ptr<Block> block;
2076
39.5k
    _number_input_rows += rows;
2077
    // update incrementally so that FE can get the progress.
2078
    // the real 'num_rows_load_total' will be set when sink being closed.
2079
39.5k
    _state->update_num_rows_load_total(rows);
2080
39.5k
    _state->update_num_bytes_load_total(bytes);
2081
39.5k
    DorisMetrics::instance()->load_rows->increment(rows);
2082
39.5k
    DorisMetrics::instance()->load_bytes->increment(bytes);
2083
2084
39.5k
    _row_distribution_watch.start();
2085
39.5k
    RETURN_IF_ERROR(_row_distribution.generate_rows_distribution(
2086
39.5k
            input_block, block, _row_part_tablet_ids, _number_input_rows));
2087
2088
39.5k
    ChannelDistributionPayloadVec channel_to_payload;
2089
2090
39.5k
    channel_to_payload.resize(_channels.size());
2091
39.5k
    _generate_index_channels_payloads(_row_part_tablet_ids, channel_to_payload);
2092
39.5k
    _row_distribution_watch.stop();
2093
2094
    // Add block to node channel
2095
80.1k
    for (size_t i = 0; i < _channels.size(); i++) {
2096
40.5k
        for (const auto& entry : channel_to_payload[i]) {
2097
            // if this node channel is already failed, this add_row will be skipped
2098
            // entry.second is a [row -> tablet] mapping
2099
40.2k
            auto st = entry.first->add_block(block.get(), &entry.second);
2100
40.2k
            if (!st.ok()) {
2101
0
                _channels[i]->mark_as_failed(entry.first, st.to_string());
2102
0
            }
2103
40.2k
        }
2104
40.5k
    }
2105
2106
    // check intolerable failure
2107
40.5k
    for (const auto& index_channel : _channels) {
2108
40.5k
        RETURN_IF_ERROR(index_channel->check_intolerable_failure());
2109
40.5k
    }
2110
2111
39.5k
    g_sink_write_bytes << bytes;
2112
39.5k
    g_sink_write_rows << rows;
2113
39.5k
    return Status::OK();
2114
39.5k
}
2115
2116
} // namespace doris