Coverage Report

Created: 2026-06-23 19:09

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