Coverage Report

Created: 2026-07-24 12:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/load/channel/load_stream.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 "load/channel/load_stream.h"
19
20
#include <brpc/stream.h>
21
#include <bthread/bthread.h>
22
#include <bthread/condition_variable.h>
23
#include <bthread/mutex.h>
24
25
#include <memory>
26
#include <sstream>
27
28
#include "bvar/bvar.h"
29
#include "cloud/config.h"
30
#include "common/signal_handler.h"
31
#include "load/channel/load_channel.h"
32
#include "load/channel/load_stream_mgr.h"
33
#include "load/channel/load_stream_writer.h"
34
#include "load/delta_writer/delta_writer.h"
35
#include "runtime/exec_env.h"
36
#include "runtime/fragment_mgr.h"
37
#include "runtime/runtime_profile.h"
38
#include "runtime/workload_group/workload_group_manager.h"
39
#include "storage/rowset/rowset_factory.h"
40
#include "storage/rowset/rowset_meta.h"
41
#include "storage/storage_engine.h"
42
#include "storage/tablet/tablet.h"
43
#include "storage/tablet/tablet_fwd.h"
44
#include "storage/tablet/tablet_manager.h"
45
#include "storage/tablet/tablet_schema.h"
46
#include "storage/tablet_info.h"
47
#include "util/debug_points.h"
48
#include "util/thrift_util.h"
49
#include "util/uid_util.h"
50
51
#define UNKNOWN_ID_FOR_TEST 0x7c00
52
53
namespace doris {
54
55
bvar::Adder<int64_t> g_load_stream_cnt("load_stream_count");
56
bvar::LatencyRecorder g_load_stream_flush_wait_ms("load_stream_flush_wait_ms");
57
bvar::Adder<int> g_load_stream_flush_running_threads("load_stream_flush_wait_threads");
58
59
TabletStream::TabletStream(const PUniqueId& load_id, int64_t id, int64_t txn_id,
60
                           LoadStreamMgr* load_stream_mgr, RuntimeProfile* profile)
61
15
        : _id(id),
62
15
          _next_segid(0),
63
15
          _load_id(load_id),
64
15
          _txn_id(txn_id),
65
15
          _load_stream_mgr(load_stream_mgr) {
66
15
    load_stream_mgr->create_token(_flush_token);
67
15
    _profile = profile->create_child(fmt::format("TabletStream {}", id), true, true);
68
15
    _append_data_timer = ADD_TIMER(_profile, "AppendDataTime");
69
15
    _add_segment_timer = ADD_TIMER(_profile, "AddSegmentTime");
70
15
    _close_wait_timer = ADD_TIMER(_profile, "CloseWaitTime");
71
15
}
72
73
10
inline std::ostream& operator<<(std::ostream& ostr, const TabletStream& tablet_stream) {
74
10
    ostr << "load_id=" << print_id(tablet_stream._load_id) << ", txn_id=" << tablet_stream._txn_id
75
10
         << ", tablet_id=" << tablet_stream._id << ", status=" << tablet_stream._status.status();
76
10
    return ostr;
77
10
}
78
79
Status TabletStream::init(std::shared_ptr<OlapTableSchemaParam> schema, int64_t index_id,
80
15
                          int64_t partition_id) {
81
15
    WriteRequest req {
82
15
            .tablet_id = _id,
83
15
            .txn_id = _txn_id,
84
15
            .index_id = index_id,
85
15
            .partition_id = partition_id,
86
15
            .load_id = _load_id,
87
15
            .table_schema_param = schema,
88
            // TODO(plat1ko): write_file_cache
89
15
            .storage_vault_id {},
90
15
    };
91
92
15
    _load_stream_writer = std::make_shared<LoadStreamWriter>(&req, _profile);
93
15
    DBUG_EXECUTE_IF("TabletStream.init.uninited_writer", {
94
15
        _status.update(Status::Uninitialized("fault injection"));
95
15
        return _status.status();
96
15
    });
97
15
    _status.update(_load_stream_writer->init());
98
15
    if (!_status.ok()) {
99
1
        LOG(INFO) << "failed to init rowset builder due to " << *this;
100
1
    }
101
15
    return _status.status();
102
15
}
103
104
27
Status TabletStream::append_data(const PStreamHeader& header, butil::IOBuf* data) {
105
27
    if (!_status.ok()) {
106
1
        return _status.status();
107
1
    }
108
109
    // dispatch add_segment request
110
26
    if (header.opcode() == PStreamHeader::ADD_SEGMENT) {
111
0
        return add_segment(header, data);
112
0
    }
113
114
26
    SCOPED_TIMER(_append_data_timer);
115
116
26
    int64_t src_id = header.src_id();
117
26
    uint32_t segid = header.segment_id();
118
    // Ensure there are enough space and mapping are built.
119
26
    SegIdMapping* mapping = nullptr;
120
26
    {
121
26
        std::lock_guard lock_guard(_lock);
122
26
        if (!_segids_mapping.contains(src_id)) {
123
14
            _segids_mapping[src_id] = std::make_unique<SegIdMapping>();
124
14
        }
125
26
        mapping = _segids_mapping[src_id].get();
126
26
    }
127
26
    if (segid + 1 > mapping->size()) {
128
        // TODO: Each sender lock is enough.
129
15
        std::lock_guard lock_guard(_lock);
130
15
        ssize_t origin_size = mapping->size();
131
15
        if (segid + 1 > origin_size) {
132
15
            mapping->resize(segid + 1, std::numeric_limits<uint32_t>::max());
133
39
            for (size_t index = origin_size; index <= segid; index++) {
134
24
                mapping->at(index) = _next_segid;
135
24
                _next_segid++;
136
24
                VLOG_DEBUG << "src_id=" << src_id << ", segid=" << index << " to "
137
0
                           << " segid=" << _next_segid - 1 << ", " << *this;
138
24
            }
139
15
        }
140
15
    }
141
142
    // Each sender sends data in one segment sequential, so we also do not
143
    // need a lock here.
144
26
    bool eos = header.segment_eos();
145
26
    FileType file_type = header.file_type();
146
26
    uint32_t new_segid = mapping->at(segid);
147
26
    DCHECK(new_segid != std::numeric_limits<uint32_t>::max());
148
26
    butil::IOBuf buf = data->movable();
149
26
    auto flush_func = [this, new_segid, eos, buf, header, file_type]() mutable {
150
26
        signal::set_signal_task_id(_load_id);
151
26
        g_load_stream_flush_running_threads << -1;
152
26
        auto st = _load_stream_writer->append_data(new_segid, header.offset(), buf, file_type);
153
26
        if (!st.ok() && !config::is_cloud_mode()) {
154
1
            auto res = ExecEnv::get_tablet(_id);
155
1
            TabletSharedPtr tablet =
156
1
                    res.has_value() ? std::dynamic_pointer_cast<Tablet>(res.value()) : nullptr;
157
1
            if (tablet) {
158
1
                tablet->report_error(st);
159
1
            }
160
1
        }
161
26
        if (eos && st.ok()) {
162
21
            DBUG_EXECUTE_IF("TabletStream.append_data.unknown_file_type",
163
21
                            { file_type = static_cast<FileType>(-1); });
164
21
            if (file_type == FileType::SEGMENT_FILE || file_type == FileType::INVERTED_INDEX_FILE) {
165
21
                st = _load_stream_writer->close_writer(new_segid, file_type);
166
21
            } else {
167
0
                st = Status::InternalError(
168
0
                        "appent data failed, file type error, file type = {}, "
169
0
                        "segment_id={}",
170
0
                        file_type, new_segid);
171
0
            }
172
21
        }
173
26
        DBUG_EXECUTE_IF("TabletStream.append_data.append_failed",
174
26
                        { st = Status::InternalError("fault injection"); });
175
26
        if (!st.ok()) {
176
2
            _status.update(st);
177
2
            LOG(WARNING) << "write data failed " << st << ", " << *this;
178
2
        }
179
26
    };
180
26
    auto load_stream_flush_token_max_tasks = config::load_stream_flush_token_max_tasks;
181
26
    auto load_stream_max_wait_flush_token_time_ms =
182
26
            config::load_stream_max_wait_flush_token_time_ms;
183
26
    DBUG_EXECUTE_IF("TabletStream.append_data.long_wait", {
184
26
        load_stream_flush_token_max_tasks = 0;
185
26
        load_stream_max_wait_flush_token_time_ms = 1000;
186
26
    });
187
26
    MonotonicStopWatch timer;
188
26
    timer.start();
189
26
    while (_flush_token->num_tasks() >= load_stream_flush_token_max_tasks) {
190
0
        if (timer.elapsed_time() / 1000 / 1000 >= load_stream_max_wait_flush_token_time_ms) {
191
0
            _status.update(
192
0
                    Status::Error<true>("wait flush token back pressure time is more than "
193
0
                                        "load_stream_max_wait_flush_token_time {}",
194
0
                                        load_stream_max_wait_flush_token_time_ms));
195
0
            return _status.status();
196
0
        }
197
0
        bthread_usleep(2 * 1000); // 2ms
198
0
    }
199
26
    timer.stop();
200
26
    int64_t time_ms = timer.elapsed_time() / 1000 / 1000;
201
26
    g_load_stream_flush_wait_ms << time_ms;
202
26
    g_load_stream_flush_running_threads << 1;
203
26
    Status st = Status::OK();
204
26
    DBUG_EXECUTE_IF("TabletStream.append_data.submit_func_failed",
205
26
                    { st = Status::InternalError("fault injection"); });
206
26
    if (st.ok()) {
207
26
        st = _flush_token->submit_func(flush_func);
208
26
    }
209
26
    if (!st.ok()) {
210
0
        _status.update(st);
211
0
    }
212
26
    return _status.status();
213
26
}
214
215
0
Status TabletStream::add_segment(const PStreamHeader& header, butil::IOBuf* data) {
216
0
    if (!_status.ok()) {
217
0
        return _status.status();
218
0
    }
219
220
0
    SCOPED_TIMER(_add_segment_timer);
221
0
    DCHECK(header.has_segment_statistics());
222
0
    SegmentStatistics stat(header.segment_statistics());
223
224
0
    int64_t src_id = header.src_id();
225
0
    uint32_t segid = header.segment_id();
226
0
    uint32_t new_segid;
227
0
    DBUG_EXECUTE_IF("TabletStream.add_segment.unknown_segid", { segid = UNKNOWN_ID_FOR_TEST; });
228
0
    {
229
0
        std::lock_guard lock_guard(_lock);
230
0
        if (!_segids_mapping.contains(src_id)) {
231
0
            _status.update(Status::InternalError(
232
0
                    "add segment failed, no segment written by this src be yet, src_id={}, "
233
0
                    "segment_id={}",
234
0
                    src_id, segid));
235
0
            return _status.status();
236
0
        }
237
0
        DBUG_EXECUTE_IF("TabletStream.add_segment.segid_never_written",
238
0
                        { segid = static_cast<uint32_t>(_segids_mapping[src_id]->size()); });
239
0
        if (segid >= _segids_mapping[src_id]->size()) {
240
0
            _status.update(Status::InternalError(
241
0
                    "add segment failed, segment is never written, src_id={}, segment_id={}",
242
0
                    src_id, segid));
243
0
            return _status.status();
244
0
        }
245
0
        new_segid = _segids_mapping[src_id]->at(segid);
246
0
    }
247
0
    DCHECK(new_segid != std::numeric_limits<uint32_t>::max());
248
249
0
    auto add_segment_func = [this, new_segid, stat]() {
250
0
        signal::set_signal_task_id(_load_id);
251
0
        auto st = _load_stream_writer->add_segment(new_segid, stat);
252
0
        DBUG_EXECUTE_IF("TabletStream.add_segment.add_segment_failed",
253
0
                        { st = Status::InternalError("fault injection"); });
254
0
        if (!st.ok()) {
255
0
            _status.update(st);
256
0
            LOG(INFO) << "add segment failed " << *this;
257
0
        }
258
0
    };
259
0
    Status st = Status::OK();
260
0
    DBUG_EXECUTE_IF("TabletStream.add_segment.submit_func_failed",
261
0
                    { st = Status::InternalError("fault injection"); });
262
0
    if (st.ok()) {
263
0
        st = _flush_token->submit_func(add_segment_func);
264
0
    }
265
0
    if (!st.ok()) {
266
0
        _status.update(st);
267
0
    }
268
0
    return _status.status();
269
0
}
270
271
32
Status TabletStream::_run_in_heavy_work_pool(std::function<Status()> fn) {
272
32
    bthread::Mutex mu;
273
32
    std::unique_lock<bthread::Mutex> lock(mu);
274
32
    bthread::ConditionVariable cv;
275
32
    auto st = Status::OK();
276
32
    auto func = [this, &mu, &cv, &st, &fn] {
277
32
        signal::set_signal_task_id(_load_id);
278
32
        st = fn();
279
32
        std::lock_guard<bthread::Mutex> lock(mu);
280
32
        cv.notify_one();
281
32
    };
282
32
    bool ret = _load_stream_mgr->heavy_work_pool()->try_offer(func);
283
32
    if (!ret) {
284
0
        return Status::Error<ErrorCode::INTERNAL_ERROR>(
285
0
                "there is not enough thread resource for close load");
286
0
    }
287
32
    cv.wait(lock);
288
32
    return st;
289
32
}
290
291
30
void TabletStream::wait_for_flush_tasks() {
292
30
    {
293
30
        std::lock_guard lock_guard(_lock);
294
30
        if (_flush_tasks_done) {
295
15
            return;
296
15
        }
297
15
        _flush_tasks_done = true;
298
15
    }
299
300
15
    if (!_status.ok()) {
301
2
        _flush_token->shutdown();
302
2
        return;
303
2
    }
304
305
    // Use heavy_work_pool to avoid blocking bthread
306
13
    auto st = _run_in_heavy_work_pool([this]() {
307
13
        _flush_token->wait();
308
13
        return Status::OK();
309
13
    });
310
13
    if (!st.ok()) {
311
        // If heavy_work_pool is unavailable, fall back to shutdown
312
        // which will cancel pending tasks and wait for running tasks
313
0
        _flush_token->shutdown();
314
0
        _status.update(st);
315
0
    }
316
13
}
317
318
15
void TabletStream::pre_close() {
319
15
    SCOPED_TIMER(_close_wait_timer);
320
15
    wait_for_flush_tasks();
321
322
15
    if (!_status.ok()) {
323
3
        return;
324
3
    }
325
326
12
    DBUG_EXECUTE_IF("TabletStream.close.segment_num_mismatch", { _num_segments++; });
327
12
    if (_check_num_segments && (_next_segid.load() != _num_segments)) {
328
2
        _status.update(Status::Corruption(
329
2
                "segment num mismatch in tablet {}, expected: {}, actual: {}, load_id: {}", _id,
330
2
                _num_segments, _next_segid.load(), print_id(_load_id)));
331
2
        return;
332
2
    }
333
334
10
    _status.update(_run_in_heavy_work_pool([this]() { return _load_stream_writer->pre_close(); }));
335
10
}
336
337
15
Status TabletStream::close() {
338
15
    if (!_status.ok()) {
339
6
        return _status.status();
340
6
    }
341
342
9
    SCOPED_TIMER(_close_wait_timer);
343
9
    _status.update(_run_in_heavy_work_pool([this]() { return _load_stream_writer->close(); }));
344
9
    return _status.status();
345
15
}
346
347
IndexStream::IndexStream(const PUniqueId& load_id, int64_t id, int64_t txn_id,
348
                         std::shared_ptr<OlapTableSchemaParam> schema,
349
                         LoadStreamMgr* load_stream_mgr, RuntimeProfile* profile)
350
30
        : _id(id),
351
30
          _load_id(load_id),
352
30
          _txn_id(txn_id),
353
30
          _schema(schema),
354
30
          _load_stream_mgr(load_stream_mgr) {
355
30
    _profile = profile->create_child(fmt::format("IndexStream {}", id), true, true);
356
30
    _append_data_timer = ADD_TIMER(_profile, "AppendDataTime");
357
30
    _close_wait_timer = ADD_TIMER(_profile, "CloseWaitTime");
358
30
}
359
360
30
IndexStream::~IndexStream() {
361
    // Ensure all TabletStreams have their flush tokens properly handled before destruction.
362
    // In normal flow, close() should have called pre_close() on all tablet streams.
363
    // But if IndexStream is destroyed without close() being called (e.g., on_idle_timeout),
364
    // we need to wait for flush tasks here to ensure flush tokens are properly shut down.
365
30
    for (auto& [_, tablet_stream] : _tablet_streams_map) {
366
15
        tablet_stream->wait_for_flush_tasks();
367
15
    }
368
30
}
369
370
27
Status IndexStream::append_data(const PStreamHeader& header, butil::IOBuf* data) {
371
27
    SCOPED_TIMER(_append_data_timer);
372
27
    int64_t tablet_id = header.tablet_id();
373
27
    TabletStreamSharedPtr tablet_stream;
374
27
    {
375
27
        std::lock_guard lock_guard(_lock);
376
27
        auto it = _tablet_streams_map.find(tablet_id);
377
27
        if (it == _tablet_streams_map.end()) {
378
13
            _init_tablet_stream(tablet_stream, tablet_id, header.partition_id());
379
14
        } else {
380
14
            tablet_stream = it->second;
381
14
        }
382
27
    }
383
384
27
    return tablet_stream->append_data(header, data);
385
27
}
386
387
void IndexStream::_init_tablet_stream(TabletStreamSharedPtr& tablet_stream, int64_t tablet_id,
388
15
                                      int64_t partition_id) {
389
15
    tablet_stream = std::make_shared<TabletStream>(_load_id, tablet_id, _txn_id, _load_stream_mgr,
390
15
                                                   _profile);
391
15
    _tablet_streams_map[tablet_id] = tablet_stream;
392
15
    auto st = tablet_stream->init(_schema, _id, partition_id);
393
15
    if (!st.ok()) {
394
1
        LOG(WARNING) << "tablet stream init failed " << *tablet_stream;
395
1
    }
396
15
}
397
398
0
void IndexStream::get_all_write_tablet_ids(std::vector<int64_t>* tablet_ids) {
399
0
    std::lock_guard lock_guard(_lock);
400
0
    for (const auto& [tablet_id, _] : _tablet_streams_map) {
401
0
        tablet_ids->push_back(tablet_id);
402
0
    }
403
0
}
404
405
void IndexStream::close(const std::vector<PTabletID>& tablets_to_commit,
406
30
                        std::vector<int64_t>* success_tablet_ids, FailedTablets* failed_tablets) {
407
30
    std::lock_guard lock_guard(_lock);
408
30
    SCOPED_TIMER(_close_wait_timer);
409
    // open all need commit tablets
410
40
    for (const auto& tablet : tablets_to_commit) {
411
40
        if (_id != tablet.index_id()) {
412
21
            continue;
413
21
        }
414
19
        TabletStreamSharedPtr tablet_stream;
415
19
        auto it = _tablet_streams_map.find(tablet.tablet_id());
416
19
        if (it == _tablet_streams_map.end()) {
417
2
            _init_tablet_stream(tablet_stream, tablet.tablet_id(), tablet.partition_id());
418
17
        } else {
419
17
            tablet_stream = it->second;
420
17
        }
421
19
        if (tablet.has_num_segments()) {
422
16
            tablet_stream->add_num_segments(tablet.num_segments());
423
16
        } else {
424
            // for compatibility reasons (sink from old version BE)
425
3
            tablet_stream->disable_num_segments_check();
426
3
        }
427
19
    }
428
429
30
    for (auto& [_, tablet_stream] : _tablet_streams_map) {
430
15
        tablet_stream->pre_close();
431
15
    }
432
433
30
    for (auto& [_, tablet_stream] : _tablet_streams_map) {
434
15
        auto st = tablet_stream->close();
435
15
        if (st.ok()) {
436
9
            success_tablet_ids->push_back(tablet_stream->id());
437
9
        } else {
438
6
            LOG(INFO) << "close tablet stream " << *tablet_stream << ", status=" << st;
439
6
            failed_tablets->emplace_back(tablet_stream->id(), st);
440
6
        }
441
15
    }
442
30
}
443
444
// TODO: Profile is temporary disabled, because:
445
// 1. It's not being processed by the upstream for now
446
// 2. There are some problems in _profile->to_thrift()
447
LoadStream::LoadStream(const PUniqueId& load_id, LoadStreamMgr* load_stream_mgr,
448
                       bool enable_profile)
449
15
        : _load_id(load_id), _enable_profile(false), _load_stream_mgr(load_stream_mgr) {
450
15
    g_load_stream_cnt << 1;
451
15
    _profile = std::make_unique<RuntimeProfile>("LoadStream");
452
15
    _append_data_timer = ADD_TIMER(_profile, "AppendDataTime");
453
15
    _close_wait_timer = ADD_TIMER(_profile, "CloseWaitTime");
454
15
    TUniqueId load_tid = ((UniqueId)load_id).to_thrift();
455
#ifndef BE_TEST
456
    std::shared_ptr<QueryContext> query_context =
457
            ExecEnv::GetInstance()->fragment_mgr()->get_query_ctx(load_tid);
458
    if (query_context != nullptr) {
459
        _resource_ctx = query_context->resource_ctx();
460
    } else {
461
        _resource_ctx = ResourceContext::create_shared();
462
        _resource_ctx->task_controller()->set_task_id(load_tid);
463
        std::shared_ptr<MemTrackerLimiter> mem_tracker = MemTrackerLimiter::create_shared(
464
                MemTrackerLimiter::Type::LOAD,
465
                fmt::format("(FromLoadStream)Load#Id={}", ((UniqueId)load_id).to_string()));
466
        _resource_ctx->memory_context()->set_mem_tracker(mem_tracker);
467
    }
468
#else
469
15
    _resource_ctx = ResourceContext::create_shared();
470
15
    _resource_ctx->task_controller()->set_task_id(load_tid);
471
15
    std::shared_ptr<MemTrackerLimiter> mem_tracker = MemTrackerLimiter::create_shared(
472
15
            MemTrackerLimiter::Type::LOAD,
473
15
            fmt::format("(FromLoadStream)Load#Id={}", ((UniqueId)load_id).to_string()));
474
15
    _resource_ctx->memory_context()->set_mem_tracker(mem_tracker);
475
15
#endif
476
15
}
477
478
15
LoadStream::~LoadStream() {
479
15
    g_load_stream_cnt << -1;
480
15
    LOG(INFO) << "load stream is deconstructed " << *this;
481
15
}
482
483
15
Status LoadStream::init(const POpenLoadStreamRequest* request) {
484
15
    _txn_id = request->txn_id();
485
15
    _total_streams = static_cast<int32_t>(request->total_streams());
486
15
    _is_incremental = (_total_streams == 0);
487
488
15
    _schema = std::make_shared<OlapTableSchemaParam>();
489
15
    RETURN_IF_ERROR(_schema->init(request->schema()));
490
30
    for (auto& index : request->schema().indexes()) {
491
30
        _index_streams_map[index.id()] = std::make_shared<IndexStream>(
492
30
                _load_id, index.id(), _txn_id, _schema, _load_stream_mgr, _profile.get());
493
30
    }
494
15
    LOG(INFO) << "succeed to init load stream " << *this;
495
15
    return Status::OK();
496
15
}
497
498
bool LoadStream::close(int64_t src_id, const std::vector<PTabletID>& tablets_to_commit,
499
19
                       std::vector<int64_t>* success_tablet_ids, FailedTablets* failed_tablets) {
500
19
    std::lock_guard<bthread::Mutex> lock_guard(_lock);
501
19
    SCOPED_TIMER(_close_wait_timer);
502
503
    // we do nothing until recv CLOSE_LOAD from all stream to ensure all data are handled before ack
504
19
    _open_streams[src_id]--;
505
19
    if (_open_streams[src_id] == 0) {
506
19
        _open_streams.erase(src_id);
507
19
    }
508
19
    _close_load_cnt++;
509
19
    LOG(INFO) << "received CLOSE_LOAD from sender " << src_id << ", remaining "
510
19
              << _total_streams - _close_load_cnt << " senders, " << *this;
511
512
19
    _tablets_to_commit.insert(_tablets_to_commit.end(), tablets_to_commit.begin(),
513
19
                              tablets_to_commit.end());
514
515
19
    if (_close_load_cnt < _total_streams) {
516
        // do not return commit info if there is remaining streams.
517
4
        return false;
518
4
    }
519
520
30
    for (auto& [_, index_stream] : _index_streams_map) {
521
30
        index_stream->close(_tablets_to_commit, success_tablet_ids, failed_tablets);
522
30
    }
523
15
    LOG(INFO) << "close load " << *this << ", success_tablet_num=" << success_tablet_ids->size()
524
15
              << ", failed_tablet_num=" << failed_tablets->size();
525
15
    return true;
526
19
}
527
528
std::vector<int64_t> LoadStream::mark_eos_sent_and_collect(int64_t stream_id,
529
19
                                                          bool is_incremental) {
530
19
    std::lock_guard<bthread::Mutex> lock_guard(_lock);
531
19
    std::vector<int64_t> to_close;
532
    // A non-incremental stream is closed as soon as its own CLOSE_LOAD (and EOS)
533
    // is handled -- this is the first batch of streams, known up front, not subject
534
    // to fencing. Closing it promptly also means a duplicate/late CLOSE_LOAD lands
535
    // on an already-closed stream and is dropped, instead of being counted again.
536
    // An incremental stream must be deferred (fencing #56120: it may only close once
537
    // every non-incremental stream is closed), so it is parked in _eos_sent_stream_ids
538
    // until all CLOSE_LOADs have been received.
539
19
    if (is_incremental) {
540
        // Parked only after the caller sent this stream's EOS via _report_result,
541
        // so every parked id is safe to close.
542
3
        _eos_sent_stream_ids.push_back(stream_id);
543
16
    } else {
544
16
        to_close.push_back(stream_id);
545
16
    }
546
    // `_close_load_cnt == _total_streams` means every CLOSE_LOAD has been counted by
547
    // close(). Latch it so that any thread reaching here afterwards also drains the
548
    // parked incremental streams, guaranteeing none is left un-closed regardless of
549
    // thread interleaving (fixes the split-lock leak race).
550
19
    if (_close_load_cnt >= _total_streams) {
551
17
        _all_close_load_received = true;
552
17
    }
553
19
    if (_all_close_load_received) {
554
17
        for (const auto& parked_id : _eos_sent_stream_ids) {
555
3
            to_close.push_back(parked_id);
556
3
        }
557
17
        _eos_sent_stream_ids.clear();
558
17
    }
559
19
    return to_close;
560
19
}
561
562
void LoadStream::_report_result(StreamId stream, const Status& status,
563
                                const std::vector<int64_t>& success_tablet_ids,
564
39
                                const FailedTablets& failed_tablets, bool eos) {
565
39
    LOG(INFO) << "report result " << *this << ", success tablet num " << success_tablet_ids.size()
566
39
              << ", failed tablet num " << failed_tablets.size();
567
39
    butil::IOBuf buf;
568
39
    PLoadStreamResponse response;
569
39
    response.set_eos(eos);
570
39
    status.to_protobuf(response.mutable_status());
571
39
    for (auto& id : success_tablet_ids) {
572
9
        response.add_success_tablet_ids(id);
573
9
    }
574
39
    for (auto& [id, st] : failed_tablets) {
575
10
        auto pb = response.add_failed_tablets();
576
10
        pb->set_id(id);
577
10
        st.to_protobuf(pb->mutable_status());
578
10
    }
579
580
39
    if (_enable_profile && _close_load_cnt == _total_streams) {
581
0
        TRuntimeProfileTree tprofile;
582
0
        ThriftSerializer ser(false, 4096);
583
0
        uint8_t* profile_buf = nullptr;
584
0
        uint32_t len = 0;
585
0
        std::unique_lock<bthread::Mutex> l(_lock);
586
587
0
        _profile->to_thrift(&tprofile);
588
0
        auto st = ser.serialize(&tprofile, &len, &profile_buf);
589
0
        if (st.ok()) {
590
0
            response.set_load_stream_profile(profile_buf, len);
591
0
        } else {
592
0
            LOG(WARNING) << "TRuntimeProfileTree serialize failed, errmsg=" << st << ", " << *this;
593
0
        }
594
0
    }
595
596
39
    buf.append(response.SerializeAsString());
597
39
    auto wst = _write_stream(stream, buf);
598
39
    if (!wst.ok()) {
599
0
        LOG(WARNING) << " report result failed with " << wst << ", " << *this;
600
0
    }
601
39
}
602
603
0
void LoadStream::_report_schema(StreamId stream, const PStreamHeader& hdr) {
604
0
    butil::IOBuf buf;
605
0
    PLoadStreamResponse response;
606
0
    Status st = Status::OK();
607
0
    for (const auto& req : hdr.tablets()) {
608
0
        BaseTabletSPtr tablet;
609
0
        if (auto res = ExecEnv::get_tablet(req.tablet_id()); res.has_value()) {
610
0
            tablet = std::move(res).value();
611
0
        } else {
612
0
            st = std::move(res).error();
613
0
            break;
614
0
        }
615
0
        auto* resp = response.add_tablet_schemas();
616
0
        resp->set_index_id(req.index_id());
617
0
        resp->set_enable_unique_key_merge_on_write(tablet->enable_unique_key_merge_on_write());
618
0
        tablet->tablet_schema()->to_schema_pb(resp->mutable_tablet_schema());
619
0
    }
620
0
    st.to_protobuf(response.mutable_status());
621
622
0
    buf.append(response.SerializeAsString());
623
0
    auto wst = _write_stream(stream, buf);
624
0
    if (!wst.ok()) {
625
0
        LOG(WARNING) << " report result failed with " << wst << ", " << *this;
626
0
    }
627
0
}
628
629
0
void LoadStream::_report_tablet_load_info(StreamId stream, int64_t index_id) {
630
0
    std::vector<int64_t> write_tablet_ids;
631
0
    auto it = _index_streams_map.find(index_id);
632
0
    if (it != _index_streams_map.end()) {
633
0
        it->second->get_all_write_tablet_ids(&write_tablet_ids);
634
0
    }
635
636
0
    if (!write_tablet_ids.empty()) {
637
0
        butil::IOBuf buf;
638
0
        PLoadStreamResponse response;
639
0
        auto* tablet_load_infos = response.mutable_tablet_load_rowset_num_infos();
640
0
        _collect_tablet_load_info_from_tablets(write_tablet_ids, tablet_load_infos);
641
0
        if (tablet_load_infos->empty()) {
642
0
            return;
643
0
        }
644
0
        buf.append(response.SerializeAsString());
645
0
        auto wst = _write_stream(stream, buf);
646
0
        if (!wst.ok()) {
647
0
            LOG(WARNING) << "report tablet load info failed with " << wst << ", " << *this;
648
0
        }
649
0
    }
650
0
}
651
652
void LoadStream::_collect_tablet_load_info_from_tablets(
653
        const std::vector<int64_t>& tablet_ids,
654
0
        google::protobuf::RepeatedPtrField<PTabletLoadRowsetInfo>* tablet_load_infos) {
655
0
    for (auto tablet_id : tablet_ids) {
656
0
        BaseTabletSPtr tablet;
657
0
        if (auto res = ExecEnv::get_tablet(tablet_id); res.has_value()) {
658
0
            tablet = std::move(res).value();
659
0
        } else {
660
0
            continue;
661
0
        }
662
0
        BaseDeltaWriter::collect_tablet_load_rowset_num_info(tablet.get(), tablet_load_infos);
663
0
    }
664
0
}
665
666
39
Status LoadStream::_write_stream(StreamId stream, butil::IOBuf& buf) {
667
39
    for (;;) {
668
39
        int ret = 0;
669
39
        DBUG_EXECUTE_IF("LoadStream._write_stream.EAGAIN", { ret = EAGAIN; });
670
39
        if (ret == 0) {
671
39
            ret = brpc::StreamWrite(stream, buf);
672
39
        }
673
39
        switch (ret) {
674
39
        case 0:
675
39
            return Status::OK();
676
0
        case EAGAIN: {
677
0
            const timespec time = butil::seconds_from_now(config::load_stream_eagain_wait_seconds);
678
0
            int wait_ret = brpc::StreamWait(stream, &time);
679
0
            if (wait_ret != 0) {
680
0
                return Status::InternalError("StreamWait failed, err={}", wait_ret);
681
0
            }
682
0
            break;
683
0
        }
684
0
        default:
685
0
            return Status::InternalError("StreamWrite failed, err={}", ret);
686
39
        }
687
39
    }
688
0
    return Status::OK();
689
39
}
690
691
65
void LoadStream::_parse_header(butil::IOBuf* const message, PStreamHeader& hdr) {
692
65
    butil::IOBufAsZeroCopyInputStream wrapper(*message);
693
65
    hdr.ParseFromZeroCopyStream(&wrapper);
694
65
    VLOG_DEBUG << "header parse result: " << hdr.DebugString();
695
65
}
696
697
28
Status LoadStream::_append_data(const PStreamHeader& header, butil::IOBuf* data) {
698
28
    SCOPED_TIMER(_append_data_timer);
699
28
    IndexStreamSharedPtr index_stream;
700
701
28
    int64_t index_id = header.index_id();
702
28
    DBUG_EXECUTE_IF("TabletStream._append_data.unknown_indexid",
703
28
                    { index_id = UNKNOWN_ID_FOR_TEST; });
704
28
    auto it = _index_streams_map.find(index_id);
705
28
    if (it == _index_streams_map.end()) {
706
1
        return Status::Error<ErrorCode::INVALID_ARGUMENT>("unknown index_id {}", index_id);
707
27
    } else {
708
27
        index_stream = it->second;
709
27
    }
710
711
27
    return index_stream->append_data(header, data);
712
28
}
713
714
53
int LoadStream::on_received_messages(StreamId id, butil::IOBuf* const messages[], size_t size) {
715
53
    VLOG_DEBUG << "on_received_messages " << id << " " << size;
716
118
    for (size_t i = 0; i < size; ++i) {
717
130
        while (messages[i]->size() > 0) {
718
            // step 1: parse header
719
65
            size_t hdr_len = 0;
720
65
            messages[i]->cutn((void*)&hdr_len, sizeof(size_t));
721
65
            butil::IOBuf hdr_buf;
722
65
            PStreamHeader hdr;
723
65
            messages[i]->cutn(&hdr_buf, hdr_len);
724
65
            _parse_header(&hdr_buf, hdr);
725
726
            // step 2: cut data
727
65
            size_t data_len = 0;
728
65
            messages[i]->cutn((void*)&data_len, sizeof(size_t));
729
65
            butil::IOBuf data_buf;
730
65
            PStreamHeader data;
731
65
            messages[i]->cutn(&data_buf, data_len);
732
733
            // step 3: dispatch
734
65
            _dispatch(id, hdr, &data_buf);
735
65
        }
736
65
    }
737
53
    return 0;
738
53
}
739
740
65
void LoadStream::_dispatch(StreamId id, const PStreamHeader& hdr, butil::IOBuf* data) {
741
65
    VLOG_DEBUG << PStreamHeader_Opcode_Name(hdr.opcode()) << " from " << hdr.src_id()
742
0
               << " with tablet " << hdr.tablet_id();
743
65
    SCOPED_ATTACH_TASK(_resource_ctx);
744
    // CLOSE_LOAD message should not be fault injected,
745
    // otherwise the message will be ignored and causing close wait timeout
746
65
    if (hdr.opcode() != PStreamHeader::CLOSE_LOAD) {
747
30
        DBUG_EXECUTE_IF("LoadStream._dispatch.unknown_loadid", {
748
30
            PStreamHeader& t_hdr = const_cast<PStreamHeader&>(hdr);
749
30
            PUniqueId* load_id = t_hdr.mutable_load_id();
750
30
            load_id->set_hi(UNKNOWN_ID_FOR_TEST);
751
30
            load_id->set_lo(UNKNOWN_ID_FOR_TEST);
752
30
        });
753
30
        DBUG_EXECUTE_IF("LoadStream._dispatch.unknown_srcid", {
754
30
            PStreamHeader& t_hdr = const_cast<PStreamHeader&>(hdr);
755
30
            t_hdr.set_src_id(UNKNOWN_ID_FOR_TEST);
756
30
        });
757
30
    }
758
65
    if (UniqueId(hdr.load_id()) != UniqueId(_load_id)) {
759
1
        Status st = Status::Error<ErrorCode::INVALID_ARGUMENT>(
760
1
                "invalid load id {}, expected {}", print_id(hdr.load_id()), print_id(_load_id));
761
1
        _report_failure(id, st, hdr);
762
1
        return;
763
1
    }
764
765
64
    {
766
64
        std::lock_guard lock_guard(_lock);
767
64
        if (!_open_streams.contains(hdr.src_id())) {
768
17
            Status st = Status::Error<ErrorCode::INVALID_ARGUMENT>("no open stream from source {}",
769
17
                                                                   hdr.src_id());
770
17
            _report_failure(id, st, hdr);
771
17
            return;
772
17
        }
773
64
    }
774
775
47
    switch (hdr.opcode()) {
776
0
    case PStreamHeader::ADD_SEGMENT: {
777
0
        auto st = _append_data(hdr, data);
778
0
        if (!st.ok()) {
779
0
            _report_failure(id, st, hdr);
780
0
        } else {
781
            // Report tablet load info only on ADD_SEGMENT to reduce frequency.
782
            // ADD_SEGMENT is sent once per segment, while APPEND_DATA is sent
783
            // for every data batch. This reduces unnecessary writes and avoids
784
            // potential stream write failures when the sender is closing.
785
0
            _report_tablet_load_info(id, hdr.index_id());
786
0
        }
787
0
    } break;
788
28
    case PStreamHeader::APPEND_DATA: {
789
28
        auto st = _append_data(hdr, data);
790
28
        if (!st.ok()) {
791
2
            _report_failure(id, st, hdr);
792
2
        }
793
28
    } break;
794
19
    case PStreamHeader::CLOSE_LOAD: {
795
19
        DBUG_EXECUTE_IF("LoadStream.close_load.block", DBUG_BLOCK);
796
19
        std::vector<int64_t> success_tablet_ids;
797
19
        FailedTablets failed_tablets;
798
19
        std::vector<PTabletID> tablets_to_commit(hdr.tablets().begin(), hdr.tablets().end());
799
        // Step 1: count this CLOSE_LOAD and, if this is the last one, commit. Under _lock.
800
19
        bool all_received =
801
19
                close(hdr.src_id(), tablets_to_commit, &success_tablet_ids, &failed_tablets);
802
        // Step 2: send THIS stream's EOS (network IO, must be outside _lock). A stream
803
        // must not be StreamClose'd before its own EOS is delivered, otherwise the
804
        // sender sees on_closed without EOS and reports "Stream closed without EOS".
805
19
        _report_result(id, Status::OK(), success_tablet_ids, failed_tablets, true);
806
19
        bool is_incremental =
807
19
                hdr.has_num_incremental_streams() && hdr.num_incremental_streams() > 0;
808
        // Test-only: delay every incremental stream except the one that made
809
        // all_received, so a non-last incremental stream parks after the last
810
        // stream drained the list. On the buggy code this orphans it and the
811
        // load hangs; on the fix the latch drains the late registration under
812
        // the same lock. Inert unless enable_debug_points=true.
813
19
        if (is_incremental && !all_received) {
814
2
            DBUG_EXECUTE_IF("LoadStream.close_load.delay_incremental_register",
815
2
                            { bthread_usleep(3000000); });
816
2
        }
817
        // Step 3: close this stream (non-incremental) or park it for deferred close
818
        // (incremental, fencing), then collect everything that is now safe to close.
819
        // Registration happens only after step 2, so a collected stream already had
820
        // its EOS delivered (fixes the close-before-EOS race); the all-received latch
821
        // inside makes any late thread drain the parked streams (fixes the leak race).
822
19
        auto streams_to_close = mark_eos_sent_and_collect(id, is_incremental);
823
19
        for (auto& closing_id : streams_to_close) {
824
19
            brpc::StreamClose(closing_id);
825
19
        }
826
19
    } break;
827
0
    case PStreamHeader::GET_SCHEMA: {
828
0
        _report_schema(id, hdr);
829
0
    } break;
830
0
    default:
831
0
        LOG(WARNING) << "unexpected stream message " << hdr.opcode() << ", " << *this;
832
0
        DCHECK(false);
833
47
    }
834
47
}
835
836
0
void LoadStream::on_idle_timeout(StreamId id) {
837
0
    LOG(WARNING) << "closing load stream on idle timeout, " << *this;
838
0
    brpc::StreamClose(id);
839
0
}
840
841
19
void LoadStream::on_closed(StreamId id) {
842
    // `this` may be freed by other threads after increasing `_close_rpc_cnt`,
843
    // format string first to prevent use-after-free
844
19
    std::stringstream ss;
845
19
    ss << *this;
846
19
    auto remaining_streams = _total_streams - _close_rpc_cnt.fetch_add(1) - 1;
847
19
    LOG(INFO) << "stream " << id << " on_closed, remaining streams = " << remaining_streams << ", "
848
19
              << ss.str();
849
19
    if (remaining_streams == 0) {
850
15
        _load_stream_mgr->clear_load(_load_id);
851
15
    }
852
19
}
853
854
122
inline std::ostream& operator<<(std::ostream& ostr, const LoadStream& load_stream) {
855
122
    ostr << "load_id=" << print_id(load_stream._load_id) << ", txn_id=" << load_stream._txn_id;
856
122
    return ostr;
857
122
}
858
859
} // namespace doris