Coverage Report

Created: 2026-07-15 10:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/segment_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 "storage/segment/segment_writer.h"
19
20
#include <assert.h>
21
#include <gen_cpp/segment_v2.pb.h>
22
#include <parallel_hashmap/phmap.h>
23
24
#include <algorithm>
25
26
// IWYU pragma: no_include <opentelemetry/common/threadlocal.h>
27
#include <crc32c/crc32c.h>
28
29
#include "cloud/config.h"
30
#include "common/cast_set.h"
31
#include "common/compiler_util.h" // IWYU pragma: keep
32
#include "common/config.h"
33
#include "common/logging.h" // LOG
34
#include "common/status.h"
35
#include "core/block/block.h"
36
#include "core/block/column_with_type_and_name.h"
37
#include "core/column/column_nullable.h"
38
#include "core/data_type/primitive_type.h"
39
#include "core/field.h"
40
#include "core/types.h"
41
#include "core/value/vdatetime_value.h"
42
#include "exec/common/variant_util.h"
43
#include "io/cache/block_file_cache.h"
44
#include "io/cache/block_file_cache_factory.h"
45
#include "io/fs/file_system.h"
46
#include "io/fs/file_writer.h"
47
#include "io/fs/local_file_system.h"
48
#include "runtime/exec_env.h"
49
#include "runtime/memory/mem_tracker.h"
50
#include "service/point_query_executor.h"
51
#include "storage/data_dir.h"
52
#include "storage/index/index_file_writer.h"
53
#include "storage/index/index_writer.h"
54
#include "storage/index/inverted/inverted_index_fs_directory.h"
55
#include "storage/index/primary_key_index.h"
56
#include "storage/index/short_key_index.h"
57
#include "storage/iterator/olap_data_convertor.h"
58
#include "storage/key_coder.h"
59
#include "storage/olap_common.h"
60
#include "storage/olap_define.h"
61
#include "storage/partial_update_info.h"
62
#include "storage/rowset/rowset_writer_context.h" // RowsetWriterContext
63
#include "storage/rowset/segment_creator.h"
64
#include "storage/segment/column_writer.h" // ColumnWriter
65
#include "storage/segment/encoding_info.h"
66
#include "storage/segment/external_col_meta_util.h"
67
#include "storage/segment/historical_row_retriever.h"
68
#include "storage/segment/page_io.h"
69
#include "storage/segment/page_pointer.h"
70
#include "storage/segment/segment_loader.h"
71
#include "storage/segment/variant/variant_ext_meta_writer.h"
72
#include "storage/segment/variant_stats_calculator.h"
73
#include "storage/storage_engine.h"
74
#include "storage/tablet/tablet_schema.h"
75
#include "storage/utils.h"
76
#include "util/coding.h"
77
#include "util/faststring.h"
78
#include "util/jsonb/serialize.h"
79
#include "util/simd/bits.h"
80
namespace doris {
81
namespace segment_v2 {
82
83
using namespace ErrorCode;
84
85
const char* k_segment_magic = "D0R1";
86
const uint32_t k_segment_magic_length = 4;
87
88
14.8k
inline std::string segment_mem_tracker_name(uint32_t segment_id) {
89
14.8k
    return "SegmentWriter:Segment-" + std::to_string(segment_id);
90
14.8k
}
91
92
SegmentWriter::SegmentWriter(io::FileWriter* file_writer, uint32_t segment_id,
93
                             TabletSchemaSPtr tablet_schema, BaseTabletSPtr tablet,
94
                             DataDir* data_dir, const SegmentWriterOptions& opts,
95
                             IndexFileWriter* index_file_writer)
96
14.8k
        : _segment_id(segment_id),
97
14.8k
          _tablet_schema(std::move(tablet_schema)),
98
14.8k
          _tablet(std::move(tablet)),
99
14.8k
          _data_dir(data_dir),
100
14.8k
          _opts(opts),
101
14.8k
          _file_writer(file_writer),
102
14.8k
          _index_file_writer(index_file_writer),
103
14.8k
          _mem_tracker(std::make_unique<MemTracker>(segment_mem_tracker_name(segment_id))),
104
14.8k
          _key_encoder(*_tablet_schema, _is_mow()),
105
14.8k
          _mow_context(std::move(opts.mow_ctx)) {
106
14.8k
    CHECK_NOTNULL(file_writer);
107
14.8k
    _num_short_key_columns = _tablet_schema->num_short_key_columns();
108
14.8k
}
109
110
14.8k
SegmentWriter::~SegmentWriter() {
111
14.8k
    _mem_tracker->release(_mem_tracker->consumption());
112
14.8k
}
113
114
void SegmentWriter::init_column_meta(ColumnMetaPB* meta, uint32_t column_id,
115
126k
                                     const TabletColumn& column, const ColumnWriterOptions& opts) {
116
126k
    meta->set_column_id(column_id);
117
126k
    meta->set_type(int(column.type()));
118
126k
    meta->set_length(column.length());
119
126k
    meta->set_encoding(EncodingInfo::resolve_default_encoding(opts.storage_format, column));
120
126k
    meta->set_compression(_opts.compression_type);
121
126k
    meta->set_is_nullable(column.is_nullable());
122
126k
    meta->set_default_value(column.default_value());
123
126k
    meta->set_precision(column.precision());
124
126k
    meta->set_frac(column.frac());
125
126k
    if (column.has_path_info()) {
126
3.37k
        column.path_info_ptr()->to_protobuf(meta->mutable_column_path_info(),
127
3.37k
                                            column.parent_unique_id());
128
3.37k
    }
129
126k
    meta->set_unique_id(column.unique_id());
130
137k
    for (uint32_t i = 0; i < column.get_subtype_count(); ++i) {
131
11.1k
        init_column_meta(meta->add_children_columns(), column_id, column.get_sub_column(i), opts);
132
11.1k
    }
133
126k
    meta->set_result_is_nullable(column.get_result_is_nullable());
134
126k
    meta->set_function_name(column.get_aggregation_name());
135
126k
    meta->set_be_exec_version(column.get_be_exec_version());
136
126k
    if (column.is_variant_type()) {
137
1.56k
        meta->set_variant_max_subcolumns_count(column.variant_max_subcolumns_count());
138
1.56k
        meta->set_variant_enable_doc_mode(column.variant_enable_doc_mode());
139
1.56k
    }
140
126k
}
141
142
5.58k
Status SegmentWriter::init() {
143
5.58k
    std::vector<uint32_t> column_ids;
144
5.58k
    auto column_cnt = cast_set<int>(_tablet_schema->num_columns());
145
35.1k
    for (uint32_t i = 0; i < column_cnt; ++i) {
146
29.5k
        column_ids.emplace_back(i);
147
29.5k
    }
148
5.58k
    return init(column_ids, true);
149
5.58k
}
150
151
Status SegmentWriter::_create_column_writer(uint32_t cid, const TabletColumn& column,
152
115k
                                            const TabletSchemaSPtr& schema) {
153
115k
    ColumnWriterOptions opts;
154
115k
    opts.meta = _footer.add_columns();
155
115k
    opts.storage_format = schema->storage_format();
156
157
115k
    init_column_meta(opts.meta, cid, column, opts);
158
159
    // now we create zone map for key columns in AGG_KEYS or all column in UNIQUE_KEYS or DUP_KEYS
160
    // except for columns whose type don't support zone map.
161
115k
    opts.need_zone_map = column.is_key() || schema->keys_type() != KeysType::AGG_KEYS;
162
115k
    opts.need_bloom_filter = column.is_bf_column();
163
115k
    if (opts.need_bloom_filter) {
164
162
        opts.bf_options.fpp = schema->has_bf_fpp() ? schema->bloom_filter_fpp() : 0.05;
165
162
    }
166
115k
    auto* tablet_index = schema->get_ngram_bf_index(column.unique_id());
167
115k
    if (tablet_index) {
168
183
        opts.need_bloom_filter = true;
169
183
        opts.is_ngram_bf_index = true;
170
        //narrow convert from int32_t to uint8_t and uint16_t which is dangerous
171
183
        auto gram_size = tablet_index->get_gram_size();
172
183
        auto gram_bf_size = tablet_index->get_gram_bf_size();
173
183
        if (gram_size > 256 || gram_size < 1) {
174
0
            return Status::NotSupported("Do not support ngram bloom filter for ngram_size: ",
175
0
                                        gram_size);
176
0
        }
177
183
        if (gram_bf_size > 65535 || gram_bf_size < 64) {
178
0
            return Status::NotSupported("Do not support ngram bloom filter for bf_size: ",
179
0
                                        gram_bf_size);
180
0
        }
181
183
        opts.gram_size = cast_set<uint8_t>(gram_size);
182
183
        opts.gram_bf_size = cast_set<uint16_t>(gram_bf_size);
183
183
    }
184
185
115k
    bool skip_inverted_index = false;
186
115k
    if (_opts.rowset_ctx != nullptr) {
187
        // skip write inverted index for index compaction column
188
113k
        skip_inverted_index =
189
113k
                _opts.rowset_ctx->columns_to_do_index_compaction.count(column.unique_id()) > 0;
190
113k
    }
191
    // skip write inverted index on load if skip_write_index_on_load is true
192
115k
    if (_opts.write_type == DataWriteType::TYPE_DIRECT && schema->skip_write_index_on_load()) {
193
0
        skip_inverted_index = true;
194
0
    }
195
    // indexes for this column
196
115k
    if (!skip_inverted_index) {
197
114k
        auto inverted_indexs = schema->inverted_indexs(column);
198
114k
        if (!inverted_indexs.empty()) {
199
3.84k
            opts.inverted_indexes = inverted_indexs;
200
3.84k
            opts.need_inverted_index = true;
201
3.84k
            DCHECK(_index_file_writer != nullptr);
202
3.84k
        }
203
114k
    }
204
    // indexes for this column
205
115k
    if (const auto& index = schema->ann_index(column); index != nullptr) {
206
1
        opts.ann_index = index;
207
1
        opts.need_ann_index = true;
208
1
        DCHECK(_index_file_writer != nullptr);
209
1
    }
210
211
115k
    opts.index_file_writer = _index_file_writer;
212
213
115k
#define DISABLE_INDEX_IF_FIELD_TYPE(TYPE)                     \
214
1.03M
    if (column.type() == FieldType::OLAP_FIELD_TYPE_##TYPE) { \
215
6.64k
        opts.need_zone_map = false;                           \
216
6.64k
        opts.need_bloom_filter = false;                       \
217
6.64k
    }
218
219
115k
    DISABLE_INDEX_IF_FIELD_TYPE(STRUCT)
220
115k
    DISABLE_INDEX_IF_FIELD_TYPE(ARRAY)
221
115k
    DISABLE_INDEX_IF_FIELD_TYPE(JSONB)
222
115k
    DISABLE_INDEX_IF_FIELD_TYPE(AGG_STATE)
223
115k
    DISABLE_INDEX_IF_FIELD_TYPE(MAP)
224
115k
    DISABLE_INDEX_IF_FIELD_TYPE(BITMAP)
225
115k
    DISABLE_INDEX_IF_FIELD_TYPE(HLL)
226
115k
    DISABLE_INDEX_IF_FIELD_TYPE(QUANTILE_STATE)
227
115k
    DISABLE_INDEX_IF_FIELD_TYPE(VARIANT)
228
229
115k
#undef DISABLE_INDEX_IF_FIELD_TYPE
230
231
115k
    int64_t storage_page_size = _tablet_schema->storage_page_size();
232
    // storage_page_size must be between 4KB and 10MB.
233
115k
    if (storage_page_size >= 4096 && storage_page_size <= 10485760) {
234
115k
        opts.data_page_size = storage_page_size;
235
115k
    }
236
115k
    opts.dict_page_size = _tablet_schema->storage_dict_page_size();
237
115k
    DBUG_EXECUTE_IF("VerticalSegmentWriter._create_column_writer.storage_page_size", {
238
115k
        auto table_id = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
239
115k
                "VerticalSegmentWriter._create_column_writer.storage_page_size", "table_id",
240
115k
                INT_MIN);
241
115k
        auto target_data_page_size = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
242
115k
                "VerticalSegmentWriter._create_column_writer.storage_page_size",
243
115k
                "storage_page_size", INT_MIN);
244
115k
        if (table_id == INT_MIN || target_data_page_size == INT_MIN) {
245
115k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
246
115k
                    "Debug point parameters missing: either 'table_id' or 'storage_page_size' not "
247
115k
                    "set.");
248
115k
        }
249
115k
        if (table_id == _tablet_schema->table_id() &&
250
115k
            opts.data_page_size != target_data_page_size) {
251
115k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
252
115k
                    "Mismatch in 'storage_page_size': expected size does not match the current "
253
115k
                    "data page size. "
254
115k
                    "Expected: " +
255
115k
                    std::to_string(target_data_page_size) +
256
115k
                    ", Actual: " + std::to_string(opts.data_page_size) + ".");
257
115k
        }
258
115k
    })
259
115k
    if (column.is_row_store_column()) {
260
        // smaller page size for row store column; encoding is already set to PLAIN /
261
        // PLAIN_V2 by init_column_meta via resolve_default_encoding().
262
130
        auto page_size = _tablet_schema->row_store_page_size();
263
130
        opts.data_page_size =
264
130
                (page_size > 0) ? page_size : segment_v2::ROW_STORE_PAGE_SIZE_DEFAULT_VALUE;
265
130
    }
266
267
115k
    opts.rowset_ctx = _opts.rowset_ctx;
268
115k
    opts.file_writer = _file_writer;
269
115k
    opts.compression_type = _opts.compression_type;
270
115k
    opts.footer = &_footer;
271
115k
    if (_opts.rowset_ctx != nullptr) {
272
113k
        opts.input_rs_readers = _opts.rowset_ctx->input_rs_readers;
273
113k
    }
274
275
115k
    std::unique_ptr<ColumnWriter> writer;
276
115k
    RETURN_IF_ERROR(ColumnWriter::create(opts, &column, _file_writer, &writer));
277
115k
    RETURN_IF_ERROR(writer->init());
278
115k
    _column_writers.push_back(std::move(writer));
279
280
115k
    _olap_data_convertor->add_column_data_convertor(column);
281
115k
    return Status::OK();
282
115k
}
283
284
28.9k
Status SegmentWriter::init(const std::vector<uint32_t>& col_ids, bool has_key) {
285
28.9k
    DCHECK(_column_writers.empty());
286
28.9k
    DCHECK(_column_ids.empty());
287
28.9k
    _has_key = has_key;
288
28.9k
    _column_writers.reserve(_tablet_schema->columns().size());
289
28.9k
    _column_ids.insert(_column_ids.end(), col_ids.begin(), col_ids.end());
290
28.9k
    _olap_data_convertor = std::make_unique<OlapBlockDataConvertor>();
291
28.9k
    if (_opts.compression_type == UNKNOWN_COMPRESSION) {
292
14.8k
        _opts.compression_type = _tablet_schema->compression_type();
293
14.8k
    }
294
295
    // Vertical compaction calls init() multiple times against the same writer; the footer accumulates entries
296
    // across calls, so this init()'s slice of footer columns starts at the current size.
297
28.9k
    const int variant_stats_footer_offset = _footer.columns_size();
298
28.9k
    RETURN_IF_ERROR(_create_writers(_tablet_schema, col_ids));
299
300
    // Initialize variant statistics calculator
301
28.9k
    _variant_stats_calculator = std::make_unique<VariantStatsCaculator>(
302
28.9k
            &_footer, _tablet_schema, col_ids, variant_stats_footer_offset);
303
304
    // we don't need the short key index for unique key merge on write table.
305
28.9k
    if (_has_key) {
306
14.8k
        if (_is_mow()) {
307
5.84k
            size_t seq_col_length = 0;
308
5.84k
            if (_tablet_schema->has_sequence_col()) {
309
82
                seq_col_length =
310
82
                        _tablet_schema->column(_tablet_schema->sequence_col_idx()).length() + 1;
311
82
            }
312
5.84k
            size_t rowid_length = 0;
313
5.84k
            if (_is_mow_with_cluster_key()) {
314
157
                rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
315
157
                _short_key_index_builder.reset(
316
157
                        new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
317
157
            }
318
5.84k
            _primary_key_index_builder.reset(
319
5.84k
                    new PrimaryKeyIndexBuilder(_file_writer, seq_col_length, rowid_length));
320
5.84k
            RETURN_IF_ERROR(_primary_key_index_builder->init());
321
9.02k
        } else {
322
9.02k
            _short_key_index_builder.reset(
323
9.02k
                    new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
324
9.02k
        }
325
14.8k
    }
326
28.9k
    return Status::OK();
327
28.9k
}
328
329
Status SegmentWriter::_create_writers(const TabletSchemaSPtr& tablet_schema,
330
28.9k
                                      const std::vector<uint32_t>& col_ids) {
331
28.9k
    _olap_data_convertor->reserve(col_ids.size());
332
115k
    for (auto& cid : col_ids) {
333
115k
        RETURN_IF_ERROR(_create_column_writer(cid, tablet_schema->column(cid), tablet_schema));
334
115k
    }
335
28.9k
    return Status::OK();
336
28.9k
}
337
338
2.81M
void SegmentWriter::_maybe_invalid_row_cache(const std::string& key) {
339
    // Just invalid row cache for simplicity, since the rowset is not visible at present.
340
    // If we update/insert cache, if load failed rowset will not be visible but cached data
341
    // will be visible, and lead to inconsistency.
342
2.81M
    if (!config::disable_storage_row_cache && _tablet_schema->has_row_store_for_all_columns() &&
343
2.81M
        _opts.write_type == DataWriteType::TYPE_DIRECT) {
344
        // invalidate cache
345
0
        RowCache::instance()->erase({_opts.rowset_ctx->tablet_id, key});
346
0
    }
347
2.81M
}
348
349
5.17k
void SegmentWriter::_serialize_block_to_row_column(Block& block) {
350
5.17k
    if (block.rows() == 0) {
351
0
        return;
352
0
    }
353
5.17k
    MonotonicStopWatch watch;
354
5.17k
    watch.start();
355
5.17k
    int row_column_id = 0;
356
36.6k
    for (int i = 0; i < _tablet_schema->num_columns(); ++i) {
357
31.7k
        if (_tablet_schema->column(i).is_row_store_column()) {
358
272
            auto row_store_column_ptr = block.get_by_position(i).column->clone_empty();
359
272
            auto* row_store_column = static_cast<ColumnString*>(row_store_column_ptr.get());
360
272
            DataTypeSerDeSPtrs serdes = create_data_type_serdes(block.get_data_types());
361
272
            JsonbSerializeUtil::block_to_jsonb(*_tablet_schema, block, *row_store_column,
362
272
                                               cast_set<int>(_tablet_schema->num_columns()), serdes,
363
272
                                               {_tablet_schema->row_columns_uids().begin(),
364
272
                                                _tablet_schema->row_columns_uids().end()});
365
272
            block.replace_by_position(i, std::move(row_store_column_ptr));
366
272
            break;
367
272
        }
368
31.7k
    }
369
370
18.4E
    VLOG_DEBUG << "serialize , num_rows:" << block.rows() << ", row_column_id:" << row_column_id
371
18.4E
               << ", total_byte_size:" << block.allocated_bytes() << ", serialize_cost(us)"
372
18.4E
               << watch.elapsed_time() / 1000;
373
5.17k
}
374
375
Status SegmentWriter::probe_key_for_mow(
376
        std::string key, std::size_t segment_pos, bool have_input_seq_column, bool have_delete_sign,
377
        const std::vector<RowsetSharedPtr>& specified_rowsets,
378
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
379
        bool& has_default_or_nullable, std::vector<bool>& use_default_or_null_flag,
380
        const std::function<void(const RowLocation& loc)>& found_cb,
381
0
        const std::function<Status()>& not_found_cb, PartialUpdateStats& stats) {
382
0
    RowLocation loc;
383
    // save rowset shared ptr so this rowset wouldn't delete
384
0
    RowsetSharedPtr rowset;
385
0
    auto st = _tablet->lookup_row_key(
386
0
            key, _tablet_schema.get(), have_input_seq_column, specified_rowsets, &loc,
387
0
            cast_set<uint32_t>(_mow_context->max_version), segment_caches, &rowset);
388
0
    if (st.is<KEY_NOT_FOUND>()) {
389
0
        if (!have_delete_sign) {
390
0
            RETURN_IF_ERROR(not_found_cb());
391
0
        }
392
0
        ++stats.num_rows_new_added;
393
0
        has_default_or_nullable = true;
394
0
        use_default_or_null_flag.emplace_back(true);
395
0
        return Status::OK();
396
0
    }
397
0
    if (!st.ok() && !st.is<KEY_ALREADY_EXISTS>()) {
398
0
        LOG(WARNING) << "failed to lookup row key, error: " << st;
399
0
        return st;
400
0
    }
401
402
    // 1. if the delete sign is marked, it means that the value columns of the row will not
403
    //    be read. So we don't need to read the missing values from the previous rows.
404
    // 2. the one exception is when there are sequence columns in the table, we need to read
405
    //    the sequence columns, otherwise it may cause the merge-on-read based compaction
406
    //    policy to produce incorrect results
407
    // TODO(bobhan1): only read seq col rather than all columns in this situation for
408
    // partial update and flexible partial update
409
410
    // TODO(bobhan1): handle sequence column here
411
0
    if (st.is<KEY_ALREADY_EXISTS>() || (have_delete_sign && !_tablet_schema->has_sequence_col())) {
412
0
        has_default_or_nullable = true;
413
0
        use_default_or_null_flag.emplace_back(true);
414
0
    } else {
415
        // partial update should not contain invisible columns
416
0
        use_default_or_null_flag.emplace_back(false);
417
0
        _rsid_to_rowset.emplace(rowset->rowset_id(), rowset);
418
0
        found_cb(loc);
419
0
    }
420
421
0
    if (st.is<KEY_ALREADY_EXISTS>()) {
422
        // although we need to mark delete current row, we still need to read missing columns
423
        // for this row, we need to ensure that each column is aligned
424
0
        _mow_context->delete_bitmap->add(
425
0
                {_opts.rowset_ctx->rowset_id, _segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
426
0
                cast_set<uint32_t>(segment_pos));
427
0
        ++stats.num_rows_deleted;
428
0
    } else {
429
0
        _mow_context->delete_bitmap->add(
430
0
                {loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON}, loc.row_id);
431
0
        ++stats.num_rows_updated;
432
0
    }
433
0
    return Status::OK();
434
0
}
435
436
0
Status SegmentWriter::partial_update_preconditions_check(size_t row_pos) {
437
0
    if (!_is_mow()) {
438
0
        auto msg = fmt::format(
439
0
                "Can only do partial update on merge-on-write unique table, but found: "
440
0
                "keys_type={}, _opts.enable_unique_key_merge_on_write={}, tablet_id={}",
441
0
                _tablet_schema->keys_type(), _opts.enable_unique_key_merge_on_write,
442
0
                _tablet->tablet_id());
443
0
        DCHECK(false) << msg;
444
0
        return Status::InternalError<false>(msg);
445
0
    }
446
0
    if (_opts.rowset_ctx->partial_update_info == nullptr) {
447
0
        auto msg =
448
0
                fmt::format("partial_update_info should not be nullptr, please check, tablet_id={}",
449
0
                            _tablet->tablet_id());
450
0
        DCHECK(false) << msg;
451
0
        return Status::InternalError<false>(msg);
452
0
    }
453
0
    if (!_opts.rowset_ctx->partial_update_info->is_fixed_partial_update()) {
454
0
        auto msg = fmt::format(
455
0
                "in fixed partial update code, but update_mode={}, please check, tablet_id={}",
456
0
                _opts.rowset_ctx->partial_update_info->update_mode(), _tablet->tablet_id());
457
0
        DCHECK(false) << msg;
458
0
        return Status::InternalError<false>(msg);
459
0
    }
460
0
    if (row_pos != 0) {
461
0
        auto msg = fmt::format("row_pos should be 0, but found {}, tablet_id={}", row_pos,
462
0
                               _tablet->tablet_id());
463
0
        DCHECK(false) << msg;
464
0
        return Status::InternalError<false>(msg);
465
0
    }
466
0
    return Status::OK();
467
0
}
468
469
// for partial update, we should do following steps to fill content of block:
470
// 1. set block data to data convertor, and get all key_column's converted slice
471
// 2. get pk of input block, and read missing columns
472
//       2.1 first find key location{rowset_id, segment_id, row_id}
473
//       2.2 build read plan to read by batch
474
//       2.3 fill block
475
// 3. set columns to data convertor and then write all columns
476
Status SegmentWriter::append_block_with_partial_content(const Block* block, size_t row_pos,
477
0
                                                        size_t num_rows) {
478
0
    if (block->columns() < _tablet_schema->num_key_columns() ||
479
0
        block->columns() >= _tablet_schema->num_columns()) {
480
0
        return Status::InvalidArgument(
481
0
                fmt::format("illegal partial update block columns: {}, num key columns: {}, total "
482
0
                            "schema columns: {}",
483
0
                            block->columns(), _tablet_schema->num_key_columns(),
484
0
                            _tablet_schema->num_columns()));
485
0
    }
486
0
    RETURN_IF_ERROR(partial_update_preconditions_check(row_pos));
487
488
    // find missing column cids
489
0
    const auto& missing_cids = _opts.rowset_ctx->partial_update_info->missing_cids;
490
0
    const auto& including_cids = _opts.rowset_ctx->partial_update_info->update_cids;
491
492
    // create full block and fill with input columns
493
0
    auto full_block = _tablet_schema->create_block();
494
0
    size_t input_id = 0;
495
0
    for (auto i : including_cids) {
496
0
        full_block.replace_by_position(i, block->get_by_position(input_id++).column);
497
0
    }
498
499
0
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
500
0
        _tablet_schema->num_variant_columns() > 0) {
501
0
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
502
0
                full_block, *_tablet_schema, including_cids));
503
0
    }
504
0
    RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
505
0
            &full_block, row_pos, num_rows, including_cids));
506
507
0
    bool have_input_seq_column = false;
508
    // write including columns
509
0
    std::vector<IOlapColumnDataAccessor*> key_columns;
510
0
    IOlapColumnDataAccessor* seq_column = nullptr;
511
0
    size_t segment_start_pos = 0;
512
0
    for (auto cid : including_cids) {
513
        // here we get segment column row num before append data.
514
0
        segment_start_pos = _column_writers[cid]->get_next_rowid();
515
        // olap data convertor alway start from id = 0
516
0
        auto converted_result = _olap_data_convertor->convert_column_data(cid);
517
0
        if (!converted_result.first.ok()) {
518
0
            return converted_result.first;
519
0
        }
520
0
        if (cid < _key_encoder.num_sort_key_columns()) {
521
0
            key_columns.push_back(converted_result.second);
522
0
        } else if (_tablet_schema->has_sequence_col() &&
523
0
                   cid == _tablet_schema->sequence_col_idx()) {
524
0
            seq_column = converted_result.second;
525
0
            have_input_seq_column = true;
526
0
        }
527
0
        RETURN_IF_ERROR(_column_writers[cid]->append(converted_result.second->get_nullmap(),
528
0
                                                     converted_result.second->get_data(),
529
0
                                                     num_rows));
530
0
    }
531
532
0
    bool has_default_or_nullable = false;
533
0
    std::vector<bool> use_default_or_null_flag;
534
0
    use_default_or_null_flag.reserve(num_rows);
535
0
    const auto* delete_signs =
536
0
            BaseTablet::get_delete_sign_column_data(full_block, row_pos + num_rows);
537
538
0
    const std::vector<RowsetSharedPtr>& specified_rowsets = _mow_context->rowset_ptrs;
539
0
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
540
541
0
    FixedReadPlan read_plan;
542
543
    // locate rows in base data
544
0
    PartialUpdateStats stats;
545
546
0
    for (size_t block_pos = row_pos; block_pos < row_pos + num_rows; block_pos++) {
547
        // block   segment
548
        //   2   ->   0
549
        //   3   ->   1
550
        //   4   ->   2
551
        //   5   ->   3
552
        // here row_pos = 2, num_rows = 4.
553
0
        size_t delta_pos = block_pos - row_pos;
554
0
        size_t segment_pos = segment_start_pos + delta_pos;
555
0
        std::string key = _key_encoder.full_encode(key_columns, delta_pos);
556
0
        _maybe_invalid_row_cache(key);
557
0
        if (have_input_seq_column) {
558
0
            _key_encoder.append_seq_suffix(&key, seq_column, delta_pos);
559
0
        }
560
        // If the table have sequence column, and the include-cids don't contain the sequence
561
        // column, we need to update the primary key index builder at the end of this method.
562
        // At that time, we have a valid sequence column to encode the key with seq col.
563
0
        if (!_tablet_schema->has_sequence_col() || have_input_seq_column) {
564
0
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
565
0
        }
566
567
        // mark key with delete sign as deleted.
568
0
        bool have_delete_sign = (delete_signs != nullptr && delete_signs[block_pos] != 0);
569
570
0
        auto not_found_cb = [&]() {
571
0
            return _opts.rowset_ctx->partial_update_info->handle_new_key(
572
0
                    *_tablet_schema, [&]() -> std::string {
573
0
                        return block->dump_one_line(
574
0
                                block_pos, cast_set<int>(_key_encoder.num_sort_key_columns()));
575
0
                    });
576
0
        };
577
0
        auto update_read_plan = [&](const RowLocation& loc) {
578
0
            read_plan.prepare_to_read(loc, segment_pos);
579
0
        };
580
0
        RETURN_IF_ERROR(probe_key_for_mow(std::move(key), segment_pos, have_input_seq_column,
581
0
                                          have_delete_sign, specified_rowsets, segment_caches,
582
0
                                          has_default_or_nullable, use_default_or_null_flag,
583
0
                                          update_read_plan, not_found_cb, stats));
584
0
    }
585
0
    CHECK_EQ(use_default_or_null_flag.size(), num_rows);
586
587
0
    if (config::enable_merge_on_write_correctness_check) {
588
0
        _tablet->add_sentinel_mark_to_delete_bitmap(_mow_context->delete_bitmap.get(),
589
0
                                                    *_mow_context->rowset_ids);
590
0
    }
591
592
    // read to fill full block
593
0
    RETURN_IF_ERROR(read_plan.fill_missing_columns(
594
0
            _opts.rowset_ctx->make_historical_row_retriever_context(), _rsid_to_rowset,
595
0
            *_tablet_schema, full_block, use_default_or_null_flag, has_default_or_nullable,
596
0
            cast_set<uint32_t>(segment_start_pos), block));
597
598
0
    if (_tablet_schema->num_variant_columns() > 0) {
599
0
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
600
0
                full_block, *_tablet_schema, missing_cids));
601
0
    }
602
603
    // convert block to row store format
604
0
    _serialize_block_to_row_column(full_block);
605
606
    // convert missing columns and send to column writer
607
0
    RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
608
0
            &full_block, row_pos, num_rows, missing_cids));
609
0
    for (auto cid : missing_cids) {
610
0
        auto converted_result = _olap_data_convertor->convert_column_data(cid);
611
0
        if (!converted_result.first.ok()) {
612
0
            return converted_result.first;
613
0
        }
614
0
        if (_tablet_schema->has_sequence_col() && !have_input_seq_column &&
615
0
            cid == _tablet_schema->sequence_col_idx()) {
616
0
            DCHECK_EQ(seq_column, nullptr);
617
0
            seq_column = converted_result.second;
618
0
        }
619
0
        RETURN_IF_ERROR(_column_writers[cid]->append(converted_result.second->get_nullmap(),
620
0
                                                     converted_result.second->get_data(),
621
0
                                                     num_rows));
622
0
    }
623
0
    _num_rows_updated += stats.num_rows_updated;
624
0
    _num_rows_deleted += stats.num_rows_deleted;
625
0
    _num_rows_new_added += stats.num_rows_new_added;
626
0
    _num_rows_filtered += stats.num_rows_filtered;
627
0
    if (_tablet_schema->has_sequence_col() && !have_input_seq_column) {
628
0
        DCHECK_NE(seq_column, nullptr);
629
0
        if (_num_rows_written != row_pos ||
630
0
            _primary_key_index_builder->num_rows() != _num_rows_written) {
631
0
            return Status::InternalError(
632
0
                    "Correctness check failed, _num_rows_written: {}, row_pos: {}, primary key "
633
0
                    "index builder num rows: {}",
634
0
                    _num_rows_written, row_pos, _primary_key_index_builder->num_rows());
635
0
        }
636
0
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, num_rows, false));
637
0
    }
638
639
0
    _num_rows_written += num_rows;
640
0
    DCHECK_EQ(_primary_key_index_builder->num_rows(), _num_rows_written)
641
0
            << "primary key index builder num rows(" << _primary_key_index_builder->num_rows()
642
0
            << ") not equal to segment writer's num rows written(" << _num_rows_written << ")";
643
0
    _olap_data_convertor->clear_source_content();
644
645
0
    return Status::OK();
646
0
}
647
648
40.5k
Status SegmentWriter::append_block(const Block* block, size_t row_pos, size_t num_rows) {
649
40.5k
    if (_opts.rowset_ctx->partial_update_info &&
650
40.5k
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
651
40.5k
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
652
40.5k
        !_opts.rowset_ctx->is_transient_rowset_writer) {
653
0
        if (_opts.rowset_ctx->partial_update_info->is_fixed_partial_update()) {
654
0
            RETURN_IF_ERROR(append_block_with_partial_content(block, row_pos, num_rows));
655
0
        } else {
656
0
            return Status::NotSupported<false>(
657
0
                    "SegmentWriter doesn't support flexible partial update, please set "
658
0
                    "enable_vertical_segment_writer=true in be.conf on all BEs to use "
659
0
                    "VerticalSegmentWriter.");
660
0
        }
661
0
        return Status::OK();
662
0
    }
663
40.5k
    if (block->columns() < _column_writers.size()) {
664
0
        return Status::InternalError(
665
0
                "block->columns() < _column_writers.size(), block->columns()=" +
666
0
                std::to_string(block->columns()) +
667
0
                ", _column_writers.size()=" + std::to_string(_column_writers.size()) +
668
0
                ", _tablet_schema->dump_structure()=" + _tablet_schema->dump_structure());
669
0
    }
670
18.4E
    CHECK(block->columns() >= _column_writers.size())
671
18.4E
            << ", block->columns()=" << block->columns()
672
18.4E
            << ", _column_writers.size()=" << _column_writers.size()
673
18.4E
            << ", _tablet_schema->dump_structure()=" << _tablet_schema->dump_structure();
674
    // Row column should be filled here when it's a directly write from memtable
675
    // or it's schema change write(since column data type maybe changed, so we should reubild)
676
40.5k
    if (_opts.write_type == DataWriteType::TYPE_DIRECT ||
677
40.5k
        _opts.write_type == DataWriteType::TYPE_SCHEMA_CHANGE) {
678
5.17k
        _serialize_block_to_row_column(*const_cast<Block*>(block));
679
5.17k
    }
680
681
40.5k
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
682
40.5k
        _tablet_schema->num_variant_columns() > 0) {
683
287
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
684
287
                const_cast<Block&>(*block), *_tablet_schema, _column_ids));
685
287
    }
686
687
40.5k
    _olap_data_convertor->set_source_content(block, row_pos, num_rows);
688
689
    // convert column data from engine format to storage layer format
690
40.5k
    std::vector<IOlapColumnDataAccessor*> key_columns;
691
40.5k
    IOlapColumnDataAccessor* seq_column = nullptr;
692
206k
    for (size_t id = 0; id < _column_writers.size(); ++id) {
693
        // olap data convertor alway start from id = 0
694
166k
        auto converted_result = _olap_data_convertor->convert_column_data(id);
695
166k
        if (!converted_result.first.ok()) {
696
0
            return converted_result.first;
697
0
        }
698
166k
        auto cid = _column_ids[id];
699
166k
        if (_has_key && cid < _tablet_schema->num_key_columns()) {
700
45.8k
            key_columns.push_back(converted_result.second);
701
120k
        } else if (_has_key && _tablet_schema->has_sequence_col() &&
702
120k
                   cid == _tablet_schema->sequence_col_idx()) {
703
146
            seq_column = converted_result.second;
704
146
        }
705
166k
        RETURN_IF_ERROR(_column_writers[id]->append(converted_result.second->get_nullmap(),
706
166k
                                                    converted_result.second->get_data(), num_rows));
707
166k
    }
708
40.5k
    if (_opts.write_type == DataWriteType::TYPE_COMPACTION) {
709
33.7k
        RETURN_IF_ERROR(
710
33.7k
                _variant_stats_calculator->calculate_variant_stats(block, row_pos, num_rows));
711
33.7k
    }
712
713
40.5k
    RETURN_IF_ERROR(build_key_index(key_columns, seq_column, num_rows));
714
715
40.5k
    _num_rows_written += num_rows;
716
40.5k
    _olap_data_convertor->clear_source_content();
717
40.5k
    return Status::OK();
718
40.5k
}
719
720
Status SegmentWriter::build_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
721
40.6k
                                      IOlapColumnDataAccessor* seq_column, size_t num_rows) {
722
40.6k
    if (!_has_key) {
723
22.1k
        return Status::OK();
724
22.1k
    }
725
726
    // find all row pos for short key indexes
727
18.4k
    std::vector<size_t> short_key_pos;
728
18.4k
    if (UNLIKELY(_short_key_row_pos == 0 && _num_rows_written == 0)) {
729
14.7k
        short_key_pos.push_back(0);
730
14.7k
    }
731
40.2k
    while (_short_key_row_pos + _opts.num_rows_per_block < _num_rows_written + num_rows) {
732
21.8k
        _short_key_row_pos += _opts.num_rows_per_block;
733
21.8k
        short_key_pos.push_back(_short_key_row_pos - _num_rows_written);
734
21.8k
    }
735
736
18.4k
    if (_is_mow_with_cluster_key()) {
737
        // For CLUSTER BY tables:
738
        // 1) generate primary key index (unique keys)
739
249
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, num_rows, true));
740
        // 2) generate short key index (cluster keys)
741
249
        key_columns.clear();
742
1.49k
        for (const auto& cid : _tablet_schema->cluster_key_uids()) {
743
1.49k
            auto cluster_key_index = _tablet_schema->field_index(cid);
744
1.49k
            if (cluster_key_index == -1) {
745
0
                return Status::InternalError("could not find cluster key column with unique_id=" +
746
0
                                             std::to_string(cid) + " in tablet schema");
747
0
            }
748
1.49k
            bool found = false;
749
13.1k
            for (auto i = 0; i < _column_ids.size(); ++i) {
750
13.1k
                if (_column_ids[i] == cluster_key_index) {
751
1.49k
                    auto converted_result = _olap_data_convertor->convert_column_data(i);
752
1.49k
                    if (!converted_result.first.ok()) {
753
0
                        return converted_result.first;
754
0
                    }
755
1.49k
                    key_columns.push_back(converted_result.second);
756
1.49k
                    found = true;
757
1.49k
                    break;
758
1.49k
                }
759
13.1k
            }
760
1.49k
            if (!found) {
761
0
                return Status::InternalError(
762
0
                        "could not found cluster key column with unique_id=" + std::to_string(cid) +
763
0
                        ", tablet schema index=" + std::to_string(cluster_key_index));
764
0
            }
765
1.49k
        }
766
249
        return _generate_short_key_index(key_columns, num_rows, short_key_pos);
767
249
    }
768
18.1k
    if (_is_mow()) {
769
6.05k
        return _generate_primary_key_index(key_columns, seq_column, num_rows, false);
770
6.05k
    }
771
12.0k
    return _generate_short_key_index(key_columns, num_rows, short_key_pos);
772
18.1k
}
773
774
7.25k
int64_t SegmentWriter::max_row_to_add(size_t row_avg_size_in_bytes) {
775
7.25k
    auto segment_size = estimate_segment_size();
776
7.25k
    if (segment_size >= MAX_SEGMENT_SIZE || _num_rows_written >= _opts.max_rows_per_segment)
777
359
            [[unlikely]] {
778
359
        return 0;
779
359
    }
780
6.89k
    int64_t size_rows = ((int64_t)MAX_SEGMENT_SIZE - (int64_t)segment_size) / row_avg_size_in_bytes;
781
6.89k
    int64_t count_rows = (int64_t)_opts.max_rows_per_segment - _num_rows_written;
782
783
6.89k
    return std::min(size_rows, count_rows);
784
7.25k
}
785
786
// TODO(lingbin): Currently this function does not include the size of various indexes,
787
// We should make this more precise.
788
// NOTE: This function will be called when any row of data is added, so we need to
789
// make this function efficient.
790
7.66k
uint64_t SegmentWriter::estimate_segment_size() {
791
    // footer_size(4) + checksum(4) + segment_magic(4)
792
7.66k
    uint64_t size = 12;
793
41.6k
    for (auto& column_writer : _column_writers) {
794
41.6k
        size += column_writer->estimate_buffer_size();
795
41.6k
    }
796
7.66k
    if (_is_mow_with_cluster_key()) {
797
197
        size += _primary_key_index_builder->size() + _short_key_index_builder->size();
798
7.47k
    } else if (_is_mow()) {
799
443
        size += _primary_key_index_builder->size();
800
7.02k
    } else {
801
7.02k
        size += _short_key_index_builder->size();
802
7.02k
    }
803
804
    // update the mem_tracker of segment size
805
7.66k
    _mem_tracker->consume(size - _mem_tracker->consumption());
806
7.66k
    return size;
807
7.66k
}
808
809
28.9k
Status SegmentWriter::finalize_columns_data() {
810
28.9k
    if (_has_key) {
811
14.8k
        _row_count = _num_rows_written;
812
14.8k
    } else {
813
18.4E
        DCHECK(_row_count == _num_rows_written)
814
18.4E
                << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
815
14.0k
        if (_row_count != _num_rows_written) {
816
0
            std::stringstream ss;
817
0
            ss << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
818
0
            LOG(WARNING) << ss.str();
819
0
            return Status::InternalError(ss.str());
820
0
        }
821
14.0k
    }
822
28.9k
    _num_rows_written = 0;
823
824
115k
    for (auto& column_writer : _column_writers) {
825
115k
        RETURN_IF_ERROR(column_writer->finish());
826
115k
    }
827
28.9k
    RETURN_IF_ERROR(_write_data());
828
829
28.9k
    return Status::OK();
830
28.9k
}
831
832
28.9k
Status SegmentWriter::finalize_columns_index(uint64_t* index_size) {
833
28.9k
    uint64_t index_start = _file_writer->bytes_appended();
834
    // Record each index range separately. Vertical compaction writes column groups as
835
    // data+index pairs, so a single [first index, EOF) range would include later column data.
836
    // This SegmentWriter path is shared by cloud load, non-vertical compaction, schema change
837
    // final output, and vertical compaction via VerticalBetaRowsetWriter.
838
28.9k
    RETURN_IF_ERROR(_write_ordinal_index());
839
28.9k
    RETURN_IF_ERROR(_write_zone_map());
840
28.9k
    RETURN_IF_ERROR(_write_inverted_index());
841
28.9k
    RETURN_IF_ERROR(_write_ann_index());
842
28.9k
    RETURN_IF_ERROR(_write_bloom_filter_index());
843
844
28.9k
    *index_size = _file_writer->bytes_appended() - index_start;
845
28.9k
    if (_has_key) {
846
14.8k
        if (_is_mow_with_cluster_key()) {
847
            // 1. sort primary keys
848
157
            std::sort(_primary_keys.begin(), _primary_keys.end());
849
            // 2. write primary keys index
850
157
            std::string last_key;
851
425k
            for (const auto& key : _primary_keys) {
852
425k
                DCHECK(key.compare(last_key) > 0)
853
0
                        << "found duplicate key or key is not sorted! current key: " << key
854
0
                        << ", last key: " << last_key;
855
425k
                RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
856
425k
                last_key = key;
857
425k
            }
858
859
157
            RETURN_IF_ERROR(_write_short_key_index());
860
157
            *index_size = _file_writer->bytes_appended() - index_start;
861
157
            RETURN_IF_ERROR(_write_primary_key_index());
862
157
            *index_size += _primary_key_index_builder->disk_size();
863
14.7k
        } else if (_is_mow()) {
864
5.68k
            RETURN_IF_ERROR(_write_primary_key_index());
865
            // IndexedColumnWriter write data pages mixed with segment data, we should use
866
            // the stat from primary key index builder.
867
5.68k
            *index_size += _primary_key_index_builder->disk_size();
868
9.02k
        } else {
869
9.02k
            RETURN_IF_ERROR(_write_short_key_index());
870
9.02k
            *index_size = _file_writer->bytes_appended() - index_start;
871
9.02k
        }
872
14.8k
    }
873
28.9k
    uint64_t file_index_end = _file_writer->bytes_appended();
874
28.9k
    _index_file_cache_info.add_index_range(index_start, file_index_end - index_start);
875
    // reset all column writers and data_conveter
876
28.9k
    clear();
877
878
28.9k
    return Status::OK();
879
28.9k
}
880
881
Status SegmentWriter::finalize_footer(uint64_t* segment_file_size,
882
14.8k
                                      SegmentIndexFileCacheInfo* index_file_cache_info) {
883
14.8k
    uint64_t footer_start = _file_writer->bytes_appended();
884
14.8k
    RETURN_IF_ERROR(_write_footer());
885
    // finish
886
14.8k
    RETURN_IF_ERROR(_file_writer->close(true));
887
14.8k
    *segment_file_size = _file_writer->bytes_appended();
888
    // The closed size completes the preload range recorded above. Local temporary rowsets, such as
889
    // schema-change internal sorting output, are filtered by SegmentIndexFileCacheLoader.
890
14.8k
    _index_file_cache_info.segment_file_size = *segment_file_size;
891
14.8k
    _index_file_cache_info.add_index_range(footer_start, *segment_file_size - footer_start);
892
14.8k
    if (index_file_cache_info != nullptr) {
893
14.7k
        *index_file_cache_info = _index_file_cache_info;
894
14.7k
    }
895
14.8k
    if (*segment_file_size == 0) {
896
0
        return Status::Corruption("Bad segment, file size = 0");
897
0
    }
898
14.8k
    return Status::OK();
899
14.8k
}
900
901
Status SegmentWriter::finalize(uint64_t* segment_file_size, uint64_t* index_size,
902
5.58k
                               SegmentIndexFileCacheInfo* index_file_cache_info) {
903
5.58k
    MonotonicStopWatch timer;
904
5.58k
    timer.start();
905
    // check disk capacity
906
5.58k
    if (_data_dir != nullptr && _data_dir->reach_capacity_limit((int64_t)estimate_segment_size())) {
907
0
        return Status::Error<DISK_REACH_CAPACITY_LIMIT>("disk {} exceed capacity limit, path: {}",
908
0
                                                        _data_dir->path_hash(), _data_dir->path());
909
0
    }
910
    // write data
911
5.58k
    RETURN_IF_ERROR(finalize_columns_data());
912
    // write index
913
5.58k
    RETURN_IF_ERROR(finalize_columns_index(index_size));
914
    // write footer
915
5.58k
    RETURN_IF_ERROR(finalize_footer(segment_file_size, index_file_cache_info));
916
917
5.58k
    if (timer.elapsed_time() > 5000000000l) {
918
9
        LOG(INFO) << "segment flush consumes a lot time_ns " << timer.elapsed_time()
919
9
                  << ", segmemt_size " << *segment_file_size;
920
9
    }
921
    // When the cache type is not ttl(expiration time == 0), the data should be split into normal cache queue
922
    // and index cache queue
923
5.58k
    if (auto* cache_builder = _file_writer->cache_builder(); cache_builder != nullptr &&
924
5.58k
                                                             cache_builder->_expiration_time == 0 &&
925
5.58k
                                                             config::is_cloud_mode()) {
926
2.01k
        auto index_start = _index_file_cache_info.cache_start_offset();
927
2.01k
        auto size = *index_size + *segment_file_size;
928
2.01k
        auto holder = cache_builder->allocate_cache_holder(index_start, size, _tablet->tablet_id());
929
2.05k
        for (auto& segment : holder->file_blocks) {
930
2.05k
            static_cast<void>(segment->change_cache_type(io::FileCacheType::INDEX));
931
2.05k
        }
932
2.01k
    }
933
5.58k
    return Status::OK();
934
5.58k
}
935
936
28.9k
void SegmentWriter::clear() {
937
115k
    for (auto& column_writer : _column_writers) {
938
115k
        column_writer.reset();
939
115k
    }
940
28.9k
    _column_writers.clear();
941
28.9k
    _column_ids.clear();
942
28.9k
    _olap_data_convertor.reset();
943
28.9k
}
944
945
// write column data to file one by one
946
28.9k
Status SegmentWriter::_write_data() {
947
115k
    for (auto& column_writer : _column_writers) {
948
115k
        RETURN_IF_ERROR(column_writer->write_data());
949
950
115k
        auto* column_meta = column_writer->get_column_meta();
951
115k
        DCHECK(column_meta != nullptr);
952
115k
        column_meta->set_compressed_data_bytes(
953
115k
                (column_meta->has_compressed_data_bytes() ? column_meta->compressed_data_bytes()
954
115k
                                                          : 0) +
955
115k
                column_writer->get_total_compressed_data_pages_bytes());
956
115k
        column_meta->set_uncompressed_data_bytes(
957
115k
                (column_meta->has_uncompressed_data_bytes() ? column_meta->uncompressed_data_bytes()
958
115k
                                                            : 0) +
959
115k
                column_writer->get_total_uncompressed_data_pages_bytes());
960
115k
        column_meta->set_raw_data_bytes(
961
115k
                (column_meta->has_raw_data_bytes() ? column_meta->raw_data_bytes() : 0) +
962
115k
                column_writer->get_raw_data_bytes());
963
115k
    }
964
28.9k
    return Status::OK();
965
28.9k
}
966
967
// write ordinal index after data has been written
968
28.9k
Status SegmentWriter::_write_ordinal_index() {
969
115k
    for (auto& column_writer : _column_writers) {
970
115k
        RETURN_IF_ERROR(column_writer->write_ordinal_index());
971
115k
    }
972
28.9k
    return Status::OK();
973
28.9k
}
974
975
28.9k
Status SegmentWriter::_write_zone_map() {
976
115k
    for (auto& column_writer : _column_writers) {
977
115k
        RETURN_IF_ERROR(column_writer->write_zone_map());
978
115k
    }
979
28.9k
    return Status::OK();
980
28.9k
}
981
982
28.9k
Status SegmentWriter::_write_inverted_index() {
983
115k
    for (auto& column_writer : _column_writers) {
984
115k
        RETURN_IF_ERROR(column_writer->write_inverted_index());
985
115k
    }
986
28.9k
    return Status::OK();
987
28.9k
}
988
989
28.9k
Status SegmentWriter::_write_ann_index() {
990
115k
    for (auto& column_writer : _column_writers) {
991
115k
        RETURN_IF_ERROR(column_writer->write_ann_index());
992
115k
    }
993
28.9k
    return Status::OK();
994
28.9k
}
995
996
28.9k
Status SegmentWriter::_write_bloom_filter_index() {
997
115k
    for (auto& column_writer : _column_writers) {
998
115k
        RETURN_IF_ERROR(column_writer->write_bloom_filter_index());
999
115k
    }
1000
28.9k
    return Status::OK();
1001
28.9k
}
1002
1003
9.17k
Status SegmentWriter::_write_short_key_index() {
1004
9.17k
    std::vector<Slice> body;
1005
9.17k
    PageFooterPB footer;
1006
9.17k
    RETURN_IF_ERROR(_short_key_index_builder->finalize(_row_count, &body, &footer));
1007
9.17k
    PagePointer pp;
1008
    // short key index page is not compressed right now
1009
9.17k
    RETURN_IF_ERROR(PageIO::write_page(_file_writer, body, footer, &pp));
1010
9.17k
    pp.to_proto(_footer.mutable_short_key_index_page());
1011
9.17k
    return Status::OK();
1012
9.17k
}
1013
1014
5.84k
Status SegmentWriter::_write_primary_key_index() {
1015
5.84k
    CHECK_EQ(_primary_key_index_builder->num_rows(), _row_count);
1016
5.84k
    return _primary_key_index_builder->finalize(_footer.mutable_primary_key_index_meta());
1017
5.84k
}
1018
1019
14.8k
Status SegmentWriter::_write_footer() {
1020
14.8k
    _footer.set_num_rows(_row_count);
1021
    // Decide whether to externalize ColumnMetaPB by tablet default, and stamp footer version
1022
14.8k
    if (_tablet_schema->storage_format() == TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V3) {
1023
5.41k
        _footer.set_version(SEGMENT_FOOTER_VERSION_V3_EXT_COL_META);
1024
5.41k
        VLOG_DEBUG << "use external column meta";
1025
        // External ColumnMetaPB writing (optional)
1026
5.41k
        RETURN_IF_ERROR(ExternalColMetaUtil::write_external_column_meta(
1027
5.41k
                _file_writer, &_footer, _opts.compression_type,
1028
5.41k
                [this](const std::vector<Slice>& slices) { return _write_raw_data(slices); }));
1029
5.41k
    }
1030
1031
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
1032
14.8k
    std::string footer_buf;
1033
14.8k
    VLOG_DEBUG << "footer " << _footer.DebugString();
1034
14.8k
    if (!_footer.SerializeToString(&footer_buf)) {
1035
0
        return Status::InternalError("failed to serialize segment footer");
1036
0
    }
1037
1038
14.8k
    faststring fixed_buf;
1039
    // footer's size
1040
14.8k
    put_fixed32_le(&fixed_buf, cast_set<uint32_t>(footer_buf.size()));
1041
    // footer's checksum
1042
14.8k
    uint32_t checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
1043
14.8k
    put_fixed32_le(&fixed_buf, checksum);
1044
    // Append magic number. we don't write magic number in the header because
1045
    // that will need an extra seek when reading
1046
14.8k
    fixed_buf.append(k_segment_magic, k_segment_magic_length);
1047
1048
14.8k
    std::vector<Slice> slices {footer_buf, fixed_buf};
1049
14.8k
    return _write_raw_data(slices);
1050
14.8k
}
1051
1052
70.7k
Status SegmentWriter::_write_raw_data(const std::vector<Slice>& slices) {
1053
70.7k
    RETURN_IF_ERROR(_file_writer->appendv(&slices[0], slices.size()));
1054
70.7k
    return Status::OK();
1055
70.7k
}
1056
1057
14.8k
Slice SegmentWriter::min_encoded_key() {
1058
14.8k
    return (_primary_key_index_builder == nullptr) ? Slice(_min_key.data(), _min_key.size())
1059
14.8k
                                                   : _primary_key_index_builder->min_key();
1060
14.8k
}
1061
14.8k
Slice SegmentWriter::max_encoded_key() {
1062
14.8k
    return (_primary_key_index_builder == nullptr) ? Slice(_max_key.data(), _max_key.size())
1063
14.8k
                                                   : _primary_key_index_builder->max_key();
1064
14.8k
}
1065
1066
24.8k
void SegmentWriter::set_min_max_key(const Slice& key) {
1067
24.8k
    if (UNLIKELY(_is_first_row)) {
1068
11
        _min_key.append(key.get_data(), key.get_size());
1069
11
        _is_first_row = false;
1070
11
    }
1071
24.8k
    if (key.compare(_max_key) > 0) {
1072
24.8k
        _max_key.clear();
1073
24.8k
        _max_key.append(key.get_data(), key.get_size());
1074
24.8k
    }
1075
24.8k
}
1076
1077
12.3k
void SegmentWriter::set_min_key(const Slice& key) {
1078
12.3k
    if (UNLIKELY(_is_first_row)) {
1079
9.16k
        _min_key.append(key.get_data(), key.get_size());
1080
9.16k
        _is_first_row = false;
1081
9.16k
    }
1082
12.3k
}
1083
1084
12.3k
void SegmentWriter::set_max_key(const Slice& key) {
1085
12.3k
    _max_key.clear();
1086
12.3k
    _max_key.append(key.get_data(), key.get_size());
1087
12.3k
}
1088
1089
Status SegmentWriter::_generate_primary_key_index(
1090
        const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
1091
6.30k
        IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort) {
1092
6.30k
    if (!need_sort) { // mow table without cluster key
1093
6.06k
        std::string last_key;
1094
2.39M
        for (size_t pos = 0; pos < num_rows; pos++) {
1095
2.39M
            std::string key = _key_encoder.full_encode(primary_key_columns, pos);
1096
2.39M
            _maybe_invalid_row_cache(key);
1097
2.39M
            if (_tablet_schema->has_sequence_col()) {
1098
159
                _key_encoder.append_seq_suffix(&key, seq_column, pos);
1099
159
            }
1100
2.39M
            DCHECK(key.compare(last_key) > 0)
1101
168
                    << "found duplicate key or key is not sorted! current key: " << key
1102
168
                    << ", last key: " << last_key;
1103
2.39M
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1104
2.39M
            last_key = std::move(key);
1105
2.39M
        }
1106
6.06k
    } else { // mow table with cluster key
1107
        // generate primary keys in memory
1108
425k
        for (uint32_t pos = 0; pos < num_rows; pos++) {
1109
425k
            std::string key = _key_encoder.full_encode_primary_keys(primary_key_columns, pos);
1110
425k
            _maybe_invalid_row_cache(key);
1111
425k
            if (_tablet_schema->has_sequence_col()) {
1112
11
                _key_encoder.append_seq_suffix(&key, seq_column, pos);
1113
11
            }
1114
425k
            _key_encoder.append_rowid_suffix(&key, pos + _num_rows_written);
1115
425k
            _primary_keys_size += key.size();
1116
425k
            _primary_keys.emplace_back(std::move(key));
1117
425k
        }
1118
249
    }
1119
6.30k
    return Status::OK();
1120
6.30k
}
1121
1122
Status SegmentWriter::_generate_short_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
1123
                                                size_t num_rows,
1124
12.3k
                                                const std::vector<size_t>& short_key_pos) {
1125
12.3k
    set_min_key(_key_encoder.full_encode(key_columns, 0));
1126
12.3k
    set_max_key(_key_encoder.full_encode(key_columns, num_rows - 1));
1127
12.3k
    DCHECK(Slice(_max_key.data(), _max_key.size())
1128
1
                   .compare(Slice(_min_key.data(), _min_key.size())) >= 0)
1129
1
            << "key is not sorted! min key: " << _min_key << ", max key: " << _max_key;
1130
1131
12.3k
    key_columns.resize(_num_short_key_columns);
1132
12.3k
    std::string last_key;
1133
29.2k
    for (const auto pos : short_key_pos) {
1134
29.2k
        std::string key = _key_encoder.encode_short_keys(key_columns, pos);
1135
18.4E
        DCHECK(key.compare(last_key) >= 0)
1136
18.4E
                << "key is not sorted! current key: " << key << ", last key: " << last_key;
1137
29.2k
        RETURN_IF_ERROR(_short_key_index_builder->add_item(key));
1138
29.2k
        last_key = std::move(key);
1139
29.2k
    }
1140
12.3k
    return Status::OK();
1141
12.3k
}
1142
1143
} // namespace segment_v2
1144
} // namespace doris