Coverage Report

Created: 2026-08-07 05:10

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
44.6k
                                                         int64_t index_id) {
106
44.6k
    for (const auto& index : partition.indexes) {
107
44.5k
        if (index.index_id == index_id) {
108
44.5k
            return &index;
109
44.5k
        }
110
44.4k
    }
111
115
    return nullptr;
112
44.6k
}
113
114
static int64_t adaptive_bucket_be_id(const VOlapTablePartition& partition,
115
34.7k
                                     const OlapTableIndexTablets* index) {
116
34.7k
    if (index != nullptr && index->__isset.bucket_be_id) {
117
18.4E
        return index->bucket_be_id > 0 ? index->bucket_be_id : BackendOptions::get_backend_id();
118
30.5k
    }
119
4.24k
    return partition.bucket_be_id > 0 ? partition.bucket_be_id : BackendOptions::get_backend_id();
120
34.7k
}
121
122
static const std::vector<int32_t>& adaptive_local_bucket_seqs(const VOlapTablePartition& partition,
123
9.56k
                                                              const OlapTableIndexTablets* index) {
124
9.56k
    if (index != nullptr && index->__isset.local_bucket_seqs) {
125
9.30k
        return index->local_bucket_seqs;
126
9.30k
    }
127
253
    return partition.local_bucket_seqs;
128
9.56k
}
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
49.2k
                          bool incremental) {
134
49.2k
    SCOPED_CONSUME_MEM_TRACKER(_index_channel_tracker.get());
135
384k
    for (const auto& tablet : tablets) {
136
        // First find the location BEs of this tablet
137
384k
        auto* tablet_locations = _parent->_location->find_tablet(tablet.tablet_id);
138
384k
        if (tablet_locations == nullptr) {
139
0
            return Status::InternalError("unknown tablet, tablet_id={}", tablet.tablet_id);
140
0
        }
141
384k
        std::vector<std::shared_ptr<VNodeChannel>> channels;
142
        // For tablet, deal with its' all replica (in some node).
143
384k
        for (auto& replica_node_id : tablet_locations->node_ids) {
144
383k
            std::shared_ptr<VNodeChannel> channel;
145
383k
            auto it = _node_channels.find(replica_node_id);
146
            // when we prepare for TableSink or incremental open tablet, we need init
147
383k
            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
50.2k
                channel =
152
50.2k
                        std::make_shared<VNodeChannel>(_parent, this, replica_node_id, incremental);
153
50.2k
                _node_channels.emplace(replica_node_id, channel);
154
                // incremental opened new node. when close we have use two-stage close.
155
50.2k
                if (incremental) {
156
0
                    _has_inc_node = true;
157
0
                }
158
50.2k
                VLOG_CRITICAL << "init new node for instance " << _parent->_sender_id
159
576
                              << ", node id:" << replica_node_id << ", incremantal:" << incremental;
160
333k
            } else {
161
333k
                channel = it->second;
162
333k
            }
163
383k
            channel->add_tablet(tablet);
164
383k
            if (_parent->_tablet_finder->is_adaptive_random_bucket() && config::is_cloud_mode()) {
165
43.7k
                for (const auto* part : _parent->_vpartition->get_partitions()) {
166
43.7k
                    if (part->id != tablet.partition_id) {
167
8.93k
                        continue;
168
8.93k
                    }
169
34.8k
                    const auto* index = find_partition_index(*part, _index_id);
170
34.8k
                    const auto bucket_be_id = adaptive_bucket_be_id(*part, index);
171
34.8k
                    if (bucket_be_id != replica_node_id) {
172
0
                        continue;
173
0
                    }
174
34.8k
                    _channels_by_partition.emplace(tablet.partition_id, channel);
175
34.8k
                    break;
176
34.8k
                }
177
34.8k
            }
178
383k
            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
383k
            channels.push_back(channel);
185
383k
            _tablets_by_channel[replica_node_id].insert(tablet.tablet_id);
186
383k
        }
187
384k
        _channels_by_tablet.emplace(tablet.tablet_id, std::move(channels));
188
384k
    }
189
50.3k
    for (auto& it : _node_channels) {
190
50.3k
        RETURN_IF_ERROR(it.second->init(state));
191
50.3k
    }
192
49.2k
    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
49.2k
    return Status::OK();
198
49.2k
}
199
200
void IndexChannel::mark_as_failed(const VNodeChannel* node_channel, const std::string& err,
201
44
                                  int64_t tablet_id) {
202
44
    DCHECK(node_channel != nullptr);
203
44
    LOG(INFO) << "mark node_id:" << node_channel->channel_info() << " tablet_id: " << tablet_id
204
44
              << " as failed, err: " << err;
205
44
    auto node_id = node_channel->node_id();
206
44
    const auto& it = _tablets_by_channel.find(node_id);
207
44
    if (it == _tablets_by_channel.end()) {
208
0
        return;
209
0
    }
210
211
44
    {
212
44
        std::lock_guard<std::mutex> l(_fail_lock);
213
44
        if (tablet_id == -1) {
214
138
            for (const auto the_tablet_id : it->second) {
215
138
                _failed_channels[the_tablet_id].insert(node_id);
216
138
                _failed_channels_msgs.emplace(the_tablet_id,
217
138
                                              err + ", host: " + node_channel->host());
218
138
                if (_failed_channels[the_tablet_id].size() > _max_failed_replicas(the_tablet_id)) {
219
138
                    _intolerable_failure_status = Status::Error<ErrorCode::INTERNAL_ERROR, false>(
220
138
                            _failed_channels_msgs[the_tablet_id]);
221
138
                }
222
138
            }
223
44
        } 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
44
    }
232
44
}
233
234
138
int IndexChannel::_max_failed_replicas(int64_t tablet_id) {
235
138
    auto [total_replicas_num, load_required_replicas_num] =
236
138
            _parent->_tablet_replica_info[tablet_id];
237
138
    int max_failed_replicas = total_replicas_num == 0
238
138
                                      ? (_parent->_num_replicas - 1) / 2
239
138
                                      : total_replicas_num - load_required_replicas_num;
240
138
    return max_failed_replicas;
241
138
}
242
243
248k
int IndexChannel::_load_required_replicas_num(int64_t tablet_id) {
244
248k
    auto [total_replicas_num, load_required_replicas_num] =
245
248k
            _parent->_tablet_replica_info[tablet_id];
246
248k
    if (total_replicas_num == 0) {
247
0
        return (_parent->_num_replicas + 1) / 2;
248
0
    }
249
248k
    return load_required_replicas_num;
250
248k
}
251
252
150k
Status IndexChannel::check_intolerable_failure() {
253
150k
    std::lock_guard<std::mutex> l(_fail_lock);
254
150k
    return _intolerable_failure_status;
255
150k
}
256
257
50.1k
void IndexChannel::set_error_tablet_in_state(RuntimeState* state) {
258
50.1k
    std::vector<TErrorTabletInfo> error_tablet_infos;
259
260
50.1k
    {
261
50.1k
        std::lock_guard<std::mutex> l(_fail_lock);
262
50.1k
        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
50.1k
    }
269
50.1k
    state->add_error_tablet_infos(error_tablet_infos);
270
50.1k
}
271
272
void IndexChannel::set_tablets_received_rows(
273
50.3k
        const std::vector<std::pair<int64_t, int64_t>>& tablets_received_rows, int64_t node_id) {
274
203k
    for (const auto& [tablet_id, rows_num] : tablets_received_rows) {
275
203k
        _tablets_received_rows[tablet_id].emplace_back(node_id, rows_num);
276
203k
    }
277
50.3k
}
278
279
void IndexChannel::set_tablets_filtered_rows(
280
50.3k
        const std::vector<std::pair<int64_t, int64_t>>& tablets_filtered_rows, int64_t node_id) {
281
203k
    for (const auto& [tablet_id, rows_num] : tablets_filtered_rows) {
282
203k
        _tablets_filtered_rows[tablet_id].emplace_back(node_id, rows_num);
283
203k
    }
284
50.3k
}
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
75
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
75
    return Status::OK();
332
75
}
333
334
static Status cancel_channel_and_check_intolerable_failure(Status status,
335
                                                           const std::string& err_msg,
336
44
                                                           IndexChannel& ich, VNodeChannel& nch) {
337
44
    LOG(WARNING) << nch.channel_info() << ", close channel failed, err: " << err_msg;
338
44
    ich.mark_as_failed(&nch, err_msg, -1);
339
    // cancel the node channel in best effort
340
44
    nch.cancel(err_msg);
341
342
    // check if index has intolerable failure
343
44
    if (Status index_st = ich.check_intolerable_failure(); !index_st.ok()) {
344
44
        status = std::move(index_st);
345
44
    } 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
44
    return status;
351
44
}
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
15
        return;
357
15
    }
358
52.9k
    static_cast<void>(_close_wait_cv.wait_for(lock, timeout_ms * 1000));
359
52.9k
}
360
361
50.5k
void IndexChannel::notify_close_wait() {
362
50.5k
    _close_wait_version.fetch_add(1, std::memory_order_acq_rel);
363
50.5k
    std::lock_guard<bthread::Mutex> lock(_close_wait_mutex);
364
50.5k
    _close_wait_cv.notify_all();
365
50.5k
}
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
50.3k
        bool need_wait_after_quorum_success) {
372
50.3k
    DBUG_EXECUTE_IF("IndexChannel.close_wait.timeout",
373
50.3k
                    { return Status::TimedOut("injected timeout"); });
374
50.3k
    Status status = Status::OK();
375
    // 1. wait quorum success
376
50.3k
    std::unordered_set<int64_t> need_finish_tablets;
377
50.3k
    auto partition_ids = _parent->_tablet_finder->partition_ids();
378
64.7k
    for (const auto& part : _parent->_vpartition->get_partitions()) {
379
64.7k
        if (partition_ids.contains(part->id)) {
380
45.0k
            for (const auto& index : part->indexes) {
381
250k
                for (const auto& tablet_id : index.tablets) {
382
250k
                    need_finish_tablets.insert(tablet_id);
383
250k
                }
384
45.0k
            }
385
36.9k
        }
386
64.7k
    }
387
103k
    while (true) {
388
103k
        int64_t close_wait_version = this->close_wait_version();
389
103k
        RETURN_IF_ERROR(check_each_node_channel_close(
390
103k
                &unfinished_node_channel_ids, node_add_batch_counter_map, writer_stats, status));
391
103k
        bool quorum_success = _quorum_success(unfinished_node_channel_ids, need_finish_tablets);
392
103k
        if (unfinished_node_channel_ids.empty() || quorum_success) {
393
50.2k
            LOG(INFO) << "quorum_success: " << quorum_success
394
50.2k
                      << ", is all finished: " << unfinished_node_channel_ids.empty()
395
50.2k
                      << ", txn_id: " << _parent->_txn_id
396
50.2k
                      << ", load_id: " << print_id(_parent->_load_id);
397
50.2k
            break;
398
50.2k
        }
399
53.1k
        wait_for_close_event(close_wait_version, CLOSE_WAIT_EVENT_FALLBACK_MS);
400
53.1k
    }
401
402
    // 2. wait for all node channel to complete as much as possible
403
50.3k
    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
50.3k
    return status;
436
50.3k
}
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
103k
        WriterStats* writer_stats, Status status) {
442
103k
    Status final_status = Status::OK();
443
103k
    for (auto& it : _node_channels) {
444
103k
        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
103k
        if (!unfinished_node_channel_ids->contains(it.first)) {
448
0
            continue;
449
0
        }
450
103k
        bool node_channel_closed = false;
451
103k
        auto close_status = it.second->close_wait(_parent->_state, &node_channel_closed);
452
103k
        if (node_channel_closed) {
453
50.3k
            close_status = it.second->after_close_handle(_parent->_state, writer_stats,
454
50.3k
                                                         node_add_batch_counter_map);
455
50.3k
            unfinished_node_channel_ids->erase(it.first);
456
50.3k
        }
457
103k
        DBUG_EXECUTE_IF("IndexChannel.check_each_node_channel_close.close_status_not_ok",
458
103k
                        { close_status = Status::InternalError("injected close status not ok"); });
459
103k
        if (!close_status.ok()) {
460
44
            final_status = cancel_channel_and_check_intolerable_failure(
461
44
                    std::move(final_status), close_status.to_string(), *this, *it.second);
462
44
        }
463
103k
    }
464
465
103k
    return final_status;
466
103k
}
467
468
bool IndexChannel::_quorum_success(const std::unordered_set<int64_t>& unfinished_node_channel_ids,
469
102k
                                   const std::unordered_set<int64_t>& need_finish_tablets) {
470
102k
    if (!config::enable_quorum_success_write) {
471
0
        return false;
472
0
    }
473
102k
    if (need_finish_tablets.empty()) [[unlikely]] {
474
32.1k
        return false;
475
32.1k
    }
476
477
    // 1. collect all write tablets and finished tablets
478
70.7k
    std::unordered_map<int64_t, int64_t> finished_tablets_replica;
479
70.9k
    for (const auto& [node_id, node_channel] : _node_channels) {
480
70.9k
        if (unfinished_node_channel_ids.contains(node_id) || !node_channel->check_status().ok()) {
481
36.9k
            continue;
482
36.9k
        }
483
294k
        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
294k
            auto gap_it = _parent->_tablet_version_gap_backends.find(tablet_id);
487
294k
            if (gap_it == _parent->_tablet_version_gap_backends.end() ||
488
294k
                gap_it->second.find(node_id) == gap_it->second.end()) {
489
294k
                finished_tablets_replica[tablet_id]++;
490
294k
            }
491
294k
        }
492
34.0k
    }
493
494
    // 2. check if quorum success
495
248k
    for (const auto& tablet_id : need_finish_tablets) {
496
248k
        if (finished_tablets_replica[tablet_id] < _load_required_replicas_num(tablet_id)) {
497
38.4k
            return false;
498
38.4k
        }
499
248k
    }
500
501
32.3k
    return true;
502
70.7k
}
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
230k
static Status none_of(std::initializer_list<bool> vars) {
549
460k
    bool none = std::none_of(vars.begin(), vars.end(), [](bool var) { return var; });
550
230k
    Status st = Status::OK();
551
230k
    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
230k
    return st;
562
230k
}
563
564
VNodeChannel::VNodeChannel(VTabletWriter* parent, IndexChannel* index_channel, int64_t node_id,
565
                           bool is_incremental)
566
49.5k
        : _parent(parent),
567
49.5k
          _index_channel(index_channel),
568
49.5k
          _node_id(node_id),
569
49.5k
          _is_incremental(is_incremental) {
570
49.5k
    _cur_add_block_request = std::make_shared<PTabletWriterAddBlockRequest>();
571
49.5k
    _node_channel_tracker = std::make_shared<MemTracker>(
572
49.5k
            fmt::format("NodeChannel:indexID={}:threadId={}",
573
49.5k
                        std::to_string(_index_channel->_index_id), ThreadContext::get_thread_id()));
574
49.5k
    _load_mem_limit = MemInfo::mem_limit() * config::load_process_max_memory_limit_percent / 100;
575
49.5k
}
576
577
50.4k
VNodeChannel::~VNodeChannel() = default;
578
579
50.5k
void VNodeChannel::clear_all_blocks() {
580
50.5k
    std::lock_guard<std::mutex> lg(_pending_batches_lock);
581
50.5k
    std::queue<AddBlockReq> empty;
582
50.5k
    std::swap(_pending_blocks, empty);
583
50.5k
    _cur_mutable_block.reset();
584
50.5k
}
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
49.7k
Status VNodeChannel::init(RuntimeState* state) {
592
49.7k
    if (_inited) {
593
201
        return Status::OK();
594
201
    }
595
596
49.5k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
597
49.5k
    _task_exec_ctx = state->get_task_execution_context();
598
49.5k
    _tuple_desc = _parent->_output_tuple_desc;
599
49.5k
    _state = state;
600
    // get corresponding BE node.
601
49.5k
    const auto* node = _parent->_nodes_info->find_node(_node_id);
602
49.5k
    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
49.5k
    _node_info = *node;
608
609
49.5k
    _load_info = "load_id=" + print_id(_parent->_load_id) +
610
49.5k
                 ", txn_id=" + std::to_string(_parent->_txn_id);
611
612
49.5k
    _row_desc = std::make_unique<RowDescriptor>(_tuple_desc);
613
49.5k
    _batch_size = state->batch_size();
614
615
49.5k
    _stub = state->exec_env()->brpc_internal_client_cache()->get_client(_node_info.host,
616
49.5k
                                                                        _node_info.brpc_port);
617
49.5k
    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
49.5k
    _rpc_timeout_ms = state->execution_timeout() * 1000;
625
49.5k
    _timeout_watch.start();
626
627
    // Initialize _cur_add_block_request
628
50.5k
    if (!_cur_add_block_request->has_id()) {
629
50.5k
        *(_cur_add_block_request->mutable_id()) = _parent->_load_id;
630
50.5k
    }
631
49.5k
    _cur_add_block_request->set_index_id(_index_channel->_index_id);
632
49.5k
    _cur_add_block_request->set_sender_id(_parent->_sender_id);
633
49.5k
    _cur_add_block_request->set_backend_id(_node_id);
634
49.5k
    _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
49.5k
    _cur_add_block_request->set_is_adaptive_random_bucket(
638
49.5k
            _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
49.5k
    _send_block_callback = WriteBlockCallback<PTabletWriterAddBlockResult>::create_shared();
643
49.5k
    _send_block_callback->addFailedHandler(
644
49.5k
            [&, 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
49.5k
    _send_block_callback->addSuccessHandler(
653
49.5k
            [&, task_exec_ctx = _task_exec_ctx](const PTabletWriterAddBlockResult& result,
654
56.8k
                                                const WriteBlockCallbackContext& ctx) {
655
56.8k
                std::shared_ptr<TaskExecutionContext> ctx_lock = task_exec_ctx.lock();
656
56.8k
                if (ctx_lock == nullptr) {
657
0
                    return;
658
0
                }
659
56.8k
                _add_block_success_callback(result, ctx);
660
56.8k
            });
661
662
49.5k
    _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
49.5k
    _batch_size = std::max(_batch_size, 8192);
669
670
50.2k
    if (_state) {
671
50.2k
        QueryContext* query_ctx = _state->get_query_ctx();
672
50.3k
        if (query_ctx) {
673
50.3k
            auto wg_ptr = query_ctx->workload_group();
674
50.3k
            if (wg_ptr) {
675
50.3k
                _wg_id = wg_ptr->id();
676
50.3k
            }
677
50.3k
        }
678
50.2k
    }
679
680
49.5k
    _inited = true;
681
49.5k
    return Status::OK();
682
49.5k
}
683
684
9.42k
void VNodeChannel::_set_adaptive_random_bucket_open_request(PTabletWriterOpenRequest* request) {
685
9.42k
    std::unordered_map<int64_t, std::vector<int64_t>> partition_to_ordered_tablets;
686
9.42k
    std::unordered_map<int64_t, std::unordered_set<int64_t>> partition_to_local_tablets;
687
35.4k
    for (const auto& tablet : _all_tablets) {
688
35.4k
        partition_to_ordered_tablets[tablet.partition_id].push_back(tablet.tablet_id);
689
35.4k
        partition_to_local_tablets[tablet.partition_id].insert(tablet.tablet_id);
690
35.4k
    }
691
9.42k
    std::unordered_map<int64_t, const VOlapTablePartition*> id_to_partition;
692
9.81k
    for (const auto* part : _parent->_vpartition->get_partitions()) {
693
9.81k
        id_to_partition.emplace(part->id, part);
694
9.81k
    }
695
9.87k
    for (const auto& [partition_id, ordered_tablets] : partition_to_ordered_tablets) {
696
9.87k
        auto partition_it = id_to_partition.find(partition_id);
697
9.87k
        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.87k
        const auto* index_info =
703
9.87k
                find_partition_index(*partition_it->second, _index_channel->_index_id);
704
9.87k
        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.87k
        std::vector<int64_t> selected_ordered_tablets;
711
9.87k
        const auto& local_bucket_seqs =
712
9.87k
                adaptive_local_bucket_seqs(*partition_it->second, index_info);
713
9.87k
        if (!local_bucket_seqs.empty()) {
714
9.30k
            const auto& full_ordered_tablets = index_info->tablets;
715
30.7k
            for (auto bucket_seq : local_bucket_seqs) {
716
30.7k
                if (bucket_seq < 0 ||
717
30.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
30.7k
                auto tablet_id = full_ordered_tablets[bucket_seq];
725
30.7k
                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
30.7k
                selected_ordered_tablets.push_back(tablet_id);
733
30.7k
            }
734
9.30k
        } else {
735
573
            selected_ordered_tablets = ordered_tablets;
736
573
        }
737
9.87k
        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.87k
        _adaptive_partition_compat_tablets[partition_id] = selected_ordered_tablets.front();
745
9.87k
        auto* random_bucket_partition = request->add_random_bucket_partitions();
746
9.87k
        random_bucket_partition->set_partition_id(partition_id);
747
35.5k
        for (auto tablet_id : selected_ordered_tablets) {
748
35.5k
            random_bucket_partition->add_ordered_tablet_ids(tablet_id);
749
35.5k
        }
750
9.87k
    }
751
9.42k
}
752
753
50.2k
void VNodeChannel::_open_internal(bool is_incremental) {
754
50.2k
    if (_tablets_wait_open.empty()) {
755
0
        return;
756
0
    }
757
50.2k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
758
50.2k
    auto request = std::make_shared<PTabletWriterOpenRequest>();
759
50.2k
    request->mutable_id()->CopyFrom(_parent->_load_id);
760
50.2k
    request->set_index_id(_index_channel->_index_id);
761
50.2k
    request->set_txn_id(_parent->_txn_id);
762
50.2k
    request->set_sender_id(_parent->_sender_id);
763
50.2k
    request->mutable_schema()->CopyFrom(*_parent->_schema->to_protobuf());
764
50.2k
    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
50.2k
    request->set_is_adaptive_random_bucket(_parent->_tablet_finder->is_adaptive_random_bucket());
769
50.2k
    std::set<int64_t> deduper;
770
383k
    for (auto& tablet : _tablets_wait_open) {
771
383k
        if (deduper.contains(tablet.tablet_id)) {
772
0
            continue;
773
0
        }
774
383k
        auto* ptablet = request->add_tablets();
775
383k
        ptablet->set_partition_id(tablet.partition_id);
776
383k
        ptablet->set_tablet_id(tablet.tablet_id);
777
383k
        deduper.insert(tablet.tablet_id);
778
383k
        _all_tablets.push_back(std::move(tablet));
779
383k
    }
780
50.2k
    _tablets_wait_open.clear();
781
782
50.2k
    request->set_num_senders(_parent->_num_senders);
783
50.2k
    request->set_need_gen_rollup(false); // Useless but it is a required field in pb
784
50.2k
    request->set_load_channel_timeout_s(_parent->_load_channel_timeout_s);
785
50.2k
    request->set_is_high_priority(_parent->_is_high_priority);
786
50.2k
    request->set_sender_ip(BackendOptions::get_localhost());
787
50.2k
    request->set_is_vectorized(true);
788
50.2k
    request->set_backend_id(_node_id);
789
50.2k
    request->set_enable_profile(_state->enable_profile());
790
50.2k
    request->set_is_incremental(is_incremental);
791
50.2k
    request->set_txn_expiration(_parent->_txn_expiration);
792
50.2k
    request->set_write_file_cache(_parent->_write_file_cache);
793
794
50.2k
    if (_parent->_tablet_finder->is_adaptive_random_bucket()) {
795
9.56k
        _set_adaptive_random_bucket_open_request(request.get());
796
9.56k
    }
797
798
50.2k
    if (_wg_id > 0) {
799
50.1k
        request->set_workload_group_id(_wg_id);
800
50.1k
    }
801
802
50.2k
    auto open_callback = DummyBrpcCallback<PTabletWriterOpenResult>::create_shared();
803
50.2k
    auto open_closure = AutoReleaseClosure<
804
50.2k
            PTabletWriterOpenRequest,
805
50.2k
            DummyBrpcCallback<PTabletWriterOpenResult>>::create_unique(request, open_callback);
806
50.2k
    open_callback->cntl_->set_timeout_ms(config::tablet_writer_open_rpc_timeout_sec * 1000);
807
50.2k
    if (config::tablet_writer_ignore_eovercrowded) {
808
50.0k
        open_callback->cntl_->ignore_eovercrowded();
809
50.0k
    }
810
50.2k
    VLOG_DEBUG << fmt::format("txn {}: open NodeChannel to {}, incremental: {}, senders: {}",
811
50
                              _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
50.2k
    _stub->tablet_writer_open(open_closure->cntl_.get(), open_closure->request_.get(),
814
50.2k
                              open_closure->response_.get(), open_closure.get());
815
50.2k
    open_closure.release();
816
50.2k
    _open_callbacks.push_back(open_callback);
817
50.2k
}
818
819
50.2k
void VNodeChannel::open() {
820
50.2k
    _open_internal(false);
821
50.2k
}
822
823
201
void VNodeChannel::incremental_open() {
824
201
    VLOG_DEBUG << "incremental opening node channel" << _node_id;
825
201
    _open_internal(true);
826
201
}
827
828
50.3k
Status VNodeChannel::open_wait() {
829
50.3k
    Status status;
830
50.6k
    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
50.6k
        if (open_callback == nullptr) {
833
0
            continue;
834
0
        }
835
836
50.6k
        open_callback->join();
837
50.6k
        SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
838
50.6k
        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
50.6k
        status = Status::create(open_callback->response_->status());
857
858
50.6k
        if (!status.ok()) {
859
0
            _cancelled = true;
860
0
            return status;
861
0
        }
862
50.6k
    }
863
864
50.3k
    return status;
865
50.3k
}
866
867
42.4k
Status VNodeChannel::add_block(Block* block, const Payload* payload) {
868
42.4k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
869
42.4k
    if (payload->row_part_tablet_ids == nullptr || payload->row_ids == nullptr ||
870
42.4k
        payload->row_ids->empty()) {
871
0
        return Status::OK();
872
0
    }
873
42.4k
    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
42.4k
    auto st = none_of({_cancelled, _eos_is_produced});
876
42.4k
    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
42.4k
    constexpr int64_t kBackPressureSleepMs = 10;
892
42.4k
    auto* memtable_limiter = ExecEnv::GetInstance()->memtable_memory_limiter();
893
42.4k
    while (true) {
894
42.4k
        bool is_exceed_soft_mem_limit = GlobalMemoryArbitrator::is_exceed_soft_mem_limit();
895
42.4k
        int64_t memtable_mem =
896
42.4k
                (memtable_limiter != nullptr && memtable_limiter->mem_tracker() != nullptr)
897
42.4k
                        ? memtable_limiter->mem_tracker()->consumption()
898
42.4k
                        : 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
42.4k
        auto current_load_mem_value = MemoryProfile::load_current_usage() + memtable_mem;
903
42.4k
        bool mem_limit_exceeded = is_exceed_soft_mem_limit ||
904
42.4k
                                  current_load_mem_value > _load_mem_limit ||
905
42.4k
                                  _pending_batches_bytes > _max_pending_batches_bytes;
906
42.4k
        bool need_back_pressure = !_cancelled && !_state->is_cancelled() &&
907
42.4k
                                  _pending_batches_num > 0 && mem_limit_exceeded;
908
42.4k
        if (!need_back_pressure) {
909
42.4k
            break;
910
42.4k
        }
911
18.4E
        SCOPED_RAW_TIMER(&_stat.mem_exceeded_block_ns);
912
18.4E
        std::this_thread::sleep_for(std::chrono::milliseconds(kBackPressureSleepMs));
913
18.4E
    }
914
915
42.4k
    if (UNLIKELY(!_cur_mutable_block)) {
916
34.1k
        _cur_mutable_block = MutableBlock::create_unique(block->clone_empty());
917
34.1k
    }
918
919
42.4k
    SCOPED_RAW_TIMER(&_stat.append_node_channel_ns);
920
42.4k
    st = block->append_to_block_by_selector(_cur_mutable_block.get(), *payload->row_ids);
921
42.4k
    if (!st.ok()) {
922
0
        _cancel_with_msg(fmt::format("{}, err: {}", channel_info(), st.to_string()));
923
0
        return st;
924
0
    }
925
42.4k
    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
34.0M
        } else {
939
34.0M
            _cur_add_block_request->add_tablet_ids(row_part_tablet_ids->tablet_ids[route_idx]);
940
34.0M
        }
941
36.0M
    }
942
42.4k
    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
42.4k
    _write_bytes.fetch_add(_cur_mutable_block->bytes());
946
947
42.4k
    if (_cur_mutable_block->rows() >= _batch_size ||
948
42.4k
        _cur_mutable_block->bytes() > config::doris_scanner_row_bytes) {
949
2.33k
        {
950
2.33k
            SCOPED_ATOMIC_TIMER(&_queue_push_lock_ns);
951
2.33k
            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.33k
            _pending_batches_bytes += _cur_mutable_block->allocated_bytes();
954
2.33k
            _cur_add_block_request->set_eos(
955
2.33k
                    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.33k
            auto tmp_add_block_request = std::make_shared<PTabletWriterAddBlockRequest>();
958
2.33k
            *tmp_add_block_request = *_cur_add_block_request;
959
2.33k
            _pending_blocks.emplace(std::move(_cur_mutable_block), tmp_add_block_request);
960
2.33k
            _pending_batches_num++;
961
2.33k
            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.33k
        }
966
2.33k
        _cur_mutable_block = MutableBlock::create_unique(block->clone_empty());
967
2.33k
        _cur_add_block_request->clear_tablet_ids();
968
2.33k
        _cur_add_block_request->clear_partition_ids();
969
2.33k
        _cur_add_block_request->clear_row_binlog_lsns();
970
2.33k
    }
971
972
42.4k
    return Status::OK();
973
42.4k
}
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
14.9M
                                            std::unique_ptr<ThreadPoolToken>& thread_pool_token) {
981
14.9M
    DBUG_EXECUTE_IF("VNodeChannel.try_send_and_fetch_status_full_gc", {
982
14.9M
        std::thread t(injection_full_gc_fn);
983
14.9M
        t.join();
984
14.9M
    });
985
986
15.0M
    if (_cancelled || _send_finished) { // not run
987
125k
        return 0;
988
125k
    }
989
990
14.8M
    auto load_back_pressure_version_wait_time_ms = _load_back_pressure_version_wait_time_ms.load();
991
14.8M
    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.8M
    if (!_send_block_callback->try_set_in_flight()) {
1001
        // There is packet in flight, skip.
1002
440k
        return _send_finished ? 0 : 1;
1003
440k
    }
1004
1005
    // We are sure that try_send_batch is not running
1006
14.4M
    if (_pending_batches_num > 0) {
1007
56.9k
        auto s = thread_pool_token->submit_func([this, state] { try_send_pending_block(state); });
1008
56.9k
        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
14.3M
    } else {
1015
        // sending finished. clear in flight
1016
14.3M
        _send_block_callback->clear_in_flight();
1017
14.3M
    }
1018
14.4M
    return _send_finished ? 0 : 1;
1019
14.8M
}
1020
1021
212
void VNodeChannel::_cancel_with_msg(const std::string& msg) {
1022
212
    LOG(WARNING) << "cancel node channel " << channel_info() << ", error message: " << msg;
1023
212
    {
1024
212
        std::lock_guard<std::mutex> l(_cancel_msg_lock);
1025
212
        if (_cancel_msg.empty()) {
1026
168
            _cancel_msg = msg;
1027
168
        }
1028
212
    }
1029
212
    _cancelled = true;
1030
212
    _index_channel->notify_close_wait();
1031
212
}
1032
1033
void VNodeChannel::_refresh_back_pressure_version_wait_time(
1034
        const ::google::protobuf::RepeatedPtrField<::doris::PTabletLoadRowsetInfo>&
1035
56.6k
                tablet_load_infos) {
1036
56.6k
    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
56.6k
    std::for_each(
1040
56.6k
            tablet_load_infos.begin(), tablet_load_infos.end(),
1041
56.6k
            [&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
56.6k
    auto max_time = config::max_load_back_pressure_version_wait_time_ms;
1062
56.6k
    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
56.6k
}
1071
1072
56.9k
void VNodeChannel::try_send_pending_block(RuntimeState* state) {
1073
56.9k
    SCOPED_ATTACH_TASK(state);
1074
56.9k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker);
1075
56.9k
    SCOPED_ATOMIC_TIMER(&_actual_consume_ns);
1076
56.9k
    signal::set_signal_task_id(_parent->_load_id);
1077
56.9k
    AddBlockReq send_block;
1078
56.9k
    {
1079
56.9k
        std::lock_guard<std::mutex> l(_pending_batches_lock);
1080
56.9k
        DCHECK(!_pending_blocks.empty());
1081
56.9k
        send_block = std::move(_pending_blocks.front());
1082
56.9k
        _pending_blocks.pop();
1083
56.9k
        _pending_batches_num--;
1084
56.9k
        _pending_batches_bytes -= send_block.first->allocated_bytes();
1085
56.9k
    }
1086
1087
56.9k
    auto mutable_block = std::move(send_block.first);
1088
56.9k
    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
56.9k
    request->set_packet_seq(_next_packet_seq);
1092
56.9k
    auto block = mutable_block->to_block();
1093
56.9k
    int request_rows = request->is_adaptive_random_bucket() && !request->eos()
1094
56.9k
                               ? request->partition_ids_size()
1095
56.9k
                               : request->tablet_ids_size();
1096
56.9k
    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
56.9k
    if (block.rows() > 0) {
1106
36.1k
        SCOPED_ATOMIC_TIMER(&_serialize_batch_ns);
1107
36.1k
        size_t uncompressed_bytes = 0, compressed_bytes = 0;
1108
36.1k
        int64_t compressed_time = 0;
1109
36.1k
        Status st = block.serialize(state->be_exec_version(), request->mutable_block(),
1110
36.1k
                                    &uncompressed_bytes, &compressed_bytes, &compressed_time,
1111
36.1k
                                    state->fragement_transmission_compression_type(),
1112
36.1k
                                    _parent->_transfer_large_data_by_brpc);
1113
36.1k
        TEST_INJECTION_POINT_CALLBACK("VNodeChannel::try_send_block", &st);
1114
36.1k
        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.1k
        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.1k
    }
1125
1126
56.9k
    auto remain_ms = _rpc_timeout_ms - _timeout_watch.elapsed_time() / NANOS_PER_MILLIS;
1127
56.9k
    if (UNLIKELY(remain_ms < config::min_load_rpc_timeout_ms)) {
1128
46
        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
46
        } else {
1134
46
            remain_ms = config::min_load_rpc_timeout_ms;
1135
46
        }
1136
46
    }
1137
1138
56.9k
    _send_block_callback->reset();
1139
56.9k
    _send_block_callback->cntl_->set_timeout_ms(remain_ms);
1140
56.9k
    if (config::tablet_writer_ignore_eovercrowded) {
1141
56.8k
        _send_block_callback->cntl_->ignore_eovercrowded();
1142
56.8k
    }
1143
1144
56.9k
    if (request->eos()) {
1145
50.3k
        if (!request->is_adaptive_random_bucket() || !request->has_block()) {
1146
50.3k
            for (auto pid : _parent->_tablet_finder->partition_ids()) {
1147
37.0k
                request->add_partition_ids(pid);
1148
37.0k
            }
1149
50.3k
        }
1150
1151
50.3k
        request->set_write_single_replica(_parent->_write_single_replica);
1152
50.3k
        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
50.3k
        _send_block_callback->end_mark();
1183
50.3k
        _send_finished = true;
1184
18.4E
        CHECK(_pending_batches_num == 0) << _pending_batches_num;
1185
50.3k
    }
1186
1187
56.9k
    auto send_block_closure = AutoReleaseClosure<
1188
56.9k
            PTabletWriterAddBlockRequest,
1189
56.9k
            WriteBlockCallback<PTabletWriterAddBlockResult>>::create_unique(request,
1190
56.9k
                                                                            _send_block_callback);
1191
56.9k
    if (_parent->_transfer_large_data_by_brpc && request->has_block() &&
1192
56.9k
        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
56.9k
    } else {
1238
56.9k
        _send_block_callback->cntl_->http_request().Clear();
1239
56.9k
        {
1240
56.9k
            _stub->tablet_writer_add_block(
1241
56.9k
                    send_block_closure->cntl_.get(), send_block_closure->request_.get(),
1242
56.9k
                    send_block_closure->response_.get(), send_block_closure.get());
1243
56.9k
            send_block_closure.release();
1244
56.9k
        }
1245
56.9k
    }
1246
1247
56.9k
    _next_packet_seq++;
1248
56.9k
}
1249
1250
void VNodeChannel::_add_block_success_callback(const PTabletWriterAddBlockResult& result,
1251
56.7k
                                               const WriteBlockCallbackContext& ctx) {
1252
56.7k
    std::lock_guard<std::mutex> l(this->_closed_lock);
1253
56.7k
    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
56.7k
    SCOPED_ATTACH_TASK(_state);
1259
56.7k
    Status status(Status::create(result.status()));
1260
56.8k
    if (status.ok()) {
1261
56.8k
        _refresh_back_pressure_version_wait_time(result.tablet_load_rowset_num_infos());
1262
        // if has error tablet, handle them first
1263
56.8k
        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
56.8k
        Status st = _index_channel->check_intolerable_failure();
1268
56.8k
        if (!st.ok()) {
1269
0
            _cancel_with_msg(st.to_string());
1270
56.8k
        } else if (ctx._is_last_rpc) {
1271
203k
            for (const auto& tablet : result.tablet_vec()) {
1272
203k
                DBUG_EXECUTE_IF("VNodeChannel.add_block_success_callback.incomplete_commit_info", {
1273
203k
                    auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
1274
203k
                    if (tablet.tablet_id() == target_tablet_id) {
1275
203k
                        LOG(INFO) << "skip tablet info: " << tablet.tablet_id()
1276
203k
                                  << ", backend_id: " << _node_id;
1277
203k
                        continue;
1278
203k
                    }
1279
203k
                });
1280
203k
                TTabletCommitInfo commit_info;
1281
203k
                commit_info.tabletId = tablet.tablet_id();
1282
203k
                commit_info.backendId = _node_id;
1283
203k
                _tablet_commit_infos.emplace_back(std::move(commit_info));
1284
203k
                if (tablet.has_received_rows()) {
1285
203k
                    _tablets_received_rows.emplace_back(tablet.tablet_id(), tablet.received_rows());
1286
203k
                }
1287
203k
                if (tablet.has_num_rows_filtered()) {
1288
203k
                    _tablets_filtered_rows.emplace_back(tablet.tablet_id(),
1289
203k
                                                        tablet.num_rows_filtered());
1290
203k
                }
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
203k
            }
1296
50.3k
            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
50.3k
            _add_batches_finished = true;
1312
50.3k
            _index_channel->notify_close_wait();
1313
50.3k
        }
1314
18.4E
    } else {
1315
18.4E
        _cancel_with_msg(fmt::format("{}, add batch req success but status isn't ok, err: {}",
1316
18.4E
                                     channel_info(), status.to_string()));
1317
18.4E
    }
1318
1319
56.9k
    if (result.has_execution_time_us()) {
1320
56.9k
        _add_batch_counter.add_batch_execution_time_us += result.execution_time_us();
1321
56.9k
        _add_batch_counter.add_batch_wait_execution_time_us += result.wait_execution_time_us();
1322
56.9k
        _add_batch_counter.add_batch_num++;
1323
56.9k
    }
1324
56.7k
    if (result.has_load_channel_profile()) {
1325
34
        TRuntimeProfileTree tprofile;
1326
34
        const auto* buf = (const uint8_t*)result.load_channel_profile().data();
1327
34
        auto len = cast_set<uint32_t>(result.load_channel_profile().size());
1328
34
        auto st = deserialize_thrift_msg(buf, &len, false, &tprofile);
1329
34
        if (st.ok()) {
1330
34
            _state->load_channel_profile()->update(tprofile);
1331
34
        } else {
1332
0
            LOG(WARNING) << "load channel TRuntimeProfileTree deserialize failed, errmsg=" << st;
1333
0
        }
1334
34
    }
1335
56.7k
}
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
211
void VNodeChannel::cancel(const std::string& cancel_msg) {
1370
211
    if (_is_closed) {
1371
        // skip the channels that have been canceled or close_wait.
1372
44
        return;
1373
44
    }
1374
167
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
1375
    // set _is_closed to true finally
1376
167
    Defer set_closed {[&]() {
1377
167
        std::lock_guard<std::mutex> l(_closed_lock);
1378
167
        _is_closed = true;
1379
167
    }};
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
167
    _cancel_with_msg(cancel_msg);
1383
    // if not inited, _stub will be nullptr, skip sending cancel rpc
1384
167
    if (!_inited) {
1385
0
        return;
1386
0
    }
1387
1388
167
    auto request = std::make_shared<PTabletWriterCancelRequest>();
1389
167
    request->mutable_id()->CopyFrom(_parent->_load_id);
1390
167
    request->set_index_id(_index_channel->_index_id);
1391
167
    request->set_sender_id(_parent->_sender_id);
1392
167
    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
167
    auto cancel_callback = DummyBrpcCallback<PTabletWriterCancelResult>::create_shared();
1396
167
    auto closure = AutoReleaseClosure<
1397
167
            PTabletWriterCancelRequest,
1398
167
            DummyBrpcCallback<PTabletWriterCancelResult>>::create_unique(request, cancel_callback);
1399
1400
167
    auto remain_ms = _rpc_timeout_ms - _timeout_watch.elapsed_time() / NANOS_PER_MILLIS;
1401
167
    if (UNLIKELY(remain_ms < config::min_load_rpc_timeout_ms)) {
1402
0
        remain_ms = config::min_load_rpc_timeout_ms;
1403
0
    }
1404
167
    cancel_callback->cntl_->set_timeout_ms(remain_ms);
1405
167
    if (config::tablet_writer_ignore_eovercrowded) {
1406
167
        closure->cntl_->ignore_eovercrowded();
1407
167
    }
1408
167
    _stub->tablet_writer_cancel(closure->cntl_.get(), closure->request_.get(),
1409
167
                                closure->response_.get(), closure.get());
1410
167
    closure.release();
1411
167
}
1412
1413
103k
Status VNodeChannel::close_wait(RuntimeState* state, bool* is_closed) {
1414
103k
    DBUG_EXECUTE_IF("VNodeChannel.close_wait_full_gc", {
1415
103k
        std::thread t(injection_full_gc_fn);
1416
103k
        t.join();
1417
103k
    });
1418
103k
    SCOPED_CONSUME_MEM_TRACKER(_node_channel_tracker.get());
1419
1420
103k
    *is_closed = true;
1421
1422
103k
    auto st = none_of({_cancelled, !_eos_is_produced});
1423
103k
    if (!st.ok()) {
1424
44
        if (_cancelled) {
1425
44
            std::lock_guard<std::mutex> l(_cancel_msg_lock);
1426
44
            return Status::Error<ErrorCode::INTERNAL_ERROR, false>("wait close failed. {}",
1427
44
                                                                   _cancel_msg);
1428
44
        } else {
1429
0
            return std::move(
1430
0
                    st.prepend("already stopped, skip waiting for close. cancelled/!eos: "));
1431
0
        }
1432
44
    }
1433
1434
103k
    DBUG_EXECUTE_IF("VNodeChannel.close_wait.cancelled", {
1435
103k
        _cancelled = true;
1436
103k
        _cancel_msg = "injected cancel";
1437
103k
    });
1438
1439
103k
    if (state->is_cancelled()) {
1440
1
        _cancel_with_msg(state->cancel_reason().to_string());
1441
1
    }
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
103k
    if (!_add_batches_finished && !_cancelled && !state->is_cancelled()) {
1448
52.9k
        *is_closed = false;
1449
52.9k
        return Status::OK();
1450
52.9k
    }
1451
18.4E
    VLOG_CRITICAL << _parent->_sender_id << " close wait finished";
1452
50.2k
    return Status::OK();
1453
103k
}
1454
1455
Status VNodeChannel::after_close_handle(
1456
        RuntimeState* state, WriterStats* writer_stats,
1457
50.3k
        std::unordered_map<int64_t, AddBatchCounter>* node_add_batch_counter_map) {
1458
50.3k
    Status st = Status::Error<ErrorCode::INTERNAL_ERROR, false>(get_cancel_msg());
1459
50.3k
    _close_time_ms = UnixMillis() - _close_time_ms;
1460
1461
50.3k
    if (_add_batches_finished) {
1462
50.3k
        _close_check();
1463
50.3k
        _state->add_tablet_commit_infos(_tablet_commit_infos);
1464
1465
50.3k
        _index_channel->set_error_tablet_in_state(state);
1466
50.3k
        _index_channel->set_tablets_received_rows(_tablets_received_rows, _node_id);
1467
50.3k
        _index_channel->set_tablets_filtered_rows(_tablets_filtered_rows, _node_id);
1468
1469
50.3k
        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
50.3k
        _is_closed = true;
1473
50.3k
        st = Status::OK();
1474
50.3k
    }
1475
1476
50.3k
    time_report(node_add_batch_counter_map, writer_stats);
1477
50.3k
    return st;
1478
50.3k
}
1479
1480
34.0k
Status VNodeChannel::check_status() {
1481
34.0k
    return none_of({_cancelled, !_eos_is_produced});
1482
34.0k
}
1483
1484
50.1k
void VNodeChannel::_close_check() {
1485
50.1k
    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
50.1k
}
1489
1490
50.3k
void VNodeChannel::mark_close(bool hang_wait) {
1491
50.3k
    auto st = none_of({_cancelled, _eos_is_produced});
1492
50.3k
    if (!st.ok()) {
1493
0
        return;
1494
0
    }
1495
1496
50.3k
    bool need_adaptive_random_bucket_eos = _cur_add_block_request->is_adaptive_random_bucket();
1497
50.3k
    {
1498
50.3k
        std::lock_guard<std::mutex> l(_pending_batches_lock);
1499
50.3k
        if (!_cur_mutable_block) [[unlikely]] {
1500
            // never had a block arrived. add a dummy block
1501
16.2k
            _cur_mutable_block = MutableBlock::create_unique();
1502
16.2k
        }
1503
50.3k
        if (need_adaptive_random_bucket_eos && _cur_mutable_block->rows() > 0) {
1504
4.17k
            _cur_add_block_request->set_eos(false);
1505
4.17k
            auto tmp_add_block_request =
1506
4.17k
                    std::make_shared<PTabletWriterAddBlockRequest>(*_cur_add_block_request);
1507
4.17k
            _pending_blocks.emplace(std::move(_cur_mutable_block), tmp_add_block_request);
1508
4.17k
            _pending_batches_num++;
1509
4.17k
            _cur_add_block_request->clear_tablet_ids();
1510
4.17k
            _cur_add_block_request->clear_partition_ids();
1511
4.17k
            _cur_mutable_block = MutableBlock::create_unique();
1512
4.17k
        }
1513
50.3k
        _cur_add_block_request->set_eos(true);
1514
50.3k
        _cur_add_block_request->set_hang_wait(hang_wait);
1515
50.3k
        auto tmp_add_block_request =
1516
50.3k
                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
50.3k
        _pending_blocks.emplace(std::move(_cur_mutable_block), tmp_add_block_request);
1519
50.3k
        _pending_batches_num++;
1520
50.3k
        DCHECK(_pending_blocks.back().second->eos());
1521
50.3k
        _close_time_ms = UnixMillis();
1522
50.3k
        LOG(INFO) << channel_info()
1523
50.3k
                  << " mark closed, left pending batch size: " << _pending_blocks.size()
1524
50.3k
                  << " hang_wait: " << hang_wait;
1525
50.3k
    }
1526
1527
50.3k
    _eos_is_produced = true;
1528
50.3k
}
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
49.2k
        : AsyncResultWriter(output_exprs, dep, fin_dep), _t_sink(t_sink) {
1533
49.2k
    _transfer_large_data_by_brpc = config::transfer_large_data_by_brpc;
1534
49.2k
}
1535
1536
49.5k
void VTabletWriter::_send_batch_process() {
1537
49.5k
    SCOPED_TIMER(_non_blocking_send_timer);
1538
49.5k
    SCOPED_ATTACH_TASK(_state);
1539
49.5k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker);
1540
1541
49.5k
    int sleep_time = int(config::olap_table_sink_send_interval_microseconds *
1542
49.5k
                         (_vpartition->is_auto_partition()
1543
49.5k
                                  ? config::olap_table_sink_send_interval_auto_partition_factor
1544
49.5k
                                  : 1));
1545
1546
14.5M
    while (true) {
1547
        // incremental open will temporarily make channels into abnormal state. stop checking when this.
1548
14.5M
        std::unique_lock<bthread::Mutex> l(_stop_check_channel);
1549
1550
14.5M
        int running_channels_num = 0;
1551
14.5M
        int opened_nodes = 0;
1552
15.1M
        for (const auto& index_channel : _channels) {
1553
15.1M
            index_channel->for_each_node_channel([&running_channels_num,
1554
15.1M
                                                  this](const std::shared_ptr<VNodeChannel>& ch) {
1555
                // if this channel all completed(cancelled), got 0. else 1.
1556
15.1M
                running_channels_num +=
1557
15.1M
                        ch->try_send_and_fetch_status(_state, this->_send_batch_thread_pool_token);
1558
15.1M
            });
1559
15.1M
            opened_nodes += index_channel->num_node_channels();
1560
15.1M
        }
1561
1562
        // auto partition table may have no node channel temporarily. wait to open.
1563
14.5M
        if (opened_nodes != 0 && running_channels_num == 0) {
1564
49.5k
            LOG(INFO) << "All node channels are stopped(maybe finished/offending/cancelled), "
1565
49.5k
                         "sender thread exit. "
1566
49.5k
                      << print_id(_load_id);
1567
49.5k
            return;
1568
49.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
14.5M
        if (_try_close.load(std::memory_order_acquire)) {
1576
224k
            opened_nodes = 0;
1577
224k
            std::ranges::for_each(_channels,
1578
402k
                                  [&opened_nodes](const std::shared_ptr<IndexChannel>& ich) {
1579
402k
                                      opened_nodes += ich->num_node_channels();
1580
402k
                                  });
1581
224k
            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
224k
        }
1588
14.5M
        bthread_usleep(sleep_time);
1589
14.5M
    }
1590
49.5k
}
1591
1592
49.5k
static void* periodic_send_batch(void* writer) {
1593
49.5k
    auto* tablet_writer = (VTabletWriter*)(writer);
1594
49.5k
    tablet_writer->_send_batch_process();
1595
49.5k
    return nullptr;
1596
49.5k
}
1597
1598
49.5k
Status VTabletWriter::open(doris::RuntimeState* state, doris::RuntimeProfile* profile) {
1599
49.5k
    RETURN_IF_ERROR(_init(state, profile));
1600
49.5k
    signal::set_signal_task_id(_load_id);
1601
49.5k
    SCOPED_TIMER(profile->total_time_counter());
1602
49.5k
    SCOPED_TIMER(_open_timer);
1603
49.5k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker.get());
1604
1605
49.5k
    fmt::memory_buffer buf;
1606
50.3k
    for (const auto& index_channel : _channels) {
1607
50.3k
        fmt::format_to(buf, "index id:{}", index_channel->_index_id);
1608
50.3k
        index_channel->for_each_node_channel(
1609
50.3k
                [](const std::shared_ptr<VNodeChannel>& ch) { ch->open(); });
1610
50.3k
    }
1611
49.5k
    VLOG_DEBUG << "list of open index id = " << fmt::to_string(buf);
1612
1613
50.2k
    for (const auto& index_channel : _channels) {
1614
50.2k
        index_channel->set_start_time(UnixMillis());
1615
50.2k
        index_channel->for_each_node_channel([&index_channel](
1616
50.2k
                                                     const std::shared_ptr<VNodeChannel>& ch) {
1617
50.2k
            auto st = ch->open_wait();
1618
50.2k
            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
50.2k
        });
1628
1629
50.2k
        RETURN_IF_ERROR(index_channel->check_intolerable_failure());
1630
50.2k
    }
1631
49.5k
    _send_batch_thread_pool_token = state->exec_env()->send_batch_thread_pool()->new_token(
1632
49.5k
            ThreadPool::ExecutionMode::CONCURRENT, _send_batch_parallelism);
1633
1634
    // start to send batch continually. this must be called after _init
1635
49.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
49.5k
    return Status::OK();
1639
49.5k
}
1640
1641
201
Status VTabletWriter::on_partitions_created(TCreatePartitionResult* result) {
1642
    // add new tablet locations. it will use by address. so add to pool
1643
201
    auto* new_locations = _pool->add(new std::vector<TTabletLocation>(result->tablets));
1644
201
    _location->add_locations(*new_locations);
1645
201
    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
201
    _nodes_info->add_nodes(result->nodes);
1652
1653
    // incremental open node channel
1654
201
    RETURN_IF_ERROR(_incremental_open_node_channel(result->partitions));
1655
1656
201
    return Status::OK();
1657
201
}
1658
1659
201
static Status on_partitions_created(void* writer, TCreatePartitionResult* result) {
1660
201
    return static_cast<VTabletWriter*>(writer)->on_partitions_created(result);
1661
201
}
1662
1663
48.9k
Status VTabletWriter::_init_row_distribution() {
1664
48.9k
    _row_distribution.init({.state = _state,
1665
48.9k
                            .block_convertor = _block_convertor.get(),
1666
48.9k
                            .tablet_finder = _tablet_finder.get(),
1667
48.9k
                            .vpartition = _vpartition,
1668
48.9k
                            .add_partition_request_timer = _add_partition_request_timer,
1669
48.9k
                            .txn_id = _txn_id,
1670
48.9k
                            .pool = _pool,
1671
48.9k
                            .location = _location,
1672
48.9k
                            .vec_output_expr_ctxs = &_vec_output_expr_ctxs,
1673
48.9k
                            .schema = _schema,
1674
48.9k
                            .caller = this,
1675
48.9k
                            .write_single_replica = _write_single_replica,
1676
48.9k
                            .create_partition_callback = &::doris::on_partitions_created});
1677
1678
48.9k
    return _row_distribution.open(_output_row_desc);
1679
48.9k
}
1680
1681
49.5k
Status VTabletWriter::_init(RuntimeState* state, RuntimeProfile* profile) {
1682
49.5k
    DCHECK(_t_sink.__isset.olap_table_sink);
1683
49.5k
    _pool = state->obj_pool();
1684
49.5k
    auto& table_sink = _t_sink.olap_table_sink;
1685
49.5k
    _load_id.set_hi(table_sink.load_id.hi);
1686
49.5k
    _load_id.set_lo(table_sink.load_id.lo);
1687
49.5k
    _txn_id = table_sink.txn_id;
1688
49.5k
    _num_replicas = table_sink.num_replicas;
1689
49.5k
    _tuple_desc_id = table_sink.tuple_id;
1690
49.5k
    _write_file_cache = table_sink.write_file_cache;
1691
49.5k
    _schema.reset(new OlapTableSchemaParam());
1692
49.5k
    RETURN_IF_ERROR(_schema->init(table_sink.schema));
1693
49.5k
    bool has_row_binlog = std::any_of(_schema->indexes().begin(), _schema->indexes().end(),
1694
50.1k
                                      [](const auto* index) { return index->row_binlog_id > 0; });
1695
49.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
49.5k
    _schema->set_timestamp_ms(state->timestamp_ms());
1700
49.5k
    _schema->set_nano_seconds(state->nano_seconds());
1701
49.5k
    _schema->set_timezone(state->timezone());
1702
49.5k
    _location = _pool->add(new OlapTableLocationParam(table_sink.location));
1703
49.5k
    _nodes_info = _pool->add(new DorisNodesInfo(table_sink.nodes_info));
1704
49.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
49.5k
    if (config::is_cloud_mode() &&
1713
49.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
49.5k
    _txn_expiration = ::time(nullptr) + table_sink.txn_timeout_s;
1717
1718
49.5k
    if (table_sink.__isset.load_channel_timeout_s) {
1719
48.8k
        _load_channel_timeout_s = table_sink.load_channel_timeout_s;
1720
48.8k
    } else {
1721
691
        _load_channel_timeout_s = config::streaming_load_rpc_max_alive_time_sec;
1722
691
    }
1723
49.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
49.5k
    auto find_tablet_mode = OlapTabletFinder::FindTabletMode::FIND_TABLET_EVERY_ROW;
1735
49.5k
    if (table_sink.partition.distributed_columns.empty()) {
1736
9.61k
        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.58k
        } else if (table_sink.__isset.enable_adaptive_random_bucket &&
1739
9.58k
                   table_sink.enable_adaptive_random_bucket && config::is_cloud_mode()) {
1740
9.53k
            find_tablet_mode = OlapTabletFinder::FindTabletMode::FIND_TABLET_RANDOM_BUCKET;
1741
9.53k
        } else {
1742
49
            find_tablet_mode = OlapTabletFinder::FindTabletMode::FIND_TABLET_EVERY_BATCH;
1743
49
        }
1744
9.59k
    }
1745
49.5k
    _vpartition = _pool->add(new doris::VOlapTablePartitionParam(_schema, table_sink.partition));
1746
49.5k
    _tablet_finder = std::make_unique<OlapTabletFinder>(_vpartition, find_tablet_mode);
1747
49.5k
    RETURN_IF_ERROR(_vpartition->init());
1748
1749
49.5k
    _state = state;
1750
49.5k
    _operator_profile = profile;
1751
1752
49.5k
    _sender_id = state->per_fragment_instance_idx();
1753
49.5k
    _num_senders = state->num_per_fragment_instances();
1754
49.5k
    _is_high_priority =
1755
49.5k
            (state->execution_timeout() <= config::load_task_high_priority_threshold_second);
1756
49.5k
    DBUG_EXECUTE_IF("VTabletWriter._init.is_high_priority", { _is_high_priority = true; });
1757
    // profile must add to state's object pool
1758
49.5k
    _mem_tracker =
1759
49.5k
            std::make_shared<MemTracker>("OlapTableSink:" + std::to_string(state->load_job_id()));
1760
49.5k
    SCOPED_TIMER(profile->total_time_counter());
1761
49.5k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker.get());
1762
1763
    // get table's tuple descriptor
1764
49.5k
    _output_tuple_desc = state->desc_tbl().get_tuple_descriptor(_tuple_desc_id);
1765
49.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
49.5k
    if (!_vec_output_expr_ctxs.empty() &&
1771
49.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
49.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
49.5k
    _block_convertor->init_autoinc_info(
1784
49.5k
            _schema->db_id(), _schema->table_id(), _state->batch_size(),
1785
49.5k
            _schema->is_fixed_partial_update() && !_schema->auto_increment_coulumn().empty(),
1786
49.5k
            _schema->auto_increment_column_unique_id());
1787
49.5k
    _output_row_desc = _pool->add(new RowDescriptor(_output_tuple_desc));
1788
1789
    // add all counter
1790
49.5k
    _input_rows_counter = ADD_COUNTER(profile, "RowsRead", TUnit::UNIT);
1791
49.5k
    _output_rows_counter = ADD_COUNTER(profile, "RowsProduced", TUnit::UNIT);
1792
49.5k
    _filtered_rows_counter = ADD_COUNTER(profile, "RowsFiltered", TUnit::UNIT);
1793
49.5k
    _send_data_timer = ADD_TIMER(profile, "SendDataTime");
1794
49.5k
    _wait_mem_limit_timer = ADD_CHILD_TIMER(profile, "WaitMemLimitTime", "SendDataTime");
1795
49.5k
    _row_distribution_timer = ADD_CHILD_TIMER(profile, "RowDistributionTime", "SendDataTime");
1796
49.5k
    _filter_timer = ADD_CHILD_TIMER(profile, "FilterTime", "SendDataTime");
1797
49.5k
    _where_clause_timer = ADD_CHILD_TIMER(profile, "WhereClauseTime", "SendDataTime");
1798
49.5k
    _append_node_channel_timer = ADD_CHILD_TIMER(profile, "AppendNodeChannelTime", "SendDataTime");
1799
49.5k
    _add_partition_request_timer =
1800
49.5k
            ADD_CHILD_TIMER(profile, "AddPartitionRequestTime", "SendDataTime");
1801
49.5k
    _validate_data_timer = ADD_TIMER(profile, "ValidateDataTime");
1802
49.5k
    _open_timer = ADD_TIMER(profile, "OpenTime");
1803
49.5k
    _close_timer = ADD_TIMER(profile, "CloseWaitTime");
1804
49.5k
    _non_blocking_send_timer = ADD_TIMER(profile, "NonBlockingSendTime");
1805
49.5k
    _non_blocking_send_work_timer =
1806
49.5k
            ADD_CHILD_TIMER(profile, "NonBlockingSendWorkTime", "NonBlockingSendTime");
1807
49.5k
    _serialize_batch_timer =
1808
49.5k
            ADD_CHILD_TIMER(profile, "SerializeBatchTime", "NonBlockingSendWorkTime");
1809
49.5k
    _total_add_batch_exec_timer = ADD_TIMER(profile, "TotalAddBatchExecTime");
1810
49.5k
    _max_add_batch_exec_timer = ADD_TIMER(profile, "MaxAddBatchExecTime");
1811
49.5k
    _total_wait_exec_timer = ADD_TIMER(profile, "TotalWaitExecTime");
1812
49.5k
    _max_wait_exec_timer = ADD_TIMER(profile, "MaxWaitExecTime");
1813
49.5k
    _add_batch_number = ADD_COUNTER(profile, "NumberBatchAdded", TUnit::UNIT);
1814
49.5k
    _num_node_channels = ADD_COUNTER(profile, "NumberNodeChannels", TUnit::UNIT);
1815
49.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
49.5k
    const auto& partitions = _vpartition->get_partitions();
1835
98.7k
    for (int i = 0; i < _schema->indexes().size(); ++i) {
1836
        // collect all tablets belong to this rollup
1837
49.2k
        std::vector<TTabletWithPartition> tablets;
1838
49.2k
        auto* index = _schema->indexes()[i];
1839
63.2k
        for (const auto& part : partitions) {
1840
377k
            for (const auto& tablet : part->indexes[i].tablets) {
1841
377k
                TTabletWithPartition tablet_with_partition;
1842
377k
                tablet_with_partition.partition_id = part->id;
1843
377k
                tablet_with_partition.tablet_id = tablet;
1844
377k
                tablets.emplace_back(std::move(tablet_with_partition));
1845
377k
                _build_tablet_replica_info(tablet, part);
1846
377k
            }
1847
63.2k
        }
1848
49.2k
        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
49.2k
        _channels.emplace_back(new IndexChannel(this, index->index_id, index->where_clause));
1853
49.2k
        _index_id_to_channel[index->index_id] = _channels.back();
1854
49.2k
        RETURN_IF_ERROR(_channels.back()->init(state, tablets));
1855
49.2k
    }
1856
1857
49.5k
    RETURN_IF_ERROR(_init_row_distribution());
1858
1859
49.5k
    _inited = true;
1860
49.5k
    return Status::OK();
1861
49.5k
}
1862
1863
Status VTabletWriter::_incremental_open_node_channel(
1864
201
        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
201
    std::unique_lock<bthread::Mutex> _l(_stop_check_channel);
1867
402
    for (int i = 0; i < _schema->indexes().size(); ++i) {
1868
201
        const OlapTableIndexSchema* index = _schema->indexes()[i];
1869
201
        std::vector<TTabletWithPartition> tablets;
1870
398
        for (const auto& t_part : partitions) {
1871
398
            VOlapTablePartition* part = nullptr;
1872
398
            RETURN_IF_ERROR(_vpartition->generate_partition_from(t_part, part));
1873
6.68k
            for (const auto& tablet : part->indexes[i].tablets) {
1874
6.68k
                TTabletWithPartition tablet_with_partition;
1875
6.68k
                tablet_with_partition.partition_id = part->id;
1876
6.68k
                tablet_with_partition.tablet_id = tablet;
1877
6.68k
                tablets.emplace_back(std::move(tablet_with_partition));
1878
6.68k
                _build_tablet_replica_info(tablet, part);
1879
6.68k
            }
1880
398
            DCHECK(!tablets.empty()) << "incremental open got nothing!";
1881
398
        }
1882
        // update and reinit for existing channels.
1883
201
        std::shared_ptr<IndexChannel> channel = _index_id_to_channel[index->index_id];
1884
201
        DCHECK(channel != nullptr);
1885
201
        RETURN_IF_ERROR(channel->init(_state, tablets, true)); // add tablets into it
1886
201
    }
1887
1888
201
    fmt::memory_buffer buf;
1889
201
    for (auto& channel : _channels) {
1890
        // incremental open new partition's tablet on storage side
1891
201
        channel->for_each_node_channel(
1892
201
                [](const std::shared_ptr<VNodeChannel>& ch) { ch->incremental_open(); });
1893
201
        fmt::format_to(buf, "index id:{}", channel->_index_id);
1894
201
        VLOG_DEBUG << "list of open index id = " << fmt::to_string(buf);
1895
1896
201
        channel->for_each_node_channel([&channel](const std::shared_ptr<VNodeChannel>& ch) {
1897
201
            auto st = ch->open_wait();
1898
201
            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
201
        });
1908
1909
201
        RETURN_IF_ERROR(channel->check_intolerable_failure());
1910
201
    }
1911
1912
201
    return Status::OK();
1913
201
}
1914
1915
void VTabletWriter::_build_tablet_replica_info(const int64_t tablet_id,
1916
381k
                                               VOlapTablePartition* partition) {
1917
381k
    if (partition != nullptr) {
1918
381k
        int total_replicas_num =
1919
381k
                partition->total_replica_num == 0 ? _num_replicas : partition->total_replica_num;
1920
381k
        int load_required_replicas_num = partition->load_required_replica_num == 0
1921
381k
                                                 ? (_num_replicas + 1) / 2
1922
381k
                                                 : partition->load_required_replica_num;
1923
381k
        _tablet_replica_info.emplace(
1924
381k
                tablet_id, std::make_pair(total_replicas_num, load_required_replicas_num));
1925
        // Copy version gap backends info for this tablet
1926
381k
        if (auto it = partition->tablet_version_gap_backends.find(tablet_id);
1927
381k
            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
381k
}
1935
1936
167
void VTabletWriter::_cancel_all_channel(Status status) {
1937
167
    for (const auto& index_channel : _channels) {
1938
167
        index_channel->for_each_node_channel([&status](const std::shared_ptr<VNodeChannel>& ch) {
1939
167
            ch->cancel(status.to_string());
1940
167
        });
1941
167
    }
1942
167
    LOG(INFO) << fmt::format(
1943
167
            "close olap table sink. load_id={}, txn_id={}, canceled all node channels due to "
1944
167
            "error: {}",
1945
167
            print_id(_load_id), _txn_id, status);
1946
167
}
1947
1948
91.0k
Status VTabletWriter::_send_new_partition_batch() {
1949
91.0k
    if (_row_distribution.need_deal_batching()) { // maybe try_close more than 1 time
1950
174
        RETURN_IF_ERROR(_row_distribution.automatic_create_partition());
1951
1952
174
        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
174
        _row_distribution.clear_batching_stats();
1959
174
        Defer recover_batching_block([&]() {
1960
174
            _row_distribution._batching_block->set_mutable_columns(
1961
174
                    std::move(tmp_block).mutate_columns());
1962
174
            _row_distribution._batching_block->clear_column_data();
1963
174
        });
1964
174
        RETURN_IF_ERROR(this->write(_state, tmp_block));
1965
174
        _row_distribution._deal_batched = false;
1966
174
    }
1967
91.0k
    return Status::OK();
1968
91.0k
}
1969
1970
49.4k
void VTabletWriter::_do_try_close(RuntimeState* state, const Status& exec_status) {
1971
49.4k
    SCOPED_TIMER(_close_timer);
1972
49.4k
    Status status = exec_status;
1973
1974
    // must before set _try_close
1975
49.4k
    if (status.ok()) {
1976
49.3k
        SCOPED_TIMER(_operator_profile->total_time_counter());
1977
49.3k
        _row_distribution._deal_batched = true;
1978
49.3k
        status = _send_new_partition_batch();
1979
49.3k
    }
1980
1981
49.4k
    _try_close.store(true, std::memory_order_release); // will stop periodic thread
1982
49.4k
    if (status.ok()) {
1983
        // BE id -> add_batch method counter
1984
49.3k
        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
49.3k
        SCOPED_TIMER(_operator_profile->total_time_counter());
1989
50.4k
        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
50.4k
            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
50.4k
            } else { // not has_incremental_node_channel
2041
50.4k
                VLOG_TRACE << _sender_id << " has no incremental channels " << _txn_id;
2042
50.4k
                index_channel->for_each_node_channel(
2043
50.4k
                        [&index_channel, &status](const std::shared_ptr<VNodeChannel>& ch) {
2044
50.3k
                            if (!status.ok() || ch->is_closed()) {
2045
0
                                return;
2046
0
                            }
2047
                            // only first try close, all node channels will mark_close()
2048
50.3k
                            ch->mark_close();
2049
50.3k
                            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
50.3k
                        });
2055
50.4k
            }
2056
50.4k
        } // end for index channels
2057
49.3k
    }
2058
2059
49.4k
    if (!status.ok()) {
2060
123
        _cancel_all_channel(status);
2061
123
        _close_status = status;
2062
123
    }
2063
49.4k
}
2064
2065
49.5k
Status VTabletWriter::close(Status exec_status) {
2066
49.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
49.5k
    SCOPED_TIMER(_close_timer);
2074
49.5k
    SCOPED_TIMER(_operator_profile->total_time_counter());
2075
2076
    // will make the last batch of request-> close_wait will wait this finished.
2077
49.5k
    _do_try_close(_state, exec_status);
2078
49.5k
    TEST_INJECTION_POINT("VOlapTableSink::close");
2079
2080
49.5k
    DBUG_EXECUTE_IF("VTabletWriter.close.sleep", {
2081
49.5k
        auto sleep_sec = dp->param<int32_t>("sleep_sec", 1);
2082
49.5k
        auto token = dp->param<std::string>("token", "");
2083
49.5k
        LOG(INFO) << "hit debug point VTabletWriter.close.sleep, token=" << token;
2084
49.5k
        std::this_thread::sleep_for(std::chrono::seconds(sleep_sec));
2085
49.5k
    });
2086
49.5k
    DBUG_EXECUTE_IF("VTabletWriter.close.close_status_not_ok",
2087
49.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
49.5k
    if (_close_status.ok()) {
2091
49.3k
        auto status = Status::OK();
2092
        // BE id -> add_batch method counter
2093
49.3k
        std::unordered_map<int64_t, AddBatchCounter> node_add_batch_counter_map;
2094
49.3k
        WriterStats writer_stats;
2095
2096
50.3k
        for (const auto& index_channel : _channels) {
2097
50.3k
            if (!status.ok()) {
2098
0
                break;
2099
0
            }
2100
50.3k
            int64_t add_batch_exec_time = 0;
2101
50.3k
            int64_t wait_exec_time = 0;
2102
50.3k
            status = index_channel->close_wait(_state, &writer_stats, &node_add_batch_counter_map,
2103
50.3k
                                               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
50.3k
            if (status.ok() && !_write_single_replica && _schema->is_strict_mode() &&
2109
50.3k
                _schema->is_partial_update()) {
2110
75
                if (Status st = index_channel->check_tablet_filtered_rows_consistency(); !st.ok()) {
2111
0
                    status = st;
2112
75
                } else {
2113
75
                    _state->set_num_rows_filtered_in_strict_mode_partial_update(
2114
75
                            index_channel->num_rows_filtered());
2115
75
                }
2116
75
            }
2117
2118
50.3k
            writer_stats.num_node_channels += index_channel->num_node_channels();
2119
50.3k
            writer_stats.max_add_batch_exec_time_ns =
2120
50.3k
                    std::max(add_batch_exec_time, writer_stats.max_add_batch_exec_time_ns);
2121
50.3k
            writer_stats.max_wait_exec_time_ns =
2122
50.3k
                    std::max(wait_exec_time, writer_stats.max_wait_exec_time_ns);
2123
50.3k
        } // end for index channels
2124
2125
49.3k
        if (status.ok()) {
2126
            // TODO need to be improved
2127
49.3k
            LOG(INFO) << "total mem_exceeded_block_ns="
2128
49.3k
                      << writer_stats.channel_stat.mem_exceeded_block_ns
2129
49.3k
                      << ", total queue_push_lock_ns=" << writer_stats.queue_push_lock_ns
2130
49.3k
                      << ", total actual_consume_ns=" << writer_stats.actual_consume_ns
2131
49.3k
                      << ", load id=" << print_id(_load_id) << ", txn_id=" << _txn_id;
2132
2133
49.3k
            COUNTER_SET(_input_rows_counter, _number_input_rows);
2134
49.3k
            COUNTER_SET(_output_rows_counter, _number_output_rows);
2135
49.3k
            COUNTER_SET(_filtered_rows_counter,
2136
49.3k
                        _block_convertor->num_filtered_rows() +
2137
49.3k
                                _tablet_finder->num_filtered_rows() +
2138
49.3k
                                _state->num_rows_filtered_in_strict_mode_partial_update());
2139
49.3k
            COUNTER_SET(_send_data_timer, _send_data_ns);
2140
49.3k
            COUNTER_SET(_row_distribution_timer, (int64_t)_row_distribution_watch.elapsed_time());
2141
49.3k
            COUNTER_SET(_filter_timer, _filter_ns);
2142
49.3k
            COUNTER_SET(_append_node_channel_timer,
2143
49.3k
                        writer_stats.channel_stat.append_node_channel_ns);
2144
49.3k
            COUNTER_SET(_where_clause_timer, writer_stats.channel_stat.where_clause_ns);
2145
49.3k
            COUNTER_SET(_wait_mem_limit_timer, writer_stats.channel_stat.mem_exceeded_block_ns);
2146
49.3k
            COUNTER_SET(_validate_data_timer, _block_convertor->validate_data_ns());
2147
49.3k
            COUNTER_SET(_serialize_batch_timer, writer_stats.serialize_batch_ns);
2148
49.3k
            COUNTER_SET(_non_blocking_send_work_timer, writer_stats.actual_consume_ns);
2149
49.3k
            COUNTER_SET(_total_add_batch_exec_timer, writer_stats.total_add_batch_exec_time_ns);
2150
49.3k
            COUNTER_SET(_max_add_batch_exec_timer, writer_stats.max_add_batch_exec_time_ns);
2151
49.3k
            COUNTER_SET(_total_wait_exec_timer, writer_stats.total_wait_exec_time_ns);
2152
49.3k
            COUNTER_SET(_max_wait_exec_timer, writer_stats.max_wait_exec_time_ns);
2153
49.3k
            COUNTER_SET(_add_batch_number, writer_stats.total_add_batch_num);
2154
49.3k
            COUNTER_SET(_num_node_channels, writer_stats.num_node_channels);
2155
49.3k
            COUNTER_SET(_load_back_pressure_version_time_ms,
2156
49.3k
                        writer_stats.load_back_pressure_version_time_ms);
2157
49.3k
            g_sink_load_back_pressure_version_time_ms
2158
49.3k
                    << 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
49.3k
            int64_t num_rows_load_total = _number_input_rows + _state->num_rows_load_filtered() +
2162
49.3k
                                          _state->num_rows_load_unselected();
2163
49.3k
            _state->set_num_rows_load_total(num_rows_load_total);
2164
49.3k
            _state->update_num_rows_load_filtered(
2165
49.3k
                    _block_convertor->num_filtered_rows() + _tablet_finder->num_filtered_rows() +
2166
49.3k
                    _state->num_rows_filtered_in_strict_mode_partial_update());
2167
49.3k
            _state->update_num_rows_load_unselected(
2168
49.3k
                    _tablet_finder->num_immutable_partition_filtered_rows());
2169
2170
49.3k
            if (_state->enable_profile() && _state->profile_level() >= 2) {
2171
                // Output detailed profiling info for auto-partition requests
2172
33
                _row_distribution.output_profile_info(_operator_profile);
2173
33
            }
2174
2175
            // print log of add batch time of all node, for tracing load performance easily
2176
49.3k
            std::stringstream ss;
2177
49.3k
            ss << "finished to close olap table sink. load_id=" << print_id(_load_id)
2178
49.3k
               << ", txn_id=" << _txn_id
2179
49.3k
               << ", node add batch time(ms)/wait execution time(ms)/close time(ms)/num: ";
2180
49.3k
            for (auto const& pair : node_add_batch_counter_map) {
2181
49.2k
                ss << "{" << pair.first << ":(" << (pair.second.add_batch_execution_time_us / 1000)
2182
49.2k
                   << ")(" << (pair.second.add_batch_wait_execution_time_us / 1000) << ")("
2183
49.2k
                   << pair.second.close_wait_time_ms << ")(" << pair.second.add_batch_num << ")} ";
2184
49.2k
            }
2185
49.3k
            LOG(INFO) << ss.str();
2186
49.3k
        } else {
2187
52
            _cancel_all_channel(status);
2188
52
        }
2189
49.3k
        _close_status = status;
2190
49.3k
    }
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
49.5k
    if (_sender_thread) {
2195
49.4k
        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
49.4k
        _send_batch_thread_pool_token->wait();
2200
49.4k
    }
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
50.5k
    for (const auto& index_channel : _channels) {
2206
50.5k
        index_channel->for_each_node_channel(
2207
50.5k
                [](const std::shared_ptr<VNodeChannel>& ch) { ch->clear_all_blocks(); });
2208
50.5k
    }
2209
49.5k
    return _close_status;
2210
49.5k
}
2211
2212
Status VTabletWriter::_generate_one_index_channel_payload(
2213
        RowPartTabletIds& row_part_tablet_id, int32_t index_idx,
2214
42.7k
        ChannelDistributionPayload& channel_payload) {
2215
42.7k
    auto& row_ids = row_part_tablet_id.row_ids;
2216
42.7k
    auto& partition_ids = row_part_tablet_id.partition_ids;
2217
42.7k
    auto& tablet_ids = row_part_tablet_id.tablet_ids;
2218
2219
42.7k
    size_t row_cnt = row_ids.size();
2220
42.7k
    bool has_row_binlog = _schema->indexes()[index_idx]->row_binlog_id > 0;
2221
42.7k
    std::vector<int64_t> row_binlog_lsns;
2222
42.7k
    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.1M
    for (size_t i = 0; i < row_ids.size(); i++) {
2228
36.1M
        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.27k
                auto [tmp_it, _] = channel_payload.emplace(
2239
5.27k
                        partition_it->second.get(),
2240
5.27k
                        Payload {std::make_unique<IColumn::Selector>(), &row_part_tablet_id,
2241
5.27k
                                 std::vector<uint32_t>(), std::vector<int64_t>()});
2242
5.27k
                payload_it = tmp_it;
2243
5.27k
                payload_it->second.row_ids->reserve(row_cnt);
2244
5.27k
                payload_it->second.route_idxs.reserve(row_cnt);
2245
5.27k
                if (has_row_binlog) {
2246
0
                    payload_it->second.row_binlog_lsns.reserve(row_cnt);
2247
0
                }
2248
5.27k
            }
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
34.0M
        auto it = _channels[index_idx]->_channels_by_tablet.find(tablet_ids[i]);
2259
34.0M
        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
34.0M
        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
37.1k
                auto [tmp_it, _] = channel_payload.emplace(
2270
37.1k
                        locate_node.get(),
2271
37.1k
                        Payload {std::make_unique<IColumn::Selector>(), &row_part_tablet_id,
2272
37.1k
                                 std::vector<uint32_t>(), std::vector<int64_t>()});
2273
37.1k
                payload_it = tmp_it;
2274
37.1k
                payload_it->second.row_ids->reserve(row_cnt);
2275
37.1k
                payload_it->second.route_idxs.reserve(row_cnt);
2276
37.1k
                if (has_row_binlog) {
2277
0
                    payload_it->second.row_binlog_lsns.reserve(row_cnt);
2278
0
                }
2279
37.1k
            }
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
34.0M
    }
2287
42.7k
    return Status::OK();
2288
42.7k
}
2289
2290
Status VTabletWriter::_generate_index_channels_payloads(
2291
        std::vector<RowPartTabletIds>& row_part_tablet_ids,
2292
41.7k
        ChannelDistributionPayloadVec& payload) {
2293
84.5k
    for (int i = 0; i < _schema->indexes().size(); i++) {
2294
42.7k
        RETURN_IF_ERROR(_generate_one_index_channel_payload(row_part_tablet_ids[i], i, payload[i]));
2295
42.7k
    }
2296
41.7k
    return Status::OK();
2297
41.7k
}
2298
2299
41.7k
Status VTabletWriter::write(RuntimeState* state, doris::Block& input_block) {
2300
41.7k
    SCOPED_CONSUME_MEM_TRACKER(_mem_tracker.get());
2301
41.7k
    Status status = Status::OK();
2302
2303
41.7k
    DCHECK(_state);
2304
41.7k
    DCHECK(_state->query_options().__isset.dry_run_query);
2305
41.7k
    if (_state->query_options().dry_run_query) {
2306
1
        return status;
2307
1
    }
2308
2309
    // check out of limit
2310
41.7k
    RETURN_IF_ERROR(_send_new_partition_batch());
2311
2312
41.7k
    const bool is_replaying_batched_block = _row_distribution._deal_batched;
2313
41.7k
    auto rows = input_block.rows();
2314
41.7k
    auto bytes = input_block.bytes();
2315
41.7k
    if (UNLIKELY(rows == 0)) {
2316
0
        return status;
2317
0
    }
2318
41.7k
    SCOPED_TIMER(_operator_profile->total_time_counter());
2319
41.7k
    SCOPED_RAW_TIMER(&_send_data_ns);
2320
2321
41.7k
    std::shared_ptr<Block> block;
2322
41.7k
    _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
41.7k
    _state->update_num_rows_load_total(rows);
2326
41.7k
    _state->update_num_bytes_load_total(bytes);
2327
41.7k
    if (!is_replaying_batched_block) {
2328
41.5k
        DorisMetrics::instance()->load_rows->increment(rows);
2329
41.5k
        DorisMetrics::instance()->load_bytes->increment(bytes);
2330
41.5k
    }
2331
2332
41.7k
    _row_distribution_watch.start();
2333
41.7k
    RETURN_IF_ERROR(_row_distribution.generate_rows_distribution(
2334
41.7k
            input_block, block, _row_part_tablet_ids, _number_input_rows));
2335
2336
41.7k
    ChannelDistributionPayloadVec channel_to_payload;
2337
2338
41.7k
    channel_to_payload.resize(_channels.size());
2339
41.7k
    Status generate_payload_status =
2340
41.7k
            _generate_index_channels_payloads(_row_part_tablet_ids, channel_to_payload);
2341
41.7k
    _row_distribution_watch.stop();
2342
41.7k
    RETURN_IF_ERROR(generate_payload_status);
2343
2344
    // Add block to node channel
2345
84.5k
    for (size_t i = 0; i < _channels.size(); i++) {
2346
42.7k
        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
42.4k
            auto st = entry.first->add_block(block.get(), &entry.second);
2350
42.4k
            if (!st.ok()) {
2351
0
                _channels[i]->mark_as_failed(entry.first, st.to_string());
2352
0
            }
2353
42.4k
        }
2354
42.7k
    }
2355
2356
    // check intolerable failure
2357
42.7k
    for (const auto& index_channel : _channels) {
2358
42.7k
        RETURN_IF_ERROR(index_channel->check_intolerable_failure());
2359
42.7k
    }
2360
2361
41.7k
    g_sink_write_bytes << bytes;
2362
41.7k
    g_sink_write_rows << rows;
2363
41.7k
    return Status::OK();
2364
41.7k
}
2365
2366
} // namespace doris