Coverage Report

Created: 2026-04-13 08:21

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
299
        : _spill_file_wptr(spill_file),
38
299
          _data_dir(data_dir),
39
299
          _spill_dir(spill_dir),
40
299
          _max_part_size(config::spill_file_part_size_bytes),
41
299
          _resource_ctx(state->get_query_ctx()->resource_ctx()) {
42
    // Common counters
43
299
    RuntimeProfile* common_profile = profile->get_child("CommonCounters");
44
299
    DCHECK(common_profile != nullptr);
45
299
    _memory_used_counter = common_profile->get_counter("MemoryUsage");
46
47
    // Register this writer as the active writer for the SpillFile.
48
299
    spill_file->_active_writer = this;
49
50
    // Custom (spill-specific) counters
51
299
    RuntimeProfile* custom_profile = profile->get_child("CustomCounters");
52
299
    _write_file_timer = custom_profile->get_counter("SpillWriteFileTime");
53
299
    _serialize_timer = custom_profile->get_counter("SpillWriteSerializeBlockTime");
54
299
    _write_block_counter = custom_profile->get_counter("SpillWriteBlockCount");
55
299
    _write_block_bytes_counter = custom_profile->get_counter("SpillWriteBlockBytes");
56
299
    _write_file_total_size = custom_profile->get_counter("SpillWriteFileBytes");
57
299
    _write_file_current_size = custom_profile->get_counter("SpillWriteFileCurrentBytes");
58
299
    _write_rows_counter = custom_profile->get_counter("SpillWriteRows");
59
299
    _total_file_count = custom_profile->get_counter("SpillWriteFileTotalCount");
60
299
}
61
62
299
SpillFileWriter::~SpillFileWriter() {
63
299
    if (_closed) {
64
272
        return;
65
272
    }
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
308
Status SpillFileWriter::_close_current_part(const std::shared_ptr<SpillFile>& spill_file) {
85
308
    if (!_file_writer) {
86
45
        return Status::OK();
87
45
    }
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
    _total_written_bytes += meta_size;
101
263
    COUNTER_UPDATE(_write_file_total_size, meta_size);
102
263
    if (_resource_ctx) {
103
263
        _resource_ctx->io_context()->update_spill_write_bytes_to_local_storage(meta_size);
104
263
    }
105
263
    if (_write_file_current_size) {
106
179
        COUNTER_UPDATE(_write_file_current_size, meta_size);
107
179
    }
108
263
    _data_dir->update_spill_data_usage(meta_size);
109
263
    ExecEnv::GetInstance()->spill_file_mgr()->update_spill_write_bytes(meta_size);
110
    // Incrementally update SpillFile's accounting so gc() can always
111
    // decrement the correct amount, even if close() is never called.
112
263
    if (spill_file) {
113
248
        spill_file->update_written_bytes(meta_size);
114
248
    }
115
116
263
    RETURN_IF_ERROR(_file_writer->close());
117
248
    _file_writer.reset();
118
119
    // Advance to next part
120
248
    ++_current_part_index;
121
248
    ++_total_parts;
122
248
    if (spill_file) {
123
248
        spill_file->increment_part_count();
124
248
    }
125
248
    _part_written_blocks = 0;
126
248
    _part_written_bytes = 0;
127
248
    _part_max_sub_block_size = 0;
128
248
    _part_meta.clear();
129
130
248
    return Status::OK();
131
263
}
132
133
470
Status SpillFileWriter::_rotate_if_needed(const std::shared_ptr<SpillFile>& spill_file) {
134
470
    if (_file_writer && _part_written_bytes >= _max_part_size) {
135
10
        RETURN_IF_ERROR(_close_current_part(spill_file));
136
10
    }
137
470
    return Status::OK();
138
470
}
139
140
473
Status SpillFileWriter::write_block(RuntimeState* state, const Block& block) {
141
473
    DCHECK(!_closed);
142
143
    // Lock the SpillFile to ensure it is still alive. If it has already been
144
    // destroyed (gc'd), we must not write any more data because the disk
145
    // accounting would be out of sync.
146
473
    auto spill_file = _spill_file_wptr.lock();
147
473
    if (!spill_file) {
148
0
        return Status::Error<INTERNAL_ERROR>(
149
0
                "SpillFile has been destroyed, cannot write more data, spill_dir={}", _spill_dir);
150
0
    }
151
152
    // Lazily open the first part
153
473
    if (!_file_writer) {
154
263
        RETURN_IF_ERROR(_open_next_part());
155
263
    }
156
157
473
    DBUG_EXECUTE_IF("fault_inject::spill_file::spill_block", {
158
473
        return Status::Error<INTERNAL_ERROR>("fault_inject spill_file spill_block failed");
159
473
    });
160
161
470
    auto rows = block.rows();
162
470
    COUNTER_UPDATE(_write_rows_counter, rows);
163
470
    COUNTER_UPDATE(_write_block_bytes_counter, block.bytes());
164
165
470
    RETURN_IF_ERROR(_write_internal(block, spill_file));
166
167
    // Auto-rotate if current part is full
168
470
    return _rotate_if_needed(spill_file);
169
470
}
170
171
317
Status SpillFileWriter::close() {
172
317
    if (_closed) {
173
18
        return Status::OK();
174
18
    }
175
299
    _closed = true;
176
177
299
    DBUG_EXECUTE_IF("fault_inject::spill_file::spill_eof", {
178
299
        return Status::Error<INTERNAL_ERROR>("fault_inject spill_file spill_eof failed");
179
299
    });
180
181
298
    auto spill_file = _spill_file_wptr.lock();
182
298
    RETURN_IF_ERROR(_close_current_part(spill_file));
183
184
283
    if (spill_file) {
185
283
        if (spill_file->_active_writer != this) {
186
0
            return Status::Error<INTERNAL_ERROR>(
187
0
                    "SpillFileWriter close() called but not registered as active writer, possible "
188
0
                    "double close or logic error");
189
0
        }
190
283
        spill_file->finish_writing();
191
283
    }
192
193
283
    return Status::OK();
194
283
}
195
196
Status SpillFileWriter::_write_internal(const Block& block,
197
470
                                        const std::shared_ptr<SpillFile>& spill_file) {
198
470
    size_t uncompressed_bytes = 0, compressed_bytes = 0;
199
200
470
    Status status;
201
470
    std::string buff;
202
470
    int64_t buff_size {0};
203
204
470
    if (block.rows() > 0) {
205
449
        {
206
449
            PBlock pblock;
207
449
            SCOPED_TIMER(_serialize_timer);
208
449
            int64_t compressed_time = 0;
209
449
            status = block.serialize(
210
449
                    BeExecVersionManager::get_newest_version(), &pblock, &uncompressed_bytes,
211
449
                    &compressed_bytes, &compressed_time,
212
449
                    segment_v2::CompressionTypePB::ZSTD); // ZSTD for better compression ratio
213
449
            RETURN_IF_ERROR(status);
214
449
            int64_t pblock_mem = pblock.ByteSizeLong();
215
449
            COUNTER_UPDATE(_memory_used_counter, pblock_mem);
216
449
            Defer defer {[&]() { COUNTER_UPDATE(_memory_used_counter, -pblock_mem); }};
217
449
            if (!pblock.SerializeToString(&buff)) {
218
0
                return Status::Error<ErrorCode::SERIALIZE_PROTOBUF_ERROR>(
219
0
                        "serialize spill data error. [path={}]", _current_part_path);
220
0
            }
221
449
            buff_size = buff.size();
222
449
            COUNTER_UPDATE(_memory_used_counter, buff_size);
223
449
            Defer defer2 {[&]() { COUNTER_UPDATE(_memory_used_counter, -buff_size); }};
224
449
        }
225
449
        if (_data_dir->reach_capacity_limit(buff_size)) {
226
0
            return Status::Error<ErrorCode::DISK_REACH_CAPACITY_LIMIT>(
227
0
                    "spill data total size exceed limit, path: {}, size limit: {}, spill data "
228
0
                    "size: {}",
229
0
                    _data_dir->path(),
230
0
                    PrettyPrinter::print_bytes(_data_dir->get_spill_data_limit()),
231
0
                    PrettyPrinter::print_bytes(_data_dir->get_spill_data_bytes()));
232
0
        }
233
234
449
        {
235
449
            Defer defer {[&]() {
236
449
                if (status.ok()) {
237
449
                    _data_dir->update_spill_data_usage(buff_size);
238
449
                    ExecEnv::GetInstance()->spill_file_mgr()->update_spill_write_bytes(buff_size);
239
240
449
                    _part_max_sub_block_size =
241
449
                            std::max(_part_max_sub_block_size, (size_t)buff_size);
242
243
449
                    _part_meta.append((const char*)&_part_written_bytes, sizeof(size_t));
244
449
                    COUNTER_UPDATE(_write_file_total_size, buff_size);
245
449
                    if (_resource_ctx) {
246
449
                        _resource_ctx->io_context()->update_spill_write_bytes_to_local_storage(
247
449
                                buff_size);
248
449
                    }
249
449
                    if (_write_file_current_size) {
250
313
                        COUNTER_UPDATE(_write_file_current_size, buff_size);
251
313
                    }
252
449
                    COUNTER_UPDATE(_write_block_counter, 1);
253
449
                    _part_written_bytes += buff_size;
254
449
                    _total_written_bytes += buff_size;
255
449
                    ++_part_written_blocks;
256
                    // Incrementally update SpillFile so gc() can always
257
                    // decrement the correct amount from _data_dir.
258
449
                    spill_file->update_written_bytes(buff_size);
259
449
                }
260
449
            }};
261
449
            {
262
449
                SCOPED_TIMER(_write_file_timer);
263
449
                status = _file_writer->append(buff);
264
449
                RETURN_IF_ERROR(status);
265
449
            }
266
449
        }
267
449
    }
268
269
470
    return status;
270
470
}
271
272
} // namespace doris