Coverage Report

Created: 2026-08-14 00:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/sink/writer/vtablet_writer.h
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
#pragma once
19
#include <brpc/controller.h>
20
#include <bthread/types.h>
21
#include <butil/errno.h>
22
#include <fmt/format.h>
23
#include <gen_cpp/Exprs_types.h>
24
#include <gen_cpp/FrontendService.h>
25
#include <gen_cpp/FrontendService_types.h>
26
#include <gen_cpp/PaloInternalService_types.h>
27
#include <gen_cpp/Types_types.h>
28
#include <gen_cpp/internal_service.pb.h>
29
#include <gen_cpp/types.pb.h>
30
#include <glog/logging.h>
31
#include <google/protobuf/stubs/callback.h>
32
33
// IWYU pragma: no_include <bits/chrono.h>
34
#include <bthread/condition_variable.h>
35
#include <bthread/mutex.h>
36
37
#include <atomic>
38
#include <chrono> // IWYU pragma: keep
39
#include <cstddef>
40
#include <cstdint>
41
#include <functional>
42
#include <map>
43
#include <memory>
44
#include <mutex>
45
#include <ostream>
46
#include <queue>
47
#include <sstream>
48
#include <string>
49
#include <thread>
50
#include <unordered_map>
51
#include <unordered_set>
52
#include <utility>
53
#include <vector>
54
55
#include "common/config.h"
56
#include "common/status.h"
57
#include "core/block/block.h"
58
#include "core/column/column.h"
59
#include "core/data_type/data_type.h"
60
#include "exec/sink/vrow_distribution.h"
61
#include "exec/sink/vtablet_block_convertor.h"
62
#include "exec/sink/vtablet_finder.h"
63
#include "exec/sink/writer/async_result_writer.h"
64
#include "exprs/vexpr_fwd.h"
65
#include "runtime/exec_env.h"
66
#include "runtime/memory/mem_tracker.h"
67
#include "runtime/runtime_profile.h"
68
#include "runtime/thread_context.h"
69
#include "storage/tablet_info.h"
70
#include "util/brpc_closure.h"
71
#include "util/stopwatch.hpp"
72
73
namespace doris {
74
class ObjectPool;
75
class RowDescriptor;
76
class RuntimeState;
77
class TDataSink;
78
class TExpr;
79
class Thread;
80
class ThreadPoolToken;
81
class TupleDescriptor;
82
class AutoIncIDBuffer;
83
84
// The counter of add_batch rpc of a single node
85
struct AddBatchCounter {
86
    // total execution time of a add_batch rpc
87
    int64_t add_batch_execution_time_us = 0;
88
    // lock waiting time in a add_batch rpc
89
    int64_t add_batch_wait_execution_time_us = 0;
90
    // number of add_batch call
91
    int64_t add_batch_num = 0;
92
    // time passed between marked close and finish close
93
    int64_t close_wait_time_ms = 0;
94
95
0
    AddBatchCounter& operator+=(const AddBatchCounter& rhs) {
96
0
        add_batch_execution_time_us += rhs.add_batch_execution_time_us;
97
0
        add_batch_wait_execution_time_us += rhs.add_batch_wait_execution_time_us;
98
0
        add_batch_num += rhs.add_batch_num;
99
0
        close_wait_time_ms += rhs.close_wait_time_ms;
100
0
        return *this;
101
0
    }
102
0
    friend AddBatchCounter operator+(const AddBatchCounter& lhs, const AddBatchCounter& rhs) {
103
0
        AddBatchCounter sum = lhs;
104
0
        sum += rhs;
105
0
        return sum;
106
0
    }
107
};
108
109
struct WriteBlockCallbackContext {
110
    std::atomic<bool> _is_last_rpc {false};
111
};
112
113
// It's very error-prone to guarantee the handler capture vars' & this closure's destruct sequence.
114
// So using create() to get the closure pointer is recommended. We can delete the closure ptr before the capture vars destruction.
115
// Delete this point is safe, don't worry about RPC callback will run after WriteBlockCallback deleted.
116
// "Ping-Pong" between sender and receiver, `try_set_in_flight` when send, `clear_in_flight` after rpc failure or callback,
117
// then next send will start, and it will wait for the rpc callback to complete when it is destroyed.
118
template <typename T>
119
class WriteBlockCallback final : public ::doris::DummyBrpcCallback<T> {
120
    ENABLE_FACTORY_CREATOR(WriteBlockCallback);
121
122
public:
123
0
    WriteBlockCallback() : cid(INVALID_BTHREAD_ID) {}
124
0
    ~WriteBlockCallback() override = default;
125
126
0
    void addFailedHandler(const std::function<void(const WriteBlockCallbackContext&)>& fn) {
127
0
        failed_handler = fn;
128
0
    }
129
    void addSuccessHandler(
130
0
            const std::function<void(const T&, const WriteBlockCallbackContext&)>& fn) {
131
0
        success_handler = fn;
132
0
    }
133
134
0
    void join() override {
135
        // We rely on in_flight to assure one rpc is running,
136
        // while cid is not reliable due to memory order.
137
        // in_flight is written before getting callid,
138
        // so we can not use memory fence to synchronize.
139
0
        while (_packet_in_flight) {
140
            // cid here is complicated
141
0
            if (cid != INVALID_BTHREAD_ID) {
142
                // actually cid may be the last rpc call id.
143
0
                brpc::Join(cid);
144
0
            }
145
0
            if (_packet_in_flight) {
146
0
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
147
0
            }
148
0
        }
149
0
    }
150
151
    // plz follow this order: reset() -> set_in_flight() -> send brpc batch
152
0
    void reset() {
153
0
        ::doris::DummyBrpcCallback<T>::cntl_->Reset();
154
0
        cid = ::doris::DummyBrpcCallback<T>::cntl_->call_id();
155
0
    }
156
157
    // if _packet_in_flight == false, set it to true. Return true.
158
    // if _packet_in_flight == true, Return false.
159
0
    bool try_set_in_flight() {
160
0
        bool value = false;
161
0
        return _packet_in_flight.compare_exchange_strong(value, true);
162
0
    }
163
164
0
    void clear_in_flight() { _packet_in_flight = false; }
165
166
    bool is_packet_in_flight() { return _packet_in_flight; }
167
168
0
    void end_mark() {
169
0
        DCHECK(_ctx._is_last_rpc == false);
170
0
        _ctx._is_last_rpc = true;
171
0
    }
172
173
0
    void call() override {
174
0
        DCHECK(_packet_in_flight);
175
0
        if (::doris::DummyBrpcCallback<T>::cntl_->Failed()) {
176
0
            LOG(WARNING) << "failed to send brpc batch, error="
177
0
                         << berror(::doris::DummyBrpcCallback<T>::cntl_->ErrorCode())
178
0
                         << ", error_text=" << ::doris::DummyBrpcCallback<T>::cntl_->ErrorText();
179
0
            failed_handler(_ctx);
180
0
        } else {
181
0
            success_handler(*(::doris::DummyBrpcCallback<T>::response_), _ctx);
182
0
        }
183
0
        clear_in_flight();
184
0
    }
185
186
private:
187
    brpc::CallId cid;
188
    std::atomic<bool> _packet_in_flight {false};
189
    WriteBlockCallbackContext _ctx;
190
    std::function<void(const WriteBlockCallbackContext&)> failed_handler;
191
    std::function<void(const T&, const WriteBlockCallbackContext&)> success_handler;
192
};
193
194
class IndexChannel;
195
class VTabletWriter;
196
197
class VNodeChannelStat {
198
public:
199
0
    VNodeChannelStat& operator+=(const VNodeChannelStat& stat) {
200
0
        mem_exceeded_block_ns += stat.mem_exceeded_block_ns;
201
0
        where_clause_ns += stat.where_clause_ns;
202
0
        append_node_channel_ns += stat.append_node_channel_ns;
203
0
        return *this;
204
0
    };
205
206
    int64_t mem_exceeded_block_ns = 0;
207
    int64_t where_clause_ns = 0;
208
    int64_t append_node_channel_ns = 0;
209
};
210
211
struct WriterStats {
212
    int64_t serialize_batch_ns = 0;
213
    int64_t queue_push_lock_ns = 0;
214
    int64_t actual_consume_ns = 0;
215
    int64_t total_add_batch_exec_time_ns = 0;
216
    int64_t max_add_batch_exec_time_ns = 0;
217
    int64_t total_wait_exec_time_ns = 0;
218
    int64_t max_wait_exec_time_ns = 0;
219
    int64_t total_add_batch_num = 0;
220
    int64_t num_node_channels = 0;
221
    int64_t load_back_pressure_version_time_ms = 0;
222
    VNodeChannelStat channel_stat;
223
};
224
225
struct Payload {
226
    std::unique_ptr<IColumn::Selector> row_ids;
227
    RowPartTabletIds* row_part_tablet_ids = nullptr;
228
    std::vector<uint32_t> route_idxs;
229
    std::vector<int64_t> row_binlog_lsns;
230
};
231
232
// every NodeChannel keeps a data transmission channel with one BE. for multiple times open, it has a dozen of requests and corresponding closures.
233
class VNodeChannel {
234
public:
235
    VNodeChannel(VTabletWriter* parent, IndexChannel* index_channel, int64_t node_id,
236
                 bool is_incremental = false);
237
238
    ~VNodeChannel();
239
240
    // called before open, used to add tablet located in this backend. called by IndexChannel::init
241
0
    void add_tablet(const TTabletWithPartition& tablet) { _tablets_wait_open.emplace_back(tablet); }
242
0
    std::string debug_tablets() const {
243
0
        std::stringstream ss;
244
0
        for (const auto& tab : _all_tablets) {
245
0
            tab.printTo(ss);
246
0
            ss << '\n';
247
0
        }
248
0
        return ss.str();
249
0
    }
250
251
    // this function is NON_REENTRANT
252
    Status init(RuntimeState* state);
253
    /// these two functions will call open_internal. should keep that clear --- REENTRANT
254
    // build corresponding connect to BE. NON-REENTRANT
255
    void open();
256
    // for auto partition, we use this to open more tablet. KEEP IT REENTRANT
257
    void incremental_open();
258
    // this will block until all request transmission which were opened or incremental opened finished.
259
    // this function will called multi times. NON_REENTRANT
260
    Status open_wait();
261
262
    Status add_block(Block* block, const Payload* payload);
263
264
    // @return: 1 if running, 0 if finished.
265
    // @caller: VOlapTabletSink::_send_batch_process. it's a continual asynchronous process.
266
    int try_send_and_fetch_status(RuntimeState* state,
267
                                  std::unique_ptr<ThreadPoolToken>& thread_pool_token);
268
    // when there's pending block found by try_send_and_fetch_status(), we will awake a thread to send it.
269
    void try_send_pending_block(RuntimeState* state);
270
271
    void clear_all_blocks();
272
273
    // two ways to stop channel:
274
    // 1. mark_close()->close_wait() PS. close_wait() will block waiting for the last AddBatch rpc response.
275
    // 2. just cancel()
276
    // hang_wait = true will make reciever hang until all sender mark_closed.
277
    void mark_close(bool hang_wait = false);
278
279
0
    bool is_closed() const { return _is_closed; }
280
0
    bool is_cancelled() const { return _cancelled; }
281
0
    std::string get_cancel_msg() {
282
0
        std::lock_guard<std::mutex> l(_cancel_msg_lock);
283
0
        if (!_cancel_msg.empty()) {
284
0
            return _cancel_msg;
285
0
        }
286
0
        return fmt::format("{} is cancelled", channel_info());
287
0
    }
288
289
    // two ways to stop channel:
290
    // 1. mark_close()->close_wait() PS. close_wait() will block waiting for the last AddBatch rpc response.
291
    // 2. just cancel()
292
    Status close_wait(RuntimeState* state, bool* is_closed);
293
294
    Status after_close_handle(
295
            RuntimeState* state, WriterStats* writer_stats,
296
            std::unordered_map<int64_t, AddBatchCounter>* node_add_batch_counter_map);
297
298
    Status check_status();
299
300
    void cancel(const std::string& cancel_msg);
301
302
    void time_report(std::unordered_map<int64_t, AddBatchCounter>* add_batch_counter_map,
303
0
                     WriterStats* writer_stats) const {
304
0
        if (add_batch_counter_map != nullptr) {
305
0
            (*add_batch_counter_map)[_node_id] += _add_batch_counter;
306
0
            (*add_batch_counter_map)[_node_id].close_wait_time_ms = _close_time_ms;
307
0
        }
308
0
        if (writer_stats != nullptr) {
309
0
            writer_stats->serialize_batch_ns += _serialize_batch_ns;
310
0
            writer_stats->channel_stat += _stat;
311
0
            writer_stats->queue_push_lock_ns += _queue_push_lock_ns;
312
0
            writer_stats->actual_consume_ns += _actual_consume_ns;
313
0
            writer_stats->total_add_batch_exec_time_ns +=
314
0
                    (_add_batch_counter.add_batch_execution_time_us * 1000);
315
0
            writer_stats->total_wait_exec_time_ns +=
316
0
                    (_add_batch_counter.add_batch_wait_execution_time_us * 1000);
317
0
            writer_stats->total_add_batch_num += _add_batch_counter.add_batch_num;
318
0
            writer_stats->load_back_pressure_version_time_ms +=
319
0
                    _load_back_pressure_version_block_ms;
320
0
        }
321
0
    }
322
323
0
    int64_t node_id() const { return _node_id; }
324
0
    std::string host() const { return _node_info.host; }
325
0
    std::string name() const { return _name; }
326
327
0
    std::string channel_info() const {
328
0
        return fmt::format("{}, {}, node={}:{}", _name, _load_info, _node_info.host,
329
0
                           _node_info.brpc_port);
330
0
    }
331
332
0
    size_t get_pending_bytes() { return _pending_batches_bytes; }
333
334
0
    bool is_incremental() const { return _is_incremental; }
335
336
0
    int64_t write_bytes() const { return _write_bytes.load(); }
337
338
protected:
339
    // make a real open request for relative BE's load channel.
340
    void _open_internal(bool is_incremental);
341
    void _set_adaptive_random_bucket_open_request(PTabletWriterOpenRequest* request);
342
343
    void _close_check();
344
    void _cancel_with_msg(const std::string& msg);
345
346
    void _add_block_success_callback(const PTabletWriterAddBlockResult& result,
347
                                     const WriteBlockCallbackContext& ctx);
348
    void _add_block_failed_callback(const WriteBlockCallbackContext& ctx);
349
350
    void _refresh_back_pressure_version_wait_time(
351
            const ::google::protobuf::RepeatedPtrField<::doris::PTabletLoadRowsetInfo>&
352
                    tablet_load_infos);
353
354
    VTabletWriter* _parent = nullptr;
355
    IndexChannel* _index_channel = nullptr;
356
    int64_t _node_id = -1;
357
    std::string _load_info;
358
    std::string _name;
359
360
    std::shared_ptr<MemTracker> _node_channel_tracker;
361
    int64_t _load_mem_limit = -1;
362
363
    TupleDescriptor* _tuple_desc = nullptr;
364
    NodeInfo _node_info;
365
366
    // this should be set in init() using config
367
    int _rpc_timeout_ms = 60000;
368
    int64_t _next_packet_seq = 0;
369
    MonotonicStopWatch _timeout_watch;
370
371
    // the timestamp when this node channel be marked closed and finished closed
372
    uint64_t _close_time_ms = 0;
373
374
    // user cancel or get some errors
375
    std::atomic<bool> _cancelled {false};
376
    std::mutex _cancel_msg_lock;
377
    std::string _cancel_msg;
378
379
    // send finished means the consumer thread which send the rpc can exit
380
    std::atomic<bool> _send_finished {false};
381
382
    // add batches finished means the last rpc has be response, used to check whether this channel can be closed
383
    std::atomic<bool> _add_batches_finished {false}; // reuse for vectorized
384
385
    bool _eos_is_produced {false}; // only for restricting producer behaviors
386
387
    std::unique_ptr<RowDescriptor> _row_desc;
388
    int _batch_size = 0;
389
390
    // limit _pending_batches size
391
    std::atomic<size_t> _pending_batches_bytes {0};
392
    size_t _max_pending_batches_bytes {(size_t)config::nodechannel_pending_queue_max_bytes};
393
    std::mutex _pending_batches_lock;          // reuse for vectorized
394
    std::atomic<int> _pending_batches_num {0}; // reuse for vectorized
395
396
    std::shared_ptr<PBackendService_Stub> _stub;
397
    // because we have incremantal open, we should keep one relative closure for one request. it's similarly for adding block.
398
    std::vector<std::shared_ptr<DummyBrpcCallback<PTabletWriterOpenResult>>> _open_callbacks;
399
400
    std::vector<TTabletWithPartition> _all_tablets;
401
    std::vector<TTabletWithPartition> _tablets_wait_open;
402
    // For rolling-upgrade compatibility, adaptive random bucket add-block RPCs also carry
403
    // tablet_ids. New receivers ignore them and route by partition id, while old receivers use
404
    // this local tablet id instead of failing on an empty tablet_ids list.
405
    std::unordered_map<int64_t, int64_t> _adaptive_partition_compat_tablets;
406
    std::vector<TTabletCommitInfo> _tablet_commit_infos;
407
408
    AddBatchCounter _add_batch_counter;
409
    std::atomic<int64_t> _serialize_batch_ns {0};
410
    std::atomic<int64_t> _queue_push_lock_ns {0};
411
    std::atomic<int64_t> _actual_consume_ns {0};
412
    std::atomic<int64_t> _load_back_pressure_version_block_ms {0};
413
414
    VNodeChannelStat _stat;
415
    // lock to protect _is_closed.
416
    // The methods in the IndexChannel are called back in the RpcClosure in the NodeChannel.
417
    // However, this rpc callback may occur after the whole task is finished (e.g. due to network latency),
418
    // and by that time the IndexChannel may have been destructured, so we should not call the
419
    // IndexChannel methods anymore, otherwise the BE will crash.
420
    // Therefore, we use the _is_closed and _closed_lock to ensure that the RPC callback
421
    // function will not call the IndexChannel method after the NodeChannel is closed.
422
    // The IndexChannel is definitely accessible until the NodeChannel is closed.
423
    std::mutex _closed_lock;
424
    bool _is_closed = false;
425
    bool _inited = false;
426
427
    RuntimeState* _state = nullptr;
428
    // A context lock for callbacks, the callback has to lock the ctx, to avoid
429
    // the object is deleted during callback is running.
430
    std::weak_ptr<TaskExecutionContext> _task_exec_ctx;
431
    // rows number received per tablet, tablet_id -> rows_num
432
    std::vector<std::pair<int64_t, int64_t>> _tablets_received_rows;
433
    // rows number filtered per tablet, tablet_id -> filtered_rows_num
434
    std::vector<std::pair<int64_t, int64_t>> _tablets_filtered_rows;
435
436
    // build a _cur_mutable_block and push into _pending_blocks. when not building, this block is empty.
437
    std::unique_ptr<MutableBlock> _cur_mutable_block;
438
    std::shared_ptr<PTabletWriterAddBlockRequest> _cur_add_block_request;
439
440
    using AddBlockReq =
441
            std::pair<std::unique_ptr<MutableBlock>, std::shared_ptr<PTabletWriterAddBlockRequest>>;
442
    std::queue<AddBlockReq> _pending_blocks;
443
    // send block to slave BE rely on this. dont reconstruct it.
444
    std::shared_ptr<WriteBlockCallback<PTabletWriterAddBlockResult>> _send_block_callback = nullptr;
445
446
    int64_t _wg_id = -1;
447
448
    bool _is_incremental;
449
450
    std::atomic<int64_t> _write_bytes {0};
451
    std::atomic<int64_t> _load_back_pressure_version_wait_time_ms {0};
452
};
453
454
// an IndexChannel is related to specific table and its rollup and mv
455
class IndexChannel {
456
public:
457
    IndexChannel(VTabletWriter* parent, int64_t index_id, VExprContextSPtr where_clause)
458
0
            : _parent(parent), _index_id(index_id), _where_clause(std::move(where_clause)) {
459
0
        _index_channel_tracker =
460
0
                std::make_unique<MemTracker>("IndexChannel:indexID=" + std::to_string(_index_id));
461
0
    }
462
0
    ~IndexChannel() = default;
463
464
    // allow to init multi times, for incremental open more tablets for one index(table)
465
    Status init(RuntimeState* state, const std::vector<TTabletWithPartition>& tablets,
466
                bool incremental = false);
467
468
    void for_each_node_channel(
469
0
            const std::function<void(const std::shared_ptr<VNodeChannel>&)>& func) {
470
0
        for (auto& it : _node_channels) {
471
0
            func(it.second);
472
0
        }
473
0
    }
474
475
    void for_init_node_channel(
476
0
            const std::function<void(const std::shared_ptr<VNodeChannel>&)>& func) {
477
0
        for (auto& it : _node_channels) {
478
0
            if (!it.second->is_incremental()) {
479
0
                func(it.second);
480
0
            }
481
0
        }
482
0
    }
483
484
    void for_inc_node_channel(
485
0
            const std::function<void(const std::shared_ptr<VNodeChannel>&)>& func) {
486
0
        for (auto& it : _node_channels) {
487
0
            if (it.second->is_incremental()) {
488
0
                func(it.second);
489
0
            }
490
0
        }
491
0
    }
492
493
0
    std::unordered_set<int64_t> init_node_channel_ids() {
494
0
        std::unordered_set<int64_t> node_channel_ids;
495
0
        for (auto& it : _node_channels) {
496
0
            if (!it.second->is_incremental()) {
497
0
                node_channel_ids.insert(it.first);
498
0
            }
499
0
        }
500
0
        return node_channel_ids;
501
0
    }
502
503
0
    std::unordered_set<int64_t> inc_node_channel_ids() {
504
0
        std::unordered_set<int64_t> node_channel_ids;
505
0
        for (auto& it : _node_channels) {
506
0
            if (it.second->is_incremental()) {
507
0
                node_channel_ids.insert(it.first);
508
0
            }
509
0
        }
510
0
        return node_channel_ids;
511
0
    }
512
513
0
    std::unordered_set<int64_t> each_node_channel_ids() {
514
0
        std::unordered_set<int64_t> node_channel_ids;
515
0
        for (auto& it : _node_channels) {
516
0
            node_channel_ids.insert(it.first);
517
0
        }
518
0
        return node_channel_ids;
519
0
    }
520
521
0
    bool has_incremental_node_channel() const { return _has_inc_node; }
522
523
    void mark_as_failed(const VNodeChannel* node_channel, const std::string& err,
524
                        int64_t tablet_id = -1);
525
    Status check_intolerable_failure();
526
527
    Status close_wait(RuntimeState* state, WriterStats* writer_stats,
528
                      std::unordered_map<int64_t, AddBatchCounter>* node_add_batch_counter_map,
529
                      std::unordered_set<int64_t> unfinished_node_channel_ids,
530
                      bool need_wait_after_quorum_success);
531
532
0
    int64_t close_wait_version() const {
533
0
        return _close_wait_version.load(std::memory_order_acquire);
534
0
    }
535
536
    void wait_for_close_event(int64_t observed_version, int64_t timeout_ms);
537
538
    void notify_close_wait();
539
540
    Status check_each_node_channel_close(
541
            std::unordered_set<int64_t>* unfinished_node_channel_ids,
542
            std::unordered_map<int64_t, AddBatchCounter>* node_add_batch_counter_map,
543
            WriterStats* writer_stats, Status status);
544
545
    // set error tablet info in runtime state, so that it can be returned to FE.
546
    void set_error_tablet_in_state(RuntimeState* state);
547
548
0
    size_t num_node_channels() const { return _node_channels.size(); }
549
550
0
    size_t get_pending_bytes() const {
551
0
        size_t mem_consumption = 0;
552
0
        for (const auto& kv : _node_channels) {
553
0
            mem_consumption += kv.second->get_pending_bytes();
554
0
        }
555
0
        return mem_consumption;
556
0
    }
557
558
    void set_tablets_received_rows(
559
            const std::vector<std::pair<int64_t, int64_t>>& tablets_received_rows, int64_t node_id);
560
561
    void set_tablets_filtered_rows(
562
            const std::vector<std::pair<int64_t, int64_t>>& tablets_filtered_rows, int64_t node_id);
563
564
0
    int64_t num_rows_filtered() {
565
        // the Unique table has no roll up or materilized view
566
        // we just add up filtered rows from all partitions
567
0
        return std::accumulate(_tablets_filtered_rows.cbegin(), _tablets_filtered_rows.cend(), 0,
568
0
                               [](int64_t sum, const auto& a) { return sum + a.second[0].second; });
569
0
    }
570
571
    // check whether the rows num written by different replicas is consistent
572
    Status check_tablet_received_rows_consistency();
573
574
    // check whether the rows num filtered by different replicas is consistent
575
    Status check_tablet_filtered_rows_consistency();
576
577
0
    void set_start_time(const int64_t& start_time) { _start_time = start_time; }
578
579
0
    VExprContextSPtr get_where_clause() { return _where_clause; }
580
581
private:
582
    friend class VNodeChannel;
583
    friend class VTabletWriter;
584
    friend class VRowDistribution;
585
586
    int _max_failed_replicas(int64_t tablet_id);
587
588
    int _load_required_replicas_num(int64_t tablet_id);
589
590
    bool _quorum_success(const std::unordered_set<int64_t>& unfinished_node_channel_ids,
591
                         const std::unordered_set<int64_t>& need_finish_tablets);
592
593
    int64_t _calc_max_wait_time_ms(const std::unordered_set<int64_t>& unfinished_node_channel_ids);
594
595
    VTabletWriter* _parent = nullptr;
596
    int64_t _index_id;
597
    VExprContextSPtr _where_clause;
598
599
    // from backend channel to tablet_id
600
    // ATTN: must be placed before `_node_channels` and `_channels_by_tablet`.
601
    // Because the destruct order of objects is opposite to the creation order.
602
    // So NodeChannel will be destructured first.
603
    // And the destructor function of NodeChannel waits for all RPCs to finish.
604
    // This ensures that it is safe to use `_tablets_by_channel` in the callback function for the end of the RPC.
605
    std::unordered_map<int64_t, std::unordered_set<int64_t>> _tablets_by_channel;
606
    // BeId -> channel
607
    std::unordered_map<int64_t, std::shared_ptr<VNodeChannel>> _node_channels;
608
    // from tablet_id to backend channel
609
    std::unordered_map<int64_t, std::vector<std::shared_ptr<VNodeChannel>>> _channels_by_tablet;
610
    // from partition_id to FE-planned bucket owner channel in cloud adaptive random bucket mode
611
    std::unordered_map<int64_t, std::shared_ptr<VNodeChannel>> _channels_by_partition;
612
    bool _has_inc_node = false;
613
614
    // lock to protect _failed_channels and _failed_channels_msgs
615
    mutable std::mutex _fail_lock;
616
    // key is tablet_id, value is a set of failed node id
617
    std::unordered_map<int64_t, std::unordered_set<int64_t>> _failed_channels;
618
    // key is tablet_id, value is error message
619
    std::unordered_map<int64_t, std::string> _failed_channels_msgs;
620
    Status _intolerable_failure_status = Status::OK();
621
622
    std::unique_ptr<MemTracker> _index_channel_tracker;
623
    // rows num received by DeltaWriter per tablet, tablet_id -> <node_Id, rows_num>
624
    // used to verify whether the rows num received by different replicas is consistent
625
    std::map<int64_t, std::vector<std::pair<int64_t, int64_t>>> _tablets_received_rows;
626
627
    // rows num filtered by DeltaWriter per tablet, tablet_id -> <node_Id, filtered_rows_num>
628
    // used to verify whether the rows num filtered by different replicas is consistent
629
    std::map<int64_t, std::vector<std::pair<int64_t, int64_t>>> _tablets_filtered_rows;
630
631
    int64_t _start_time = 0;
632
633
    std::atomic<int64_t> _close_wait_version {0};
634
    bthread::Mutex _close_wait_mutex;
635
    bthread::ConditionVariable _close_wait_cv;
636
};
637
} // namespace doris
638
639
namespace doris {
640
//
641
// write result to file
642
class VTabletWriter final : public AsyncResultWriter {
643
public:
644
    VTabletWriter(const TDataSink& t_sink, const VExprContextSPtrs& output_exprs,
645
                  std::shared_ptr<Dependency> dep, std::shared_ptr<Dependency> fin_dep);
646
647
    Status write(RuntimeState* state, Block& block) override;
648
649
    Status close(Status) override;
650
651
    Status open(RuntimeState* state, RuntimeProfile* profile) override;
652
653
    // the consumer func of sending pending batches in every NodeChannel.
654
    // use polling & NodeChannel::try_send_and_fetch_status() to achieve nonblocking sending.
655
    // only focus on pending batches and channel status, the internal errors of NodeChannels will be handled by the producer
656
    void _send_batch_process();
657
658
    Status on_partitions_created(TCreatePartitionResult* result);
659
660
    Status _send_new_partition_batch();
661
662
private:
663
    friend class VNodeChannel;
664
    friend class IndexChannel;
665
666
    using ChannelDistributionPayload = std::unordered_map<VNodeChannel*, Payload>;
667
    using ChannelDistributionPayloadVec = std::vector<std::unordered_map<VNodeChannel*, Payload>>;
668
669
    Status _init_row_distribution();
670
671
    Status _init(RuntimeState* state, RuntimeProfile* profile);
672
673
    Status _generate_one_index_channel_payload(RowPartTabletIds& row_part_tablet_tuple,
674
                                               int32_t index_idx,
675
                                               ChannelDistributionPayload& channel_payload);
676
677
    Status _generate_index_channels_payloads(std::vector<RowPartTabletIds>& row_part_tablet_ids,
678
                                             ChannelDistributionPayloadVec& payload);
679
680
    void _cancel_all_channel(Status status);
681
682
    Status _incremental_open_node_channel(const std::vector<TOlapTablePartition>& partitions);
683
684
    void _do_try_close(RuntimeState* state, const Status& exec_status);
685
686
    void _build_tablet_replica_info(const int64_t tablet_id, VOlapTablePartition* partition);
687
688
    TDataSink _t_sink;
689
690
    std::shared_ptr<MemTracker> _mem_tracker;
691
692
    ObjectPool* _pool = nullptr;
693
694
    bthread_t _sender_thread = 0;
695
696
    // unique load id
697
    PUniqueId _load_id;
698
    int64_t _txn_id = -1;
699
    int _num_replicas = -1;
700
    int _tuple_desc_id = -1;
701
702
    // this is tuple descriptor of destination OLAP table
703
    TupleDescriptor* _output_tuple_desc = nullptr;
704
    RowDescriptor* _output_row_desc = nullptr;
705
706
    // number of senders used to insert into OlapTable, if we only support single node insert,
707
    // all data from select should collectted and then send to OlapTable.
708
    // To support multiple senders, we maintain a channel for each sender.
709
    int _sender_id = -1;
710
    int _num_senders = -1;
711
    bool _is_high_priority = false;
712
713
    // TODO(zc): think about cache this data
714
    std::shared_ptr<OlapTableSchemaParam> _schema;
715
    OlapTableLocationParam* _location = nullptr;
716
    DorisNodesInfo* _nodes_info = nullptr;
717
718
    std::unique_ptr<OlapTabletFinder> _tablet_finder;
719
720
    // index_channel
721
    bthread::Mutex _stop_check_channel;
722
    std::vector<std::shared_ptr<IndexChannel>> _channels;
723
    std::unordered_map<int64_t, std::shared_ptr<IndexChannel>> _index_id_to_channel;
724
    // Table-level row-binlog LSN buffer
725
    std::shared_ptr<AutoIncIDBuffer> _row_binlog_lsn_buffer;
726
727
    std::unique_ptr<ThreadPoolToken> _send_batch_thread_pool_token;
728
729
    // support only one partition column now
730
    std::vector<std::vector<TStringLiteral>> _partitions_need_create;
731
732
    std::unique_ptr<OlapTableBlockConvertor> _block_convertor;
733
    // Stats for this
734
    int64_t _send_data_ns = 0;
735
    int64_t _number_input_rows = 0;
736
    int64_t _number_output_rows = 0;
737
    int64_t _filter_ns = 0;
738
739
    MonotonicStopWatch _row_distribution_watch;
740
741
    RuntimeProfile::Counter* _input_rows_counter = nullptr;
742
    RuntimeProfile::Counter* _output_rows_counter = nullptr;
743
    RuntimeProfile::Counter* _filtered_rows_counter = nullptr;
744
    RuntimeProfile::Counter* _send_data_timer = nullptr;
745
    RuntimeProfile::Counter* _row_distribution_timer = nullptr;
746
    RuntimeProfile::Counter* _append_node_channel_timer = nullptr;
747
    RuntimeProfile::Counter* _filter_timer = nullptr;
748
    RuntimeProfile::Counter* _where_clause_timer = nullptr;
749
    RuntimeProfile::Counter* _add_partition_request_timer = nullptr;
750
    RuntimeProfile::Counter* _wait_mem_limit_timer = nullptr;
751
    RuntimeProfile::Counter* _validate_data_timer = nullptr;
752
    RuntimeProfile::Counter* _open_timer = nullptr;
753
    RuntimeProfile::Counter* _close_timer = nullptr;
754
    RuntimeProfile::Counter* _non_blocking_send_timer = nullptr;
755
    RuntimeProfile::Counter* _non_blocking_send_work_timer = nullptr;
756
    RuntimeProfile::Counter* _serialize_batch_timer = nullptr;
757
    RuntimeProfile::Counter* _total_add_batch_exec_timer = nullptr;
758
    RuntimeProfile::Counter* _max_add_batch_exec_timer = nullptr;
759
    RuntimeProfile::Counter* _total_wait_exec_timer = nullptr;
760
    RuntimeProfile::Counter* _max_wait_exec_timer = nullptr;
761
    RuntimeProfile::Counter* _add_batch_number = nullptr;
762
    RuntimeProfile::Counter* _num_node_channels = nullptr;
763
    RuntimeProfile::Counter* _load_back_pressure_version_time_ms = nullptr;
764
765
    // the timeout of load channels opened by this tablet sink. in second
766
    int64_t _load_channel_timeout_s = 0;
767
    // the load txn absolute expiration time.
768
    int64_t _txn_expiration = 0;
769
770
    int32_t _send_batch_parallelism = 1;
771
    // Save the status of try_close() and close() method
772
    Status _close_status;
773
    // if we called try_close(), for auto partition the periodic send thread should stop if it's still waiting for node channels first-time open.
774
    // atomic: written by pthread (_do_try_close), read by bthread (_send_batch_process)
775
    std::atomic<bool> _try_close {false};
776
    bool _inited = false;
777
    bool _write_file_cache = false;
778
779
    // User can change this config at runtime, avoid it being modified during query or loading process.
780
    bool _transfer_large_data_by_brpc = false;
781
782
    VOlapTablePartitionParam* _vpartition = nullptr;
783
784
    RuntimeState* _state = nullptr; // not owned, set when open
785
786
    VRowDistribution _row_distribution;
787
    // reuse to avoid frequent memory allocation and release.
788
    std::vector<RowPartTabletIds> _row_part_tablet_ids;
789
790
    // tablet_id -> <total replicas num, load required replicas num>
791
    std::unordered_map<int64_t, std::pair<int, int>> _tablet_replica_info;
792
793
    // tablet_id -> set of backend_ids that have version gaps
794
    // these backends' success should not be counted for majority write
795
    std::unordered_map<int64_t, std::unordered_set<int64_t>> _tablet_version_gap_backends;
796
};
797
} // namespace doris