Coverage Report

Created: 2026-08-06 15:03

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