Coverage Report

Created: 2026-08-07 00:28

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