Coverage Report

Created: 2026-08-06 22:56

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