Coverage Report

Created: 2026-10-26 20:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/exec/spill/spill_file_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
20
#include <atomic>
21
#include <memory>
22
#include <string>
23
24
#include "core/block/block.h"
25
#include "io/fs/file_system.h"
26
#include "io/fs/file_writer.h"
27
#include "runtime/runtime_profile.h"
28
#include "runtime/workload_management/resource_context.h"
29
namespace doris {
30
class RuntimeState;
31
32
class SpillDataDir;
33
class SpillFile;
34
35
/// SpillFileWriter writes blocks to a SpillFile, automatically managing
36
/// part-file rotation when a part exceeds the configured size threshold
37
/// (config::spill_file_part_size_bytes).
38
///
39
/// Usage:
40
///   SpillFileWriterSPtr writer;
41
///   RETURN_IF_ERROR(spill_file->create_writer(state, profile, writer));
42
///   RETURN_IF_ERROR(writer->write_block(state, block));
43
///   RETURN_IF_ERROR(writer->close());
44
///
45
/// Part rotation is fully internal. Each part file has its own footer with
46
/// block offset metadata. Parts are named 0, 1, 2, ... within the SpillFile's
47
/// directory. A part is closed synchronously when it is rotated out or when close() is called.
48
/// If the SpillFile is destroyed before the writer is closed, the unfinished part is discarded.
49
///
50
/// Files are created on the file system pinned in the SpillFile, which is either a local disk or
51
/// the object storage of a cloud storage vault. For object storage the writer additionally
52
/// pauses before every append while the S3 upload queue holds at least
53
/// spill_s3_max_inflight_upload_bytes of buffers, which slows down a spill that
54
/// produces faster than object storage takes it, and reports request statistics derived from
55
/// the closed part.
56
class SpillFileWriter {
57
public:
58
    SpillFileWriter(const std::shared_ptr<SpillFile>& spill_file, RuntimeState* state,
59
                    RuntimeProfile* profile, SpillDataDir* data_dir, io::FileSystemSPtr fs,
60
                    std::string spill_dir);
61
62
    ~SpillFileWriter();
63
64
    /// Write a block. Automatically opens the first part, splits large blocks,
65
    /// and rotates to a new part when the current one exceeds max_part_size.
66
    Status write_block(RuntimeState* state, const Block& block);
67
68
    /// Finalize: close the current part, record cumulative stats in SpillFile. After close(),
69
    /// no more writes are allowed. After a failed write_block() the file cannot be completed:
70
    /// close() drops the current part and returns that failure.
71
    Status close();
72
73
    /// Largest serialized record and source Block written to this file, across all parts.
74
    /// Analytic replay uses these values before opening its readers.
75
23
    size_t max_record_bytes() const { return _max_record_bytes; }
76
23
    size_t max_block_bytes() const { return _max_block_bytes; }
77
23
    size_t max_footer_bytes() const { return _max_footer_bytes; }
78
79
private:
80
    Status _close_impl(const std::shared_ptr<SpillFile>& spill_file);
81
82
    friend class SpillFile;
83
84
    Status _write_block(RuntimeState* state, const Block& block);
85
86
    /// Open the next part file (spill_dir/{_current_part_index}).
87
    Status _open_next_part(const std::shared_ptr<SpillFile>& spill_file);
88
89
    /// Close the current part: write the footer, close the file writer synchronously
90
    /// (draining in-flight uploads on failure), account its remote statistics, register
91
    /// the successful part with the SpillFile, and advance to the next part index.
92
    /// Statistics are accounted whether it succeeds or not.
93
    Status _close_current_part(const std::shared_ptr<SpillFile>& spill_file);
94
95
    /// Append to the current part. For object storage `data` is appended after
96
    /// _wait_for_upload_queue(). After a failed append the part is
97
    /// broken: every later append, the footer included, returns that failure without reaching
98
    /// the file writer (S3FileWriter must not be appended to after a failed append).
99
    Status _append_to_part(const Slice& data);
100
101
    /// Object storage only: refuse a cancelled query, and wait while the S3 upload queue holds
102
    /// at least spill_s3_max_inflight_upload_bytes of buffers. Buffers that are still being
103
    /// filled are not queued, so idle writers cannot block each other.
104
    Status _wait_for_upload_queue();
105
106
    /// Object storage only: account the upload time and, after a successful close(), the bytes
107
    /// of the whole part including its footer. Does not inspect S3 upload state.
108
    void _account_remote_part(bool closed);
109
110
    /// Reset the per-part state and move on to the next part index.
111
    void _advance_part();
112
113
    /// Called by SpillFile::gc() when the SpillFile goes away before this writer was closed
114
    /// (e.g. an error unwound the owner of the file first). Drops the current part without
115
    /// a footer and without publishing it, and unregisters from the SpillFile, so that nothing
116
    /// is charged to or written under a SpillFile that no longer exists.
117
    void _discard(SpillFile* spill_file);
118
119
    /// If current part size >= _max_part_size, close it.
120
    Status _rotate_if_needed(const std::shared_ptr<SpillFile>& spill_file);
121
122
    /// Serialize and write a single block to the current part.
123
    Status _write_internal(const Block& block, const std::shared_ptr<SpillFile>& spill_file);
124
125
    // ── Back-reference ──
126
    std::weak_ptr<SpillFile> _spill_file_wptr; // weak ref; use lock() in close()
127
128
    // ── Configuration ──
129
    SpillDataDir* _data_dir = nullptr;
130
    io::FileSystemSPtr _fs;
131
    std::string _spill_dir;
132
    int64_t _max_part_size;
133
134
    // ── Current part state (reset on rotation) ──
135
    size_t _current_part_index = 0;
136
    std::string _current_part_path;
137
    std::unique_ptr<doris::io::FileWriter> _file_writer;
138
    size_t _part_written_blocks = 0;
139
    int64_t _part_written_bytes = 0;
140
    size_t _part_max_sub_block_size = 0;
141
    std::string _part_meta;
142
    // Object storage only: time spent in append() and close() of the current part.
143
    int64_t _part_upload_ns = 0;
144
    // First failed append of the current part.
145
    Status _part_append_status;
146
147
    bool _closed = false;
148
    // First failed write_block(); every later write and close() returns it.
149
    Status _write_status;
150
    size_t _max_record_bytes = 0;
151
    size_t _max_block_bytes = 0;
152
    size_t _max_footer_bytes = 0;
153
154
    // ── Counters ──
155
    RuntimeProfile::Counter* _write_file_timer = nullptr;
156
    RuntimeProfile::Counter* _serialize_timer = nullptr;
157
    RuntimeProfile::Counter* _write_block_counter = nullptr;
158
    RuntimeProfile::Counter* _write_block_bytes_counter = nullptr;
159
    RuntimeProfile::Counter* _write_file_total_size = nullptr;
160
    RuntimeProfile::Counter* _write_file_current_size = nullptr;
161
    RuntimeProfile::Counter* _write_rows_counter = nullptr;
162
    RuntimeProfile::Counter* _memory_used_counter = nullptr;
163
    RuntimeProfile::Counter* _total_file_count = nullptr;
164
    // Remote only, may be null when the profile does not register them.
165
    RuntimeProfile::Counter* _remote_upload_bytes = nullptr;
166
    RuntimeProfile::Counter* _remote_upload_timer = nullptr;
167
    RuntimeProfile::Counter* _remote_upload_wait_timer = nullptr;
168
169
    std::shared_ptr<ResourceContext> _resource_ctx = nullptr;
170
};
171
using SpillFileWriterSPtr = std::shared_ptr<SpillFileWriter>;
172
} // namespace doris