Coverage Report

Created: 2026-07-15 14:22

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
2.57k
inline std::string segment_mem_tracker_name(uint32_t segment_id) {
89
2.57k
    return "SegmentWriter:Segment-" + std::to_string(segment_id);
90
2.57k
}
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
2.57k
        : _segment_id(segment_id),
97
2.57k
          _tablet_schema(std::move(tablet_schema)),
98
2.57k
          _tablet(std::move(tablet)),
99
2.57k
          _data_dir(data_dir),
100
2.57k
          _opts(opts),
101
2.57k
          _file_writer(file_writer),
102
2.57k
          _index_file_writer(index_file_writer),
103
2.57k
          _mem_tracker(std::make_unique<MemTracker>(segment_mem_tracker_name(segment_id))),
104
2.57k
          _key_encoder(*_tablet_schema, _is_mow()),
105
2.57k
          _mow_context(std::move(opts.mow_ctx)) {
106
2.57k
    CHECK_NOTNULL(file_writer);
107
2.57k
    _num_short_key_columns = _tablet_schema->num_short_key_columns();
108
2.57k
}
109
110
2.57k
SegmentWriter::~SegmentWriter() {
111
2.57k
    _mem_tracker->release(_mem_tracker->consumption());
112
2.57k
}
113
114
void SegmentWriter::init_column_meta(ColumnMetaPB* meta, uint32_t column_id,
115
10.7k
                                     const TabletColumn& column, const ColumnWriterOptions& opts) {
116
10.7k
    meta->set_column_id(column_id);
117
10.7k
    meta->set_type(int(column.type()));
118
10.7k
    meta->set_length(column.length());
119
10.7k
    meta->set_encoding(EncodingInfo::resolve_default_encoding(opts.storage_format, column));
120
10.7k
    meta->set_compression(_opts.compression_type);
121
10.7k
    meta->set_is_nullable(column.is_nullable());
122
10.7k
    meta->set_default_value(column.default_value());
123
10.7k
    meta->set_precision(column.precision());
124
10.7k
    meta->set_frac(column.frac());
125
10.7k
    if (column.has_path_info()) {
126
446
        column.path_info_ptr()->to_protobuf(meta->mutable_column_path_info(),
127
446
                                            column.parent_unique_id());
128
446
    }
129
10.7k
    meta->set_unique_id(column.unique_id());
130
10.9k
    for (uint32_t i = 0; i < column.get_subtype_count(); ++i) {
131
165
        init_column_meta(meta->add_children_columns(), column_id, column.get_sub_column(i), opts);
132
165
    }
133
10.7k
    meta->set_result_is_nullable(column.get_result_is_nullable());
134
10.7k
    meta->set_function_name(column.get_aggregation_name());
135
10.7k
    meta->set_be_exec_version(column.get_be_exec_version());
136
10.7k
    if (column.is_variant_type()) {
137
391
        meta->set_variant_max_subcolumns_count(column.variant_max_subcolumns_count());
138
391
        meta->set_variant_enable_doc_mode(column.variant_enable_doc_mode());
139
391
    }
140
10.7k
}
141
142
1.35k
Status SegmentWriter::init() {
143
1.35k
    std::vector<uint32_t> column_ids;
144
1.35k
    auto column_cnt = cast_set<int>(_tablet_schema->num_columns());
145
8.44k
    for (uint32_t i = 0; i < column_cnt; ++i) {
146
7.08k
        column_ids.emplace_back(i);
147
7.08k
    }
148
1.35k
    return init(column_ids, true);
149
1.35k
}
150
151
Status SegmentWriter::_create_column_writer(uint32_t cid, const TabletColumn& column,
152
10.5k
                                            const TabletSchemaSPtr& schema) {
153
10.5k
    ColumnWriterOptions opts;
154
10.5k
    opts.meta = _footer.add_columns();
155
10.5k
    opts.storage_format = schema->storage_format();
156
157
10.5k
    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
10.5k
    opts.need_zone_map = column.is_key() || schema->keys_type() != KeysType::AGG_KEYS;
162
10.5k
    opts.need_bloom_filter = column.is_bf_column();
163
10.5k
    if (opts.need_bloom_filter) {
164
6
        opts.bf_options.fpp = schema->has_bf_fpp() ? schema->bloom_filter_fpp() : 0.05;
165
6
    }
166
10.5k
    auto* tablet_index = schema->get_ngram_bf_index(column.unique_id());
167
10.5k
    if (tablet_index) {
168
0
        opts.need_bloom_filter = true;
169
0
        opts.is_ngram_bf_index = true;
170
        //narrow convert from int32_t to uint8_t and uint16_t which is dangerous
171
0
        auto gram_size = tablet_index->get_gram_size();
172
0
        auto gram_bf_size = tablet_index->get_gram_bf_size();
173
0
        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
0
        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
0
        opts.gram_size = cast_set<uint8_t>(gram_size);
182
0
        opts.gram_bf_size = cast_set<uint16_t>(gram_bf_size);
183
0
    }
184
185
10.5k
    bool skip_inverted_index = false;
186
10.5k
    if (_opts.rowset_ctx != nullptr) {
187
        // skip write inverted index for index compaction column
188
8.36k
        skip_inverted_index =
189
8.36k
                _opts.rowset_ctx->columns_to_do_index_compaction.count(column.unique_id()) > 0;
190
8.36k
    }
191
    // skip write inverted index on load if skip_write_index_on_load is true
192
10.5k
    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
10.5k
    if (!skip_inverted_index) {
197
10.1k
        auto inverted_indexs = schema->inverted_indexs(column);
198
10.1k
        if (!inverted_indexs.empty()) {
199
2.21k
            opts.inverted_indexes = inverted_indexs;
200
2.21k
            opts.need_inverted_index = true;
201
2.21k
            DCHECK(_index_file_writer != nullptr);
202
2.21k
        }
203
10.1k
    }
204
    // indexes for this column
205
10.5k
    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
10.5k
    opts.index_file_writer = _index_file_writer;
212
213
10.5k
#define DISABLE_INDEX_IF_FIELD_TYPE(TYPE)                     \
214
95.3k
    if (column.type() == FieldType::OLAP_FIELD_TYPE_##TYPE) { \
215
421
        opts.need_zone_map = false;                           \
216
421
        opts.need_bloom_filter = false;                       \
217
421
    }
218
219
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(STRUCT)
220
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(ARRAY)
221
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(JSONB)
222
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(AGG_STATE)
223
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(MAP)
224
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(BITMAP)
225
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(HLL)
226
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(QUANTILE_STATE)
227
10.5k
    DISABLE_INDEX_IF_FIELD_TYPE(VARIANT)
228
229
10.5k
#undef DISABLE_INDEX_IF_FIELD_TYPE
230
231
10.5k
    int64_t storage_page_size = _tablet_schema->storage_page_size();
232
    // storage_page_size must be between 4KB and 10MB.
233
10.5k
    if (storage_page_size >= 4096 && storage_page_size <= 10485760) {
234
10.5k
        opts.data_page_size = storage_page_size;
235
10.5k
    }
236
10.5k
    opts.dict_page_size = _tablet_schema->storage_dict_page_size();
237
10.5k
    DBUG_EXECUTE_IF("VerticalSegmentWriter._create_column_writer.storage_page_size", {
238
10.5k
        auto table_id = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
239
10.5k
                "VerticalSegmentWriter._create_column_writer.storage_page_size", "table_id",
240
10.5k
                INT_MIN);
241
10.5k
        auto target_data_page_size = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
242
10.5k
                "VerticalSegmentWriter._create_column_writer.storage_page_size",
243
10.5k
                "storage_page_size", INT_MIN);
244
10.5k
        if (table_id == INT_MIN || target_data_page_size == INT_MIN) {
245
10.5k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
246
10.5k
                    "Debug point parameters missing: either 'table_id' or 'storage_page_size' not "
247
10.5k
                    "set.");
248
10.5k
        }
249
10.5k
        if (table_id == _tablet_schema->table_id() &&
250
10.5k
            opts.data_page_size != target_data_page_size) {
251
10.5k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
252
10.5k
                    "Mismatch in 'storage_page_size': expected size does not match the current "
253
10.5k
                    "data page size. "
254
10.5k
                    "Expected: " +
255
10.5k
                    std::to_string(target_data_page_size) +
256
10.5k
                    ", Actual: " + std::to_string(opts.data_page_size) + ".");
257
10.5k
        }
258
10.5k
    })
259
10.5k
    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
1
        auto page_size = _tablet_schema->row_store_page_size();
263
1
        opts.data_page_size =
264
1
                (page_size > 0) ? page_size : segment_v2::ROW_STORE_PAGE_SIZE_DEFAULT_VALUE;
265
1
    }
266
267
10.5k
    opts.rowset_ctx = _opts.rowset_ctx;
268
10.5k
    opts.file_writer = _file_writer;
269
10.5k
    opts.compression_type = _opts.compression_type;
270
10.5k
    opts.footer = &_footer;
271
10.5k
    if (_opts.rowset_ctx != nullptr) {
272
8.36k
        opts.input_rs_readers = _opts.rowset_ctx->input_rs_readers;
273
8.36k
    }
274
275
10.5k
    std::unique_ptr<ColumnWriter> writer;
276
10.5k
    RETURN_IF_ERROR(ColumnWriter::create(opts, &column, _file_writer, &writer));
277
10.5k
    RETURN_IF_ERROR(writer->init());
278
10.5k
    _column_writers.push_back(std::move(writer));
279
280
10.5k
    _olap_data_convertor->add_column_data_convertor(column);
281
10.5k
    return Status::OK();
282
10.5k
}
283
284
3.51k
Status SegmentWriter::init(const std::vector<uint32_t>& col_ids, bool has_key) {
285
3.51k
    DCHECK(_column_writers.empty());
286
3.51k
    DCHECK(_column_ids.empty());
287
3.51k
    _has_key = has_key;
288
3.51k
    _column_writers.reserve(_tablet_schema->columns().size());
289
3.51k
    _column_ids.insert(_column_ids.end(), col_ids.begin(), col_ids.end());
290
3.51k
    _olap_data_convertor = std::make_unique<OlapBlockDataConvertor>();
291
3.51k
    if (_opts.compression_type == UNKNOWN_COMPRESSION) {
292
2.56k
        _opts.compression_type = _tablet_schema->compression_type();
293
2.56k
    }
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
3.51k
    const int variant_stats_footer_offset = _footer.columns_size();
298
3.51k
    RETURN_IF_ERROR(_create_writers(_tablet_schema, col_ids));
299
300
    // Initialize variant statistics calculator
301
3.51k
    _variant_stats_calculator = std::make_unique<VariantStatsCaculator>(
302
3.51k
            &_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
3.51k
    if (_has_key) {
306
2.57k
        if (_is_mow()) {
307
73
            size_t seq_col_length = 0;
308
73
            if (_tablet_schema->has_sequence_col()) {
309
26
                seq_col_length =
310
26
                        _tablet_schema->column(_tablet_schema->sequence_col_idx()).length() + 1;
311
26
            }
312
73
            size_t rowid_length = 0;
313
73
            if (_is_mow_with_cluster_key()) {
314
0
                rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
315
0
                _short_key_index_builder.reset(
316
0
                        new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
317
0
            }
318
73
            _primary_key_index_builder.reset(
319
73
                    new PrimaryKeyIndexBuilder(_file_writer, seq_col_length, rowid_length));
320
73
            RETURN_IF_ERROR(_primary_key_index_builder->init());
321
2.49k
        } else {
322
2.49k
            _short_key_index_builder.reset(
323
2.49k
                    new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
324
2.49k
        }
325
2.57k
    }
326
3.51k
    return Status::OK();
327
3.51k
}
328
329
Status SegmentWriter::_create_writers(const TabletSchemaSPtr& tablet_schema,
330
3.51k
                                      const std::vector<uint32_t>& col_ids) {
331
3.51k
    _olap_data_convertor->reserve(col_ids.size());
332
10.5k
    for (auto& cid : col_ids) {
333
10.5k
        RETURN_IF_ERROR(_create_column_writer(cid, tablet_schema->column(cid), tablet_schema));
334
10.5k
    }
335
3.51k
    return Status::OK();
336
3.51k
}
337
338
800
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
800
    if (!config::disable_storage_row_cache && _tablet_schema->has_row_store_for_all_columns() &&
343
800
        _opts.write_type == DataWriteType::TYPE_DIRECT) {
344
        // invalidate cache
345
0
        RowCache::instance()->erase({_opts.rowset_ctx->tablet_id, key});
346
0
    }
347
800
}
348
349
97
void SegmentWriter::_serialize_block_to_row_column(Block& block) {
350
97
    if (block.rows() == 0) {
351
0
        return;
352
0
    }
353
97
    MonotonicStopWatch watch;
354
97
    watch.start();
355
97
    int row_column_id = 0;
356
294
    for (int i = 0; i < _tablet_schema->num_columns(); ++i) {
357
197
        if (_tablet_schema->column(i).is_row_store_column()) {
358
0
            auto row_store_column_ptr = block.get_by_position(i).column->clone_empty();
359
0
            auto* row_store_column = static_cast<ColumnString*>(row_store_column_ptr.get());
360
0
            DataTypeSerDeSPtrs serdes = create_data_type_serdes(block.get_data_types());
361
0
            JsonbSerializeUtil::block_to_jsonb(*_tablet_schema, block, *row_store_column,
362
0
                                               cast_set<int>(_tablet_schema->num_columns()), serdes,
363
0
                                               {_tablet_schema->row_columns_uids().begin(),
364
0
                                                _tablet_schema->row_columns_uids().end()});
365
0
            block.replace_by_position(i, std::move(row_store_column_ptr));
366
0
            break;
367
0
        }
368
197
    }
369
370
97
    VLOG_DEBUG << "serialize , num_rows:" << block.rows() << ", row_column_id:" << row_column_id
371
0
               << ", total_byte_size:" << block.allocated_bytes() << ", serialize_cost(us)"
372
0
               << watch.elapsed_time() / 1000;
373
97
}
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
4.07k
Status SegmentWriter::append_block(const Block* block, size_t row_pos, size_t num_rows) {
649
4.07k
    if (_opts.rowset_ctx->partial_update_info &&
650
4.07k
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
651
4.07k
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
652
4.07k
        !_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
4.07k
    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
4.07k
    CHECK(block->columns() >= _column_writers.size())
671
0
            << ", block->columns()=" << block->columns()
672
0
            << ", _column_writers.size()=" << _column_writers.size()
673
0
            << ", _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
4.07k
    if (_opts.write_type == DataWriteType::TYPE_DIRECT ||
677
4.07k
        _opts.write_type == DataWriteType::TYPE_SCHEMA_CHANGE) {
678
97
        _serialize_block_to_row_column(*const_cast<Block*>(block));
679
97
    }
680
681
4.07k
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
682
4.07k
        _tablet_schema->num_variant_columns() > 0) {
683
214
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
684
214
                const_cast<Block&>(*block), *_tablet_schema, _column_ids));
685
214
    }
686
687
4.07k
    _olap_data_convertor->set_source_content(block, row_pos, num_rows);
688
689
    // convert column data from engine format to storage layer format
690
4.07k
    std::vector<IOlapColumnDataAccessor*> key_columns;
691
4.07k
    IOlapColumnDataAccessor* seq_column = nullptr;
692
13.9k
    for (size_t id = 0; id < _column_writers.size(); ++id) {
693
        // olap data convertor alway start from id = 0
694
9.87k
        auto converted_result = _olap_data_convertor->convert_column_data(id);
695
9.87k
        if (!converted_result.first.ok()) {
696
0
            return converted_result.first;
697
0
        }
698
9.87k
        auto cid = _column_ids[id];
699
9.87k
        if (_has_key && cid < _tablet_schema->num_key_columns()) {
700
2.67k
            key_columns.push_back(converted_result.second);
701
7.20k
        } else if (_has_key && _tablet_schema->has_sequence_col() &&
702
7.20k
                   cid == _tablet_schema->sequence_col_idx()) {
703
90
            seq_column = converted_result.second;
704
90
        }
705
9.87k
        RETURN_IF_ERROR(_column_writers[id]->append(converted_result.second->get_nullmap(),
706
9.87k
                                                    converted_result.second->get_data(), num_rows));
707
9.87k
    }
708
4.07k
    if (_opts.write_type == DataWriteType::TYPE_COMPACTION) {
709
2.26k
        RETURN_IF_ERROR(
710
2.26k
                _variant_stats_calculator->calculate_variant_stats(block, row_pos, num_rows));
711
2.26k
    }
712
713
4.07k
    RETURN_IF_ERROR(build_key_index(key_columns, seq_column, num_rows));
714
715
4.07k
    _num_rows_written += num_rows;
716
4.07k
    _olap_data_convertor->clear_source_content();
717
4.07k
    return Status::OK();
718
4.07k
}
719
720
Status SegmentWriter::build_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
721
4.07k
                                      IOlapColumnDataAccessor* seq_column, size_t num_rows) {
722
4.07k
    if (!_has_key) {
723
1.00k
        return Status::OK();
724
1.00k
    }
725
726
    // find all row pos for short key indexes
727
3.07k
    std::vector<size_t> short_key_pos;
728
3.07k
    if (UNLIKELY(_short_key_row_pos == 0 && _num_rows_written == 0)) {
729
2.49k
        short_key_pos.push_back(0);
730
2.49k
    }
731
13.7k
    while (_short_key_row_pos + _opts.num_rows_per_block < _num_rows_written + num_rows) {
732
10.6k
        _short_key_row_pos += _opts.num_rows_per_block;
733
10.6k
        short_key_pos.push_back(_short_key_row_pos - _num_rows_written);
734
10.6k
    }
735
736
3.07k
    if (_is_mow_with_cluster_key()) {
737
        // For CLUSTER BY tables:
738
        // 1) generate primary key index (unique keys)
739
0
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, num_rows, true));
740
        // 2) generate short key index (cluster keys)
741
0
        key_columns.clear();
742
0
        for (const auto& cid : _tablet_schema->cluster_key_uids()) {
743
0
            auto cluster_key_index = _tablet_schema->field_index(cid);
744
0
            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
0
            bool found = false;
749
0
            for (auto i = 0; i < _column_ids.size(); ++i) {
750
0
                if (_column_ids[i] == cluster_key_index) {
751
0
                    auto converted_result = _olap_data_convertor->convert_column_data(i);
752
0
                    if (!converted_result.first.ok()) {
753
0
                        return converted_result.first;
754
0
                    }
755
0
                    key_columns.push_back(converted_result.second);
756
0
                    found = true;
757
0
                    break;
758
0
                }
759
0
            }
760
0
            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
0
        }
766
0
        return _generate_short_key_index(key_columns, num_rows, short_key_pos);
767
0
    }
768
3.07k
    if (_is_mow()) {
769
10
        return _generate_primary_key_index(key_columns, seq_column, num_rows, false);
770
10
    }
771
3.06k
    return _generate_short_key_index(key_columns, num_rows, short_key_pos);
772
3.07k
}
773
774
2.17k
int64_t SegmentWriter::max_row_to_add(size_t row_avg_size_in_bytes) {
775
2.17k
    auto segment_size = estimate_segment_size();
776
2.17k
    if (segment_size >= MAX_SEGMENT_SIZE || _num_rows_written >= _opts.max_rows_per_segment)
777
359
            [[unlikely]] {
778
359
        return 0;
779
359
    }
780
1.81k
    int64_t size_rows = ((int64_t)MAX_SEGMENT_SIZE - (int64_t)segment_size) / row_avg_size_in_bytes;
781
1.81k
    int64_t count_rows = (int64_t)_opts.max_rows_per_segment - _num_rows_written;
782
783
1.81k
    return std::min(size_rows, count_rows);
784
2.17k
}
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
2.58k
uint64_t SegmentWriter::estimate_segment_size() {
791
    // footer_size(4) + checksum(4) + segment_magic(4)
792
2.58k
    uint64_t size = 12;
793
10.0k
    for (auto& column_writer : _column_writers) {
794
10.0k
        size += column_writer->estimate_buffer_size();
795
10.0k
    }
796
2.58k
    if (_is_mow_with_cluster_key()) {
797
0
        size += _primary_key_index_builder->size() + _short_key_index_builder->size();
798
2.58k
    } else if (_is_mow()) {
799
0
        size += _primary_key_index_builder->size();
800
2.58k
    } else {
801
2.58k
        size += _short_key_index_builder->size();
802
2.58k
    }
803
804
    // update the mem_tracker of segment size
805
2.58k
    _mem_tracker->consume(size - _mem_tracker->consumption());
806
2.58k
    return size;
807
2.58k
}
808
809
3.51k
Status SegmentWriter::finalize_columns_data() {
810
3.51k
    if (_has_key) {
811
2.56k
        _row_count = _num_rows_written;
812
2.56k
    } else {
813
949
        DCHECK(_row_count == _num_rows_written)
814
0
                << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
815
949
        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
949
    }
822
3.51k
    _num_rows_written = 0;
823
824
10.5k
    for (auto& column_writer : _column_writers) {
825
10.5k
        RETURN_IF_ERROR(column_writer->finish());
826
10.5k
    }
827
3.51k
    RETURN_IF_ERROR(_write_data());
828
829
3.51k
    return Status::OK();
830
3.51k
}
831
832
3.51k
Status SegmentWriter::finalize_columns_index(uint64_t* index_size) {
833
3.51k
    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
3.51k
    RETURN_IF_ERROR(_write_ordinal_index());
839
3.51k
    RETURN_IF_ERROR(_write_zone_map());
840
3.51k
    RETURN_IF_ERROR(_write_inverted_index());
841
3.51k
    RETURN_IF_ERROR(_write_ann_index());
842
3.51k
    RETURN_IF_ERROR(_write_bloom_filter_index());
843
844
3.51k
    *index_size = _file_writer->bytes_appended() - index_start;
845
3.51k
    if (_has_key) {
846
2.56k
        if (_is_mow_with_cluster_key()) {
847
            // 1. sort primary keys
848
0
            std::sort(_primary_keys.begin(), _primary_keys.end());
849
            // 2. write primary keys index
850
0
            std::string last_key;
851
0
            for (const auto& key : _primary_keys) {
852
0
                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
0
                RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
856
0
                last_key = key;
857
0
            }
858
859
0
            RETURN_IF_ERROR(_write_short_key_index());
860
0
            *index_size = _file_writer->bytes_appended() - index_start;
861
0
            RETURN_IF_ERROR(_write_primary_key_index());
862
0
            *index_size += _primary_key_index_builder->disk_size();
863
2.56k
        } else if (_is_mow()) {
864
73
            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
73
            *index_size += _primary_key_index_builder->disk_size();
868
2.49k
        } else {
869
2.49k
            RETURN_IF_ERROR(_write_short_key_index());
870
2.49k
            *index_size = _file_writer->bytes_appended() - index_start;
871
2.49k
        }
872
2.56k
    }
873
3.51k
    uint64_t file_index_end = _file_writer->bytes_appended();
874
3.51k
    _index_file_cache_info.add_index_range(index_start, file_index_end - index_start);
875
    // reset all column writers and data_conveter
876
3.51k
    clear();
877
878
3.51k
    return Status::OK();
879
3.51k
}
880
881
Status SegmentWriter::finalize_footer(uint64_t* segment_file_size,
882
2.56k
                                      SegmentIndexFileCacheInfo* index_file_cache_info) {
883
2.56k
    uint64_t footer_start = _file_writer->bytes_appended();
884
2.56k
    RETURN_IF_ERROR(_write_footer());
885
    // finish
886
2.56k
    RETURN_IF_ERROR(_file_writer->close(true));
887
2.56k
    *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
2.56k
    _index_file_cache_info.segment_file_size = *segment_file_size;
891
2.56k
    _index_file_cache_info.add_index_range(footer_start, *segment_file_size - footer_start);
892
2.56k
    if (index_file_cache_info != nullptr) {
893
2.48k
        *index_file_cache_info = _index_file_cache_info;
894
2.48k
    }
895
2.56k
    if (*segment_file_size == 0) {
896
0
        return Status::Corruption("Bad segment, file size = 0");
897
0
    }
898
2.56k
    return Status::OK();
899
2.56k
}
900
901
Status SegmentWriter::finalize(uint64_t* segment_file_size, uint64_t* index_size,
902
1.35k
                               SegmentIndexFileCacheInfo* index_file_cache_info) {
903
1.35k
    MonotonicStopWatch timer;
904
1.35k
    timer.start();
905
    // check disk capacity
906
1.35k
    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
1.35k
    RETURN_IF_ERROR(finalize_columns_data());
912
    // write index
913
1.35k
    RETURN_IF_ERROR(finalize_columns_index(index_size));
914
    // write footer
915
1.35k
    RETURN_IF_ERROR(finalize_footer(segment_file_size, index_file_cache_info));
916
917
1.35k
    if (timer.elapsed_time() > 5000000000l) {
918
0
        LOG(INFO) << "segment flush consumes a lot time_ns " << timer.elapsed_time()
919
0
                  << ", segmemt_size " << *segment_file_size;
920
0
    }
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
1.35k
    if (auto* cache_builder = _file_writer->cache_builder(); cache_builder != nullptr &&
924
1.35k
                                                             cache_builder->_expiration_time == 0 &&
925
1.35k
                                                             config::is_cloud_mode()) {
926
0
        auto index_start = _index_file_cache_info.cache_start_offset();
927
0
        auto size = *index_size + *segment_file_size;
928
0
        auto holder = cache_builder->allocate_cache_holder(index_start, size, _tablet->tablet_id());
929
0
        for (auto& segment : holder->file_blocks) {
930
0
            static_cast<void>(segment->change_cache_type(io::FileCacheType::INDEX));
931
0
        }
932
0
    }
933
1.35k
    return Status::OK();
934
1.35k
}
935
936
3.54k
void SegmentWriter::clear() {
937
10.5k
    for (auto& column_writer : _column_writers) {
938
10.5k
        column_writer.reset();
939
10.5k
    }
940
3.54k
    _column_writers.clear();
941
3.54k
    _column_ids.clear();
942
3.54k
    _olap_data_convertor.reset();
943
3.54k
}
944
945
// write column data to file one by one
946
3.51k
Status SegmentWriter::_write_data() {
947
10.5k
    for (auto& column_writer : _column_writers) {
948
10.5k
        RETURN_IF_ERROR(column_writer->write_data());
949
950
10.5k
        auto* column_meta = column_writer->get_column_meta();
951
10.5k
        DCHECK(column_meta != nullptr);
952
10.5k
        column_meta->set_compressed_data_bytes(
953
10.5k
                (column_meta->has_compressed_data_bytes() ? column_meta->compressed_data_bytes()
954
10.5k
                                                          : 0) +
955
10.5k
                column_writer->get_total_compressed_data_pages_bytes());
956
10.5k
        column_meta->set_uncompressed_data_bytes(
957
10.5k
                (column_meta->has_uncompressed_data_bytes() ? column_meta->uncompressed_data_bytes()
958
10.5k
                                                            : 0) +
959
10.5k
                column_writer->get_total_uncompressed_data_pages_bytes());
960
10.5k
        column_meta->set_raw_data_bytes(
961
10.5k
                (column_meta->has_raw_data_bytes() ? column_meta->raw_data_bytes() : 0) +
962
10.5k
                column_writer->get_raw_data_bytes());
963
10.5k
    }
964
3.51k
    return Status::OK();
965
3.51k
}
966
967
// write ordinal index after data has been written
968
3.51k
Status SegmentWriter::_write_ordinal_index() {
969
10.5k
    for (auto& column_writer : _column_writers) {
970
10.5k
        RETURN_IF_ERROR(column_writer->write_ordinal_index());
971
10.5k
    }
972
3.51k
    return Status::OK();
973
3.51k
}
974
975
3.51k
Status SegmentWriter::_write_zone_map() {
976
10.5k
    for (auto& column_writer : _column_writers) {
977
10.5k
        RETURN_IF_ERROR(column_writer->write_zone_map());
978
10.5k
    }
979
3.51k
    return Status::OK();
980
3.51k
}
981
982
3.51k
Status SegmentWriter::_write_inverted_index() {
983
10.5k
    for (auto& column_writer : _column_writers) {
984
10.5k
        RETURN_IF_ERROR(column_writer->write_inverted_index());
985
10.5k
    }
986
3.51k
    return Status::OK();
987
3.51k
}
988
989
3.51k
Status SegmentWriter::_write_ann_index() {
990
10.5k
    for (auto& column_writer : _column_writers) {
991
10.5k
        RETURN_IF_ERROR(column_writer->write_ann_index());
992
10.5k
    }
993
3.51k
    return Status::OK();
994
3.51k
}
995
996
3.51k
Status SegmentWriter::_write_bloom_filter_index() {
997
10.5k
    for (auto& column_writer : _column_writers) {
998
10.5k
        RETURN_IF_ERROR(column_writer->write_bloom_filter_index());
999
10.5k
    }
1000
3.51k
    return Status::OK();
1001
3.51k
}
1002
1003
2.49k
Status SegmentWriter::_write_short_key_index() {
1004
2.49k
    std::vector<Slice> body;
1005
2.49k
    PageFooterPB footer;
1006
2.49k
    RETURN_IF_ERROR(_short_key_index_builder->finalize(_row_count, &body, &footer));
1007
2.49k
    PagePointer pp;
1008
    // short key index page is not compressed right now
1009
2.49k
    RETURN_IF_ERROR(PageIO::write_page(_file_writer, body, footer, &pp));
1010
2.49k
    pp.to_proto(_footer.mutable_short_key_index_page());
1011
2.49k
    return Status::OK();
1012
2.49k
}
1013
1014
73
Status SegmentWriter::_write_primary_key_index() {
1015
73
    CHECK_EQ(_primary_key_index_builder->num_rows(), _row_count);
1016
73
    return _primary_key_index_builder->finalize(_footer.mutable_primary_key_index_meta());
1017
73
}
1018
1019
2.56k
Status SegmentWriter::_write_footer() {
1020
2.56k
    _footer.set_num_rows(_row_count);
1021
    // Decide whether to externalize ColumnMetaPB by tablet default, and stamp footer version
1022
2.56k
    if (_tablet_schema->storage_format() == TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V3) {
1023
176
        _footer.set_version(SEGMENT_FOOTER_VERSION_V3_EXT_COL_META);
1024
176
        VLOG_DEBUG << "use external column meta";
1025
        // External ColumnMetaPB writing (optional)
1026
176
        RETURN_IF_ERROR(ExternalColMetaUtil::write_external_column_meta(
1027
176
                _file_writer, &_footer, _opts.compression_type,
1028
176
                [this](const std::vector<Slice>& slices) { return _write_raw_data(slices); }));
1029
176
    }
1030
1031
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
1032
2.56k
    std::string footer_buf;
1033
2.56k
    VLOG_DEBUG << "footer " << _footer.DebugString();
1034
2.56k
    if (!_footer.SerializeToString(&footer_buf)) {
1035
0
        return Status::InternalError("failed to serialize segment footer");
1036
0
    }
1037
1038
2.56k
    faststring fixed_buf;
1039
    // footer's size
1040
2.56k
    put_fixed32_le(&fixed_buf, cast_set<uint32_t>(footer_buf.size()));
1041
    // footer's checksum
1042
2.56k
    uint32_t checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
1043
2.56k
    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
2.56k
    fixed_buf.append(k_segment_magic, k_segment_magic_length);
1047
1048
2.56k
    std::vector<Slice> slices {footer_buf, fixed_buf};
1049
2.56k
    return _write_raw_data(slices);
1050
2.56k
}
1051
1052
4.63k
Status SegmentWriter::_write_raw_data(const std::vector<Slice>& slices) {
1053
4.63k
    RETURN_IF_ERROR(_file_writer->appendv(&slices[0], slices.size()));
1054
4.63k
    return Status::OK();
1055
4.63k
}
1056
1057
2.56k
Slice SegmentWriter::min_encoded_key() {
1058
2.56k
    return (_primary_key_index_builder == nullptr) ? Slice(_min_key.data(), _min_key.size())
1059
2.56k
                                                   : _primary_key_index_builder->min_key();
1060
2.56k
}
1061
2.56k
Slice SegmentWriter::max_encoded_key() {
1062
2.56k
    return (_primary_key_index_builder == nullptr) ? Slice(_max_key.data(), _max_key.size())
1063
2.56k
                                                   : _primary_key_index_builder->max_key();
1064
2.56k
}
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
3.06k
void SegmentWriter::set_min_key(const Slice& key) {
1078
3.06k
    if (UNLIKELY(_is_first_row)) {
1079
2.48k
        _min_key.append(key.get_data(), key.get_size());
1080
2.48k
        _is_first_row = false;
1081
2.48k
    }
1082
3.06k
}
1083
1084
3.06k
void SegmentWriter::set_max_key(const Slice& key) {
1085
3.06k
    _max_key.clear();
1086
3.06k
    _max_key.append(key.get_data(), key.get_size());
1087
3.06k
}
1088
1089
Status SegmentWriter::_generate_primary_key_index(
1090
        const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
1091
10
        IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort) {
1092
10
    if (!need_sort) { // mow table without cluster key
1093
10
        std::string last_key;
1094
810
        for (size_t pos = 0; pos < num_rows; pos++) {
1095
800
            std::string key = _key_encoder.full_encode(primary_key_columns, pos);
1096
800
            _maybe_invalid_row_cache(key);
1097
800
            if (_tablet_schema->has_sequence_col()) {
1098
0
                _key_encoder.append_seq_suffix(&key, seq_column, pos);
1099
0
            }
1100
800
            DCHECK(key.compare(last_key) > 0)
1101
0
                    << "found duplicate key or key is not sorted! current key: " << key
1102
0
                    << ", last key: " << last_key;
1103
800
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1104
800
            last_key = std::move(key);
1105
800
        }
1106
10
    } else { // mow table with cluster key
1107
        // generate primary keys in memory
1108
0
        for (uint32_t pos = 0; pos < num_rows; pos++) {
1109
0
            std::string key = _key_encoder.full_encode_primary_keys(primary_key_columns, pos);
1110
0
            _maybe_invalid_row_cache(key);
1111
0
            if (_tablet_schema->has_sequence_col()) {
1112
0
                _key_encoder.append_seq_suffix(&key, seq_column, pos);
1113
0
            }
1114
0
            _key_encoder.append_rowid_suffix(&key, pos + _num_rows_written);
1115
0
            _primary_keys_size += key.size();
1116
0
            _primary_keys.emplace_back(std::move(key));
1117
0
        }
1118
0
    }
1119
10
    return Status::OK();
1120
10
}
1121
1122
Status SegmentWriter::_generate_short_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
1123
                                                size_t num_rows,
1124
3.06k
                                                const std::vector<size_t>& short_key_pos) {
1125
3.06k
    set_min_key(_key_encoder.full_encode(key_columns, 0));
1126
3.06k
    set_max_key(_key_encoder.full_encode(key_columns, num_rows - 1));
1127
3.06k
    DCHECK(Slice(_max_key.data(), _max_key.size())
1128
0
                   .compare(Slice(_min_key.data(), _min_key.size())) >= 0)
1129
0
            << "key is not sorted! min key: " << _min_key << ", max key: " << _max_key;
1130
1131
3.06k
    key_columns.resize(_num_short_key_columns);
1132
3.06k
    std::string last_key;
1133
13.1k
    for (const auto pos : short_key_pos) {
1134
13.1k
        std::string key = _key_encoder.encode_short_keys(key_columns, pos);
1135
13.1k
        DCHECK(key.compare(last_key) >= 0)
1136
0
                << "key is not sorted! current key: " << key << ", last key: " << last_key;
1137
13.1k
        RETURN_IF_ERROR(_short_key_index_builder->add_item(key));
1138
13.1k
        last_key = std::move(key);
1139
13.1k
    }
1140
3.06k
    return Status::OK();
1141
3.06k
}
1142
1143
} // namespace segment_v2
1144
} // namespace doris