Coverage Report

Created: 2026-07-17 19:12

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