Coverage Report

Created: 2026-04-22 11:43

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