Coverage Report

Created: 2026-09-12 20:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/index/index_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
// CLucene is third-party code and is not clean under -Wconversion (which
21
// -Wshorten-64-to-32 belongs to). Whether its first expansion lands inside
22
// someone else's suppressed region depends on include order, so suppress it
23
// deliberately here (same pattern as inverted_index_common_impl.h).
24
#ifdef __clang__
25
#pragma clang diagnostic push
26
#pragma clang diagnostic ignored "-Wconversion"
27
#endif
28
#include <CLucene.h> // IWYU pragma: keep
29
#include <CLucene/store/IndexInput.h>
30
#ifdef __clang__
31
#pragma clang diagnostic pop
32
#endif
33
#include <gen_cpp/olap_common.pb.h>
34
#include <gen_cpp/olap_file.pb.h>
35
36
#include <optional>
37
#include <string>
38
#include <utility>
39
#include <vector>
40
41
#include "common/be_mock_util.h"
42
#include "io/fs/file_system.h"
43
#include "io/fs/file_writer.h"
44
#include "io/fs/local_file_system.h"
45
#include "storage/index/index_storage_format.h"
46
#include "storage/index/inverted/inverted_index_common.h"
47
#include "storage/index/inverted/inverted_index_compound_reader.h"
48
#include "storage/index/inverted/inverted_index_searcher.h"
49
#include "storage/index/snii/format/format_constants.h"
50
#include "storage/index/snii/snii_doris_adapter.h"
51
#include "storage/index/snii/writer/snii_compound_writer.h"
52
53
namespace doris::snii::writer {
54
class MemoryReporter;
55
class SpimiTermBuffer;
56
class SniiCompoundWriter;
57
} // namespace doris::snii::writer
58
59
namespace doris {
60
class TabletIndex;
61
62
namespace segment_v2 {
63
class DorisFSDirectory;
64
namespace snii_doris {
65
class DorisSniiFileWriter;
66
} // namespace snii_doris
67
68
using InvertedIndexDirectoryMap =
69
        std::map<std::pair<int64_t, std::string>, std::shared_ptr<lucene::store::Directory>>;
70
71
class IndexFileWriter;
72
using IndexFileWriterPtr = std::unique_ptr<IndexFileWriter>;
73
74
class IndexFileWriter {
75
public:
76
    IndexFileWriter(io::FileSystemSPtr fs, std::string index_path_prefix, std::string rowset_id,
77
                    int64_t seg_id, InvertedIndexStorageFormatPB storage_format,
78
                    io::FileWriterPtr file_writer = nullptr, bool can_use_ram_dir = true,
79
                    int64_t tablet_id = -1);
80
731
    virtual ~IndexFileWriter() = default;
81
82
    MOCK_FUNCTION Result<std::shared_ptr<DorisFSDirectory>> open(const TabletIndex* index_meta);
83
    // The directory an ANN index is built into. Separate from open() because the
84
    // two formats stage ANN output in different places: V1/V2 hand faiss the same
85
    // CLucene filesystem directory every other index gets, while SNII hands it a
86
    // memory-backed staging directory whose bytes begin_close() seals into a blob
87
    // logical index. Callers only ever write through it, so the return type is
88
    // the lucene::store::Directory base -- widening open() itself would push that
89
    // base type onto the CLucene inverted writer and index_tool, which genuinely
90
    // need the DorisFSDirectory subclass.
91
    Result<std::shared_ptr<lucene::store::Directory>> open_ann_directory(
92
            const TabletIndex* index_meta);
93
    // SNII only: drops the staging directory of one ANN index whose serialization
94
    // failed. Its sub-files unlink themselves once their last owner is gone, and
95
    // the producer releases its own reference alongside this call -- without that
96
    // a failed save keeps an ANN-sized file and its descriptor on the temp
97
    // filesystem until this writer is destroyed, which for a rowset build is not
98
    // until every other segment has been written. V1/V2 keep their directory: its
99
    // files ARE the index output, and begin_close() is what removes them.
100
    void discard_ann_staging_directory(const TabletIndex* index_meta);
101
    // SNII only: drops the staging of EVERY index on this writer because the
102
    // segment they belong to is being abandoned. Layered above the per-index
103
    // discard, not a duplicate of it: that one fires the instant one ANN
104
    // serialization fails, while this one covers a segment that failed AFTER its
105
    // indexes staged successfully, when nothing else will ever seal them.
106
    void abandon_snii_staging();
107
    // Write-path facts for one SNII index flush.
108
    struct SniiAddIndexOptions {
109
        // This flush serves a stream/broker load (DataWriteType::TYPE_DIRECT):
110
        // the prx region compresses at snii_prx_zstd_level_direct_load;
111
        // compaction / schema change / ADD INDEX keep snii_prx_zstd_level.
112
        bool is_direct_load = false;
113
        // One byte of BM25 norms per document; empty for keyword or positionless indexes.
114
        // If nonempty, its size must equal doc_count, and postings retain frequencies for scoring.
115
        std::vector<uint8_t> encoded_norms;
116
    };
117
    Status add_snii_index(const TabletIndex* index_meta, uint32_t doc_count,
118
                          std::vector<uint32_t> null_docids,
119
                          doris::snii::writer::SpimiTermBuffer* const term_buffer,
120
                          doris::snii::format::IndexConfig index_config,
121
                          SniiAddIndexOptions options,
122
                          doris::snii::writer::MemoryReporter* const mem_reporter);
123
    // T2.2 compaction index merge fast path: begins a STREAMED SNII index
124
    // session on this compound. Unlike add_snii_index (which drains a SPIMI
125
    // term buffer), the caller pushes pre-merged, lexicographically sorted
126
    // terms through *session and seals the index with (*session)->finish().
127
    // Write parameters resolve through the SAME helper as add_snii_index
128
    // (zstd levels / dict block size), always at the COMPACTION
129
    // prx tier (a merge is never a direct load). CommonGrams T3 callers transfer
130
    // a precharged destination norm vector and a validated static metadata seed;
131
    // the streamed session late-binds semantic token_count before finish. Only ONE
132
    // session may be active per compound at a time, and begin_close() with an
133
    // unfinished session fails instead of sealing a half-fed container. The
134
    // handle is owned by this writer and valid until it is destroyed.
135
    Status add_snii_index_streamed(
136
            const TabletIndex* index_meta, uint32_t doc_count,
137
            doris::snii::writer::TrackedNullDocids null_docids,
138
            doris::snii::format::IndexConfig index_config,
139
            std::shared_ptr<doris::snii::writer::MemoryReporter> mem_reporter,
140
            doris::snii::writer::SniiStreamedIndexSession** session);
141
    // Sessions with write_norms=true must supply norms through set_encoded_norms before finish.
142
    // Compaction rebuilds them in the same pass that merges postings.
143
    Status add_snii_index_streamed(
144
            const TabletIndex* index_meta, uint32_t doc_count,
145
            doris::snii::writer::TrackedNullDocids null_docids, bool write_norms,
146
            doris::snii::format::IndexConfig index_config,
147
            std::shared_ptr<doris::snii::writer::MemoryReporter> mem_reporter,
148
            doris::snii::writer::SniiStreamedIndexSession** session);
149
    // Registers one opaque BLOB logical index (a numeric BKD, an ANN graph, ...)
150
    // on this SNII compound. Unlike add_snii_index it feeds the writer no terms:
151
    // the sub-file bytes are pulled through the BlobFileSource callbacks at
152
    // finish(), which is what lets the container -- not the producer -- decide
153
    // cold/hot placement. Registration writes no byte, so a rejected call leaves
154
    // the writer clean.
155
    Status add_snii_blob_index(const TabletIndex* index_meta,
156
                               doris::snii::format::LogicalIndexKind kind,
157
                               std::vector<doris::snii::writer::BlobFileSource> cold_files,
158
                               std::vector<doris::snii::writer::BlobFileSource> hot_files);
159
    void retain_snii_memory_reporter(
160
            std::unique_ptr<doris::snii::writer::MemoryReporter> mem_reporter);
161
    // SNII only, BUILD INDEX rewrite: copies the source container's valid
162
    // physical prefix and registers the inherited metadata groups so begin_close
163
    // re-emits them without decoding a posting. Must precede every
164
    // add_snii_index on this writer (the copied prefix owns the container
165
    // front).
166
    Status inherit_snii(const doris::snii::reader::SniiRewriteSnapshot& snapshot,
167
                        doris::snii::io::FileReader* source);
168
    Status delete_index(const TabletIndex* index_meta);
169
    Status initialize(InvertedIndexDirectoryMap& indices_dirs);
170
    Status add_into_searcher_cache();
171
    // Begin the close process. This mainly triggers the asynchronous close operation of
172
    // _idx_v2_writer by calling close(true), which starts the close process but returns
173
    // immediately without waiting for completion.
174
    Status begin_close();
175
    // Finish the close process. This waits for the close operation to complete by calling
176
    // _idx_v2_writer->close(false), which blocks until the close is fully done.
177
    Status finish_close();
178
318
    const InvertedIndexFileInfo* get_index_file_info() const {
179
318
        DCHECK(_closed) << debug_string();
180
318
        return &_file_info;
181
318
    }
182
442
    int64_t get_index_file_total_size() const {
183
442
        DCHECK(_closed) << debug_string();
184
442
        return _total_file_size;
185
442
    }
186
0
    const io::FileSystemSPtr& get_fs() const { return _fs; }
187
7.55k
    InvertedIndexStorageFormatPB get_storage_format() const { return _storage_format; }
188
385
    void set_file_writer_opts(const io::FileWriterOptions& opts) { _opts = opts; }
189
    std::vector<std::string> get_index_file_names() const;
190
    std::string debug_string() const;
191
192
    // Get internal file writer (for merge file index collection)
193
0
    io::FileWriter* get_file_writer() const { return _idx_v2_writer.get(); }
194
195
private:
196
    Status _insert_directory_into_map(int64_t index_id, const std::string& index_suffix,
197
                                      std::shared_ptr<lucene::store::Directory> dir);
198
    // SNII only: registers a memory-backed staging directory for one ANN index,
199
    // together with the metadata begin_close() needs to seal it.
200
    Result<std::shared_ptr<lucene::store::Directory>> _open_snii_ann_staging_directory(
201
            const TabletIndex* index_meta);
202
    virtual Result<std::unique_ptr<IndexSearcherBuilder>> _construct_index_searcher_builder(
203
            const DorisCompoundReader* dir);
204
    // SNII only: turns every ANN staging directory into a blob logical index in
205
    // the container. Runs once, from begin_close(), before the compound writer is
206
    // sealed. Registration copies no byte -- the staged buffers are pulled by
207
    // finish() through the blob sources.
208
    Status _seal_snii_blob_directories();
209
    // Drops the staging directories once the container owns their bytes, or once
210
    // sealing has failed and they are dead either way. Only the SNII path needs
211
    // this: the V1/V2 branch of begin_close() releases its own directories
212
    // inline.
213
    void _release_snii_blob_directories();
214
215
    // Member variables...
216
    InvertedIndexDirectoryMap _indices_dirs;
217
    // SNII only: the index metadata behind each entry of _indices_dirs. Owned a
218
    // copy rather than borrowed, because the harvest happens in begin_close(),
219
    // long after open() returned. Held by shared_ptr so this header keeps
220
    // TabletIndex incomplete -- it is included nearly everywhere.
221
    std::map<std::pair<int64_t, std::string>, std::shared_ptr<TabletIndex>> _snii_blob_dir_metas;
222
    const io::FileSystemSPtr _fs;
223
    std::string _index_path_prefix;
224
    std::string _rowset_id;
225
    int64_t _seg_id;
226
    InvertedIndexStorageFormatPB _storage_format;
227
    std::string _tmp_dir;
228
    const std::shared_ptr<io::LocalFileSystem>& _local_fs;
229
230
    // write to disk or stream
231
    io::FileWriterPtr _idx_v2_writer = nullptr;
232
    io::FileWriterOptions _opts;
233
234
    // v1: all file size
235
    // v2: file size
236
    int64_t _total_file_size = 0;
237
    InvertedIndexFileInfo _file_info;
238
239
    // only once
240
    bool _closed = false;
241
    bool _can_use_ram_dir = true;
242
243
    IndexStorageFormatPtr _index_storage_format;
244
    int64_t _tablet_id = -1;
245
    std::unique_ptr<snii_doris::DorisSniiFileWriter> _snii_file_writer;
246
    std::vector<std::shared_ptr<doris::snii::writer::MemoryReporter>> _snii_memory_reporters;
247
    std::unique_ptr<doris::snii::writer::SniiCompoundWriter> _snii_compound_writer;
248
    size_t _snii_index_count = 0;
249
250
    friend class IndexStorageFormatV1;
251
    friend class IndexStorageFormatV2;
252
    friend class IndexFileWriterTest;
253
};
254
255
} // namespace segment_v2
256
} // namespace doris