Coverage Report

Created: 2026-06-17 05:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/spill/spill_file_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/spill/spill_file_writer.h"
19
20
#include "agent/be_exec_version_manager.h"
21
#include "common/config.h"
22
#include "common/status.h"
23
#include "exec/spill/spill_file.h"
24
#include "exec/spill/spill_file_manager.h"
25
#include "io/fs/local_file_system.h"
26
#include "io/fs/local_file_writer.h"
27
#include "runtime/exec_env.h"
28
#include "runtime/query_context.h"
29
#include "runtime/runtime_state.h"
30
#include "runtime/thread_context.h"
31
32
namespace doris {
33
34
SpillFileWriter::SpillFileWriter(const std::shared_ptr<SpillFile>& spill_file, RuntimeState* state,
35
                                 RuntimeProfile* profile, SpillDataDir* data_dir,
36
                                 const std::string& spill_dir)
37
300
        : _spill_file_wptr(spill_file),
38
300
          _data_dir(data_dir),
39
300
          _spill_dir(spill_dir),
40
300
          _max_part_size(config::spill_file_part_size_bytes),
41
300
          _resource_ctx(state->get_query_ctx()->resource_ctx()) {
42
    // Common counters
43
300
    RuntimeProfile* common_profile = profile->get_child("CommonCounters");
44
300
    DCHECK(common_profile != nullptr);
45
300
    _memory_used_counter = common_profile->get_counter("MemoryUsage");
46
47
    // Register this writer as the active writer for the SpillFile.
48
300
    spill_file->_active_writer = this;
49
50
    // Custom (spill-specific) counters
51
300
    RuntimeProfile* custom_profile = profile->get_child("CustomCounters");
52
300
    _write_file_timer = custom_profile->get_counter("SpillWriteFileTime");
53
300
    _serialize_timer = custom_profile->get_counter("SpillWriteSerializeBlockTime");
54
300
    _write_block_counter = custom_profile->get_counter("SpillWriteBlockCount");
55
300
    _write_block_bytes_counter = custom_profile->get_counter("SpillWriteBlockBytes");
56
300
    _write_file_total_size = custom_profile->get_counter("SpillWriteFileBytes");
57
300
    _write_file_current_size = custom_profile->get_counter("SpillWriteFileCurrentBytes");
58
300
    _write_rows_counter = custom_profile->get_counter("SpillWriteRows");
59
300
    _total_file_count = custom_profile->get_counter("SpillWriteFileTotalCount");
60
300
}
61
62
300
SpillFileWriter::~SpillFileWriter() {
63
300
    if (_closed) {
64
273
        return;
65
273
    }
66
27
    Status st = close();
67
27
    if (!st.ok()) {
68
15
        LOG(WARNING) << "SpillFileWriter::~SpillFileWriter() failed: " << st.to_string()
69
15
                     << ", spill_dir=" << _spill_dir;
70
15
    }
71
27
}
72
73
263
Status SpillFileWriter::_open_next_part() {
74
263
    _current_part_path = _spill_dir + "/" + std::to_string(_current_part_index);
75
    // Create the spill directory lazily on first part
76
263
    if (_current_part_index == 0) {
77
253
        RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(_spill_dir));
78
253
    }
79
263
    RETURN_IF_ERROR(io::global_local_filesystem()->create_file(_current_part_path, &_file_writer));
80
263
    COUNTER_UPDATE(_total_file_count, 1);
81
263
    return Status::OK();
82
263
}
83
84
309
Status SpillFileWriter::_close_current_part(const std::shared_ptr<SpillFile>& spill_file) {
85
309
    if (!_file_writer) {
86
46
        return Status::OK();
87
46
    }
88
89
    // Write footer: block offsets + max_sub_block_size + block_count
90
263
    _part_meta.append((const char*)&_part_max_sub_block_size, sizeof(_part_max_sub_block_size));
91
263
    _part_meta.append((const char*)&_part_written_blocks, sizeof(_part_written_blocks));
92
93
263
    {
94
263
        SCOPED_TIMER(_write_file_timer);
95
263
        RETURN_IF_ERROR(_file_writer->append(_part_meta));
96
263
    }
97
98
263
    int64_t meta_size = _part_meta.size();
99
263
    _part_written_bytes += meta_size;
100
263
    COUNTER_UPDATE(_write_file_total_size, meta_size);
101
263
    if (_resource_ctx) {
102
263
        _resource_ctx->io_context()->update_spill_write_bytes_to_local_storage(meta_size);
103
263
    }
104
263
    if (_write_file_current_size) {
105
179
        COUNTER_UPDATE(_write_file_current_size, meta_size);
106
179
    }
107
263
    _data_dir->update_spill_data_usage(meta_size);
108
263
    ExecEnv::GetInstance()->spill_file_mgr()->update_spill_write_bytes(meta_size);
109
    // Incrementally update SpillFile's accounting so gc() can always
110
    // decrement the correct amount, even if close() is never called.
111
263
    if (spill_file) {
112
248
        spill_file->update_written_bytes(meta_size);
113
248
    }
114
115
263
    RETURN_IF_ERROR(_file_writer->close());
116
248
    _file_writer.reset();
117
118
    // Advance to next part
119
248
    ++_current_part_index;
120
248
    if (spill_file) {
121
248
        spill_file->increment_part_count();
122
248
    }
123
248
    _part_written_blocks = 0;
124
248
    _part_written_bytes = 0;
125
248
    _part_max_sub_block_size = 0;
126
248
    _part_meta.clear();
127
128
248
    return Status::OK();
129
263
}
130
131
471
Status SpillFileWriter::_rotate_if_needed(const std::shared_ptr<SpillFile>& spill_file) {
132
471
    if (_file_writer && _part_written_bytes >= _max_part_size) {
133
10
        RETURN_IF_ERROR(_close_current_part(spill_file));
134
10
    }
135
471
    return Status::OK();
136
471
}
137
138
474
Status SpillFileWriter::write_block(RuntimeState* state, const Block& block) {
139
474
    DCHECK(!_closed);
140
141
    // Lock the SpillFile to ensure it is still alive. If it has already been
142
    // destroyed (gc'd), we must not write any more data because the disk
143
    // accounting would be out of sync.
144
474
    auto spill_file = _spill_file_wptr.lock();
145
474
    if (!spill_file) {
146
0
        return Status::Error<INTERNAL_ERROR>(
147
0
                "SpillFile has been destroyed, cannot write more data, spill_dir={}", _spill_dir);
148
0
    }
149
150
    // Lazily open the first part
151
474
    if (!_file_writer) {
152
263
        RETURN_IF_ERROR(_open_next_part());
153
263
    }
154
155
474
    DBUG_EXECUTE_IF("fault_inject::spill_file::spill_block", {
156
474
        return Status::Error<INTERNAL_ERROR>("fault_inject spill_file spill_block failed");
157
474
    });
158
159
471
    auto rows = block.rows();
160
471
    COUNTER_UPDATE(_write_rows_counter, rows);
161
471
    COUNTER_UPDATE(_write_block_bytes_counter, block.bytes());
162
163
471
    RETURN_IF_ERROR(_write_internal(block, spill_file));
164
165
    // Auto-rotate if current part is full
166
471
    return _rotate_if_needed(spill_file);
167
471
}
168
169
318
Status SpillFileWriter::close() {
170
318
    if (_closed) {
171
18
        return Status::OK();
172
18
    }
173
300
    _closed = true;
174
175
300
    DBUG_EXECUTE_IF("fault_inject::spill_file::spill_eof", {
176
300
        return Status::Error<INTERNAL_ERROR>("fault_inject spill_file spill_eof failed");
177
300
    });
178
179
299
    auto spill_file = _spill_file_wptr.lock();
180
299
    RETURN_IF_ERROR(_close_current_part(spill_file));
181
182
284
    if (spill_file) {
183
284
        if (spill_file->_active_writer != this) {
184
0
            return Status::Error<INTERNAL_ERROR>(
185
0
                    "SpillFileWriter close() called but not registered as active writer, possible "
186
0
                    "double close or logic error");
187
0
        }
188
284
        spill_file->finish_writing();
189
284
    }
190
191
284
    return Status::OK();
192
284
}
193
194
Status SpillFileWriter::_write_internal(const Block& block,
195
471
                                        const std::shared_ptr<SpillFile>& spill_file) {
196
471
    size_t uncompressed_bytes = 0, compressed_bytes = 0;
197
198
471
    Status status;
199
471
    std::string buff;
200
471
    int64_t buff_size {0};
201
202
471
    if (block.rows() > 0) {
203
450
        {
204
450
            PBlock pblock;
205
450
            SCOPED_TIMER(_serialize_timer);
206
450
            int64_t compressed_time = 0;
207
450
            status = block.serialize(
208
450
                    BeExecVersionManager::get_newest_version(), &pblock, &uncompressed_bytes,
209
450
                    &compressed_bytes, &compressed_time,
210
450
                    segment_v2::CompressionTypePB::ZSTD); // ZSTD for better compression ratio
211
450
            RETURN_IF_ERROR(status);
212
450
            int64_t pblock_mem = pblock.ByteSizeLong();
213
450
            COUNTER_UPDATE(_memory_used_counter, pblock_mem);
214
450
            Defer defer {[&]() { COUNTER_UPDATE(_memory_used_counter, -pblock_mem); }};
215
450
            if (!pblock.SerializeToString(&buff)) {
216
0
                return Status::Error<ErrorCode::SERIALIZE_PROTOBUF_ERROR>(
217
0
                        "serialize spill data error. [path={}]", _current_part_path);
218
0
            }
219
450
            buff_size = buff.size();
220
450
            COUNTER_UPDATE(_memory_used_counter, buff_size);
221
450
            Defer defer2 {[&]() { COUNTER_UPDATE(_memory_used_counter, -buff_size); }};
222
450
        }
223
450
        if (_data_dir->reach_capacity_limit(buff_size)) {
224
0
            return Status::Error<ErrorCode::DISK_REACH_CAPACITY_LIMIT>(
225
0
                    "spill data total size exceed limit, path: {}, size limit: {}, spill data "
226
0
                    "size: {}",
227
0
                    _data_dir->path(),
228
0
                    PrettyPrinter::print_bytes(_data_dir->get_spill_data_limit()),
229
0
                    PrettyPrinter::print_bytes(_data_dir->get_spill_data_bytes()));
230
0
        }
231
232
450
        {
233
450
            Defer defer {[&]() {
234
450
                if (status.ok()) {
235
450
                    _data_dir->update_spill_data_usage(buff_size);
236
450
                    ExecEnv::GetInstance()->spill_file_mgr()->update_spill_write_bytes(buff_size);
237
238
450
                    _part_max_sub_block_size =
239
450
                            std::max(_part_max_sub_block_size, (size_t)buff_size);
240
241
450
                    _part_meta.append((const char*)&_part_written_bytes, sizeof(size_t));
242
450
                    COUNTER_UPDATE(_write_file_total_size, buff_size);
243
450
                    if (_resource_ctx) {
244
450
                        _resource_ctx->io_context()->update_spill_write_bytes_to_local_storage(
245
450
                                buff_size);
246
450
                    }
247
450
                    if (_write_file_current_size) {
248
314
                        COUNTER_UPDATE(_write_file_current_size, buff_size);
249
314
                    }
250
450
                    COUNTER_UPDATE(_write_block_counter, 1);
251
450
                    _part_written_bytes += buff_size;
252
450
                    ++_part_written_blocks;
253
                    // Incrementally update SpillFile so gc() can always
254
                    // decrement the correct amount from _data_dir.
255
450
                    spill_file->update_written_bytes(buff_size);
256
450
                }
257
450
            }};
258
450
            {
259
450
                SCOPED_TIMER(_write_file_timer);
260
450
                status = _file_writer->append(buff);
261
450
                RETURN_IF_ERROR(status);
262
450
            }
263
450
        }
264
450
    }
265
266
471
    return status;
267
471
}
268
269
} // namespace doris