Coverage Report

Created: 2026-08-06 14:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/vertical_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/vertical_segment_writer.h"
19
20
#include <crc32c/crc32c.h>
21
#include <gen_cpp/olap_file.pb.h>
22
#include <gen_cpp/segment_v2.pb.h>
23
#include <parallel_hashmap/phmap.h>
24
25
#include <algorithm>
26
#include <cassert>
27
#include <memory>
28
#include <ostream>
29
#include <string>
30
#include <unordered_map>
31
#include <unordered_set>
32
#include <utility>
33
34
#include "cloud/config.h"
35
#include "common/cast_set.h"
36
#include "common/compiler_util.h" // IWYU pragma: keep
37
#include "common/config.h"
38
#include "common/logging.h" // LOG
39
#include "common/status.h"
40
#include "core/assert_cast.h"
41
#include "core/block/block.h"
42
#include "core/block/column_with_type_and_name.h"
43
#include "core/column/column_nullable.h"
44
#include "core/column/column_string.h"
45
#include "core/column/column_vector.h"
46
#include "core/data_type/data_type.h"
47
#include "core/data_type/data_type_factory.hpp"
48
#include "core/data_type/data_type_number.h" // IWYU pragma: keep
49
#include "core/types.h"
50
#include "exec/common/variant_util.h"
51
#include "io/fs/file_writer.h"
52
#include "io/fs/local_file_system.h"
53
#include "runtime/exec_env.h"
54
#include "runtime/memory/mem_tracker.h"
55
#include "storage/data_dir.h"
56
#include "storage/index/index_file_writer.h"
57
#include "storage/index/inverted/inverted_index_desc.h"
58
#include "storage/index/inverted/inverted_index_fs_directory.h"
59
#include "storage/index/primary_key_index.h"
60
#include "storage/index/short_key_index.h"
61
#include "storage/iterator/olap_data_convertor.h"
62
#include "storage/key_coder.h"
63
#include "storage/mow/historical_row_fetcher.h"
64
#include "storage/mow/key_probe.h"
65
#include "storage/olap_common.h"
66
#include "storage/partial_update_info.h"
67
#include "storage/row_cursor.h" // RowCursor // IWYU pragma: keep
68
#include "storage/rowset/rowset_fwd.h"
69
#include "storage/rowset/rowset_writer_context.h" // RowsetWriterContext
70
#include "storage/rowset/segment_creator.h"
71
#include "storage/segment/column_writer.h" // ColumnWriter
72
#include "storage/segment/encoding_info.h"
73
#include "storage/segment/external_col_meta_util.h"
74
#include "storage/segment/historical_row_retriever.h"
75
#include "storage/segment/page_io.h"
76
#include "storage/segment/page_pointer.h"
77
#include "storage/segment/segment_loader.h"
78
#include "storage/segment/variant/variant_ext_meta_writer.h"
79
#include "storage/tablet/base_tablet.h"
80
#include "storage/tablet/tablet_schema.h"
81
#include "storage/utils.h"
82
#include "util/coding.h"
83
#include "util/debug_points.h"
84
#include "util/faststring.h"
85
#include "util/json/path_in_data.h"
86
#include "util/jsonb/serialize.h"
87
namespace doris::segment_v2 {
88
89
using namespace ErrorCode;
90
91
static constexpr const char* k_segment_magic = "D0R1";
92
static constexpr uint32_t k_segment_magic_length = 4;
93
94
139
inline std::string vertical_segment_writer_mem_tracker_name(uint32_t segment_id) {
95
139
    return "VerticalSegmentWriter:Segment-" + std::to_string(segment_id);
96
139
}
97
98
8
static ColumnBitmap* get_mutable_skip_bitmap_column(Block* block, size_t skip_bitmap_col_idx) {
99
8
    auto skip_bitmap_column =
100
8
            IColumn::mutate(std::move(block->get_by_position(skip_bitmap_col_idx).column));
101
8
    auto* skip_bitmap_column_ptr = assert_cast<ColumnBitmap*>(skip_bitmap_column.get());
102
8
    block->replace_by_position(skip_bitmap_col_idx, std::move(skip_bitmap_column));
103
8
    return skip_bitmap_column_ptr;
104
8
}
105
106
VerticalSegmentWriter::VerticalSegmentWriter(io::FileWriter* file_writer, uint32_t segment_id,
107
                                             TabletSchemaSPtr tablet_schema, BaseTabletSPtr tablet,
108
                                             DataDir* data_dir,
109
                                             const VerticalSegmentWriterOptions& opts,
110
                                             IndexFileWriter* index_file_writer)
111
139
        : _segment_id(segment_id),
112
139
          _tablet_schema(std::move(tablet_schema)),
113
139
          _tablet(std::move(tablet)),
114
139
          _data_dir(data_dir),
115
139
          _opts(opts),
116
139
          _file_writer(file_writer),
117
139
          _index_file_writer(index_file_writer),
118
139
          _mem_tracker(std::make_unique<MemTracker>(
119
139
                  vertical_segment_writer_mem_tracker_name(segment_id))),
120
139
          _key_encoder(*_tablet_schema, _is_mow()),
121
139
          _mow_context(std::move(opts.mow_ctx)),
122
139
          _block_aggregator(*this) {
123
139
    CHECK_NOTNULL(file_writer);
124
139
    _num_short_key_columns = _tablet_schema->num_short_key_columns();
125
139
}
126
127
139
VerticalSegmentWriter::~VerticalSegmentWriter() {
128
139
    _mem_tracker->release(_mem_tracker->consumption());
129
139
}
130
131
void VerticalSegmentWriter::_init_column_meta(ColumnMetaPB* meta, uint32_t column_id,
132
                                              const TabletColumn& column,
133
1.99k
                                              const ColumnWriterOptions& opts) {
134
1.99k
    meta->set_column_id(column_id);
135
1.99k
    meta->set_type(int(column.type()));
136
1.99k
    meta->set_length(cast_set<int32_t>(column.length()));
137
1.99k
    meta->set_encoding(EncodingInfo::resolve_default_encoding(opts.storage_format, column));
138
1.99k
    meta->set_compression(_opts.compression_type);
139
1.99k
    meta->set_is_nullable(column.is_nullable());
140
1.99k
    meta->set_default_value(column.default_value());
141
1.99k
    meta->set_precision(column.precision());
142
1.99k
    meta->set_frac(column.frac());
143
1.99k
    if (column.has_path_info()) {
144
32
        column.path_info_ptr()->to_protobuf(meta->mutable_column_path_info(),
145
32
                                            column.parent_unique_id());
146
32
    }
147
1.99k
    meta->set_unique_id(column.unique_id());
148
2.20k
    for (uint32_t i = 0; i < column.get_subtype_count(); ++i) {
149
216
        _init_column_meta(meta->add_children_columns(), column_id, column.get_sub_column(i), opts);
150
216
    }
151
1.99k
    if (column.is_variant_type()) {
152
32
        meta->set_variant_max_subcolumns_count(column.variant_max_subcolumns_count());
153
32
        meta->set_variant_enable_doc_mode(column.variant_enable_doc_mode());
154
32
    }
155
1.99k
    meta->set_result_is_nullable(column.get_result_is_nullable());
156
1.99k
    meta->set_function_name(column.get_aggregation_name());
157
1.99k
    meta->set_be_exec_version(column.get_be_exec_version());
158
1.99k
}
159
160
Status VerticalSegmentWriter::_create_column_writer(uint32_t cid, const TabletColumn& column,
161
1.77k
                                                    const TabletSchemaSPtr& tablet_schema) {
162
1.77k
    ColumnWriterOptions opts;
163
1.77k
    opts.meta = _footer.add_columns();
164
1.77k
    opts.storage_format = tablet_schema->storage_format();
165
166
1.77k
    _init_column_meta(opts.meta, cid, column, opts);
167
168
    // now we create zone map for key columns in AGG_KEYS or all column in UNIQUE_KEYS or DUP_KEYS
169
    // except for columns whose type don't support zone map.
170
1.77k
    opts.need_zone_map = column.is_key() || tablet_schema->keys_type() != KeysType::AGG_KEYS;
171
1.77k
    opts.need_bloom_filter = column.is_bf_column();
172
1.77k
    if (opts.need_bloom_filter) {
173
24
        opts.bf_options.fpp =
174
24
                tablet_schema->has_bf_fpp() ? tablet_schema->bloom_filter_fpp() : 0.05;
175
24
    }
176
1.77k
    auto* tablet_index = tablet_schema->get_ngram_bf_index(column.unique_id());
177
1.77k
    if (tablet_index) {
178
8
        opts.need_bloom_filter = true;
179
8
        opts.is_ngram_bf_index = true;
180
        //narrow convert from int32_t to uint8_t and uint16_t which is dangerous
181
8
        auto gram_size = tablet_index->get_gram_size();
182
8
        auto gram_bf_size = tablet_index->get_gram_bf_size();
183
8
        if (gram_size > 256 || gram_size < 1) {
184
0
            return Status::NotSupported("Do not support ngram bloom filter for ngram_size: ",
185
0
                                        gram_size);
186
0
        }
187
8
        if (gram_bf_size > 65535 || gram_bf_size < 64) {
188
0
            return Status::NotSupported("Do not support ngram bloom filter for bf_size: ",
189
0
                                        gram_bf_size);
190
0
        }
191
8
        opts.gram_size = cast_set<uint8_t>(gram_size);
192
8
        opts.gram_bf_size = cast_set<uint16_t>(gram_bf_size);
193
8
    }
194
195
1.77k
    bool skip_inverted_index = false;
196
1.77k
    if (_opts.rowset_ctx != nullptr) {
197
        // skip write inverted index for index compaction column
198
1.77k
        skip_inverted_index =
199
1.77k
                _opts.rowset_ctx->columns_to_do_index_compaction.contains(column.unique_id());
200
1.77k
    }
201
    // skip write inverted index on load if skip_write_index_on_load is true
202
1.77k
    if (_opts.write_type == DataWriteType::TYPE_DIRECT &&
203
1.77k
        tablet_schema->skip_write_index_on_load()) {
204
0
        skip_inverted_index = true;
205
0
    }
206
1.77k
    if (!skip_inverted_index) {
207
1.77k
        auto inverted_indexs = tablet_schema->inverted_indexs(column);
208
1.77k
        if (!inverted_indexs.empty()) {
209
14
            opts.inverted_indexes = inverted_indexs;
210
14
            opts.need_inverted_index = true;
211
14
            DCHECK(_index_file_writer != nullptr);
212
14
        }
213
1.77k
    }
214
1.77k
    opts.index_file_writer = _index_file_writer;
215
216
1.77k
    if (const auto& index = tablet_schema->ann_index(column); index != nullptr) {
217
8
        opts.ann_index = index;
218
8
        opts.need_ann_index = true;
219
8
        DCHECK(_index_file_writer != nullptr);
220
8
        opts.index_file_writer = _index_file_writer;
221
8
    }
222
223
1.77k
#define DISABLE_INDEX_IF_FIELD_TYPE(TYPE)                     \
224
15.9k
    if (column.type() == FieldType::OLAP_FIELD_TYPE_##TYPE) { \
225
232
        opts.need_zone_map = false;                           \
226
232
        opts.need_bloom_filter = false;                       \
227
232
    }
228
229
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(STRUCT)
230
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(ARRAY)
231
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(JSONB)
232
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(AGG_STATE)
233
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(MAP)
234
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(BITMAP)
235
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(HLL)
236
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(QUANTILE_STATE)
237
1.77k
    DISABLE_INDEX_IF_FIELD_TYPE(VARIANT)
238
239
1.77k
#undef DISABLE_INDEX_IF_FIELD_TYPE
240
241
1.77k
#undef CHECK_FIELD_TYPE
242
243
1.77k
    int64_t storage_page_size = _tablet_schema->storage_page_size();
244
    // storage_page_size must be between 4KB and 10MB.
245
1.77k
    if (storage_page_size >= 4096 && storage_page_size <= 10485760) {
246
1.77k
        opts.data_page_size = storage_page_size;
247
1.77k
    }
248
1.77k
    opts.dict_page_size = _tablet_schema->storage_dict_page_size();
249
1.77k
    DBUG_EXECUTE_IF("VerticalSegmentWriter._create_column_writer.storage_page_size", {
250
1.77k
        auto table_id = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
251
1.77k
                "VerticalSegmentWriter._create_column_writer.storage_page_size", "table_id",
252
1.77k
                INT_MIN);
253
1.77k
        auto target_data_page_size = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
254
1.77k
                "VerticalSegmentWriter._create_column_writer.storage_page_size",
255
1.77k
                "storage_page_size", INT_MIN);
256
1.77k
        if (table_id == INT_MIN || target_data_page_size == INT_MIN) {
257
1.77k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
258
1.77k
                    "Debug point parameters missing: either 'table_id' or 'storage_page_size' not "
259
1.77k
                    "set.");
260
1.77k
        }
261
1.77k
        if (table_id == _tablet_schema->table_id() &&
262
1.77k
            opts.data_page_size != target_data_page_size) {
263
1.77k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
264
1.77k
                    "Mismatch in 'storage_page_size': expected size does not match the current "
265
1.77k
                    "data page size. "
266
1.77k
                    "Expected: " +
267
1.77k
                    std::to_string(target_data_page_size) +
268
1.77k
                    ", Actual: " + std::to_string(opts.data_page_size) + ".");
269
1.77k
        }
270
1.77k
    })
271
1.77k
    if (column.is_row_store_column()) {
272
        // smaller page size for row store column; encoding is already set to PLAIN /
273
        // PLAIN_V2 by _init_column_meta via resolve_default_encoding().
274
28
        auto page_size = _tablet_schema->row_store_page_size();
275
28
        opts.data_page_size =
276
28
                (page_size > 0) ? page_size : segment_v2::ROW_STORE_PAGE_SIZE_DEFAULT_VALUE;
277
28
    }
278
279
1.77k
    opts.rowset_ctx = _opts.rowset_ctx;
280
1.77k
    opts.file_writer = _file_writer;
281
1.77k
    opts.compression_type = _opts.compression_type;
282
1.77k
    opts.footer = &_footer;
283
1.77k
    opts.input_rs_readers = _opts.rowset_ctx->input_rs_readers;
284
285
1.77k
    std::unique_ptr<ColumnWriter> writer;
286
1.77k
    RETURN_IF_ERROR(ColumnWriter::create(opts, &column, _file_writer, &writer));
287
1.77k
    RETURN_IF_ERROR(writer->init());
288
1.77k
    _column_writers[cid] = std::move(writer);
289
1.77k
    _olap_data_convertor->add_column_data_convertor_at(column, cid);
290
1.77k
    return Status::OK();
291
1.77k
};
292
293
136
Status VerticalSegmentWriter::init() {
294
136
    DCHECK(_column_writers.empty());
295
136
    if (_opts.compression_type == UNKNOWN_COMPRESSION) {
296
112
        _opts.compression_type = _tablet_schema->compression_type();
297
112
    }
298
136
    _olap_data_convertor = std::make_unique<OlapBlockDataConvertor>();
299
136
    _olap_data_convertor->resize(_tablet_schema->num_columns());
300
136
    _column_writers.resize(_tablet_schema->num_columns());
301
    // we don't need the short key index for unique key merge on write table.
302
136
    if (_is_mow()) {
303
45
        size_t seq_col_length = 0;
304
45
        if (_tablet_schema->has_sequence_col()) {
305
23
            seq_col_length =
306
23
                    _tablet_schema->column(_tablet_schema->sequence_col_idx()).length() + 1;
307
23
        }
308
45
        size_t rowid_length = 0;
309
45
        if (_is_mow_with_cluster_key()) {
310
9
            rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
311
9
            _short_key_index_builder.reset(
312
9
                    new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
313
9
        }
314
45
        _primary_key_index_builder.reset(
315
45
                new PrimaryKeyIndexBuilder(_file_writer, seq_col_length, rowid_length));
316
45
        RETURN_IF_ERROR(_primary_key_index_builder->init());
317
91
    } else {
318
91
        _short_key_index_builder.reset(
319
91
                new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
320
91
    }
321
136
    return Status::OK();
322
136
}
323
324
Status VerticalSegmentWriter::_append_row_store_column(const Block& block, size_t row_pos,
325
20
                                                       size_t num_rows, uint32_t cid) {
326
20
    DCHECK(_tablet_schema->column(cid).is_row_store_column());
327
20
    if (num_rows == 0) {
328
0
        return Status::OK();
329
0
    }
330
20
    DCHECK_LE(row_pos + num_rows, block.rows());
331
332
20
    auto serdes = create_data_type_serdes(block.get_data_types());
333
20
    std::unordered_set<int32_t> row_store_cids_set(_tablet_schema->row_columns_uids().begin(),
334
20
                                                   _tablet_schema->row_columns_uids().end());
335
20
    size_t end_pos = row_pos + num_rows;
336
20
    size_t batch_rows = _opts.num_rows_per_block;
337
20
    static constexpr size_t kRowStoreBatchBytes = 4 * 1024 * 1024;
338
20
    DCHECK_GT(batch_rows, 0);
339
40
    for (size_t pos = row_pos; pos < end_pos;) {
340
20
        size_t max_rows = std::min(batch_rows, end_pos - pos);
341
20
        auto row_column = ColumnString::create();
342
20
        auto* row_store_column = row_column.get();
343
20
        size_t rows = JsonbSerializeUtil::block_to_jsonb(
344
20
                *_tablet_schema, block, *row_store_column,
345
20
                cast_set<int>(_tablet_schema->num_columns()), serdes, row_store_cids_set, pos,
346
20
                max_rows, kRowStoreBatchBytes);
347
20
        DCHECK_GT(rows, 0);
348
349
20
        auto typed_column = block.get_by_position(cid);
350
20
        typed_column.column = std::move(row_column);
351
20
        RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_column(
352
20
                typed_column, 0, rows, cid));
353
20
        auto [status, column] = _olap_data_convertor->convert_column_data(cid);
354
20
        RETURN_IF_ERROR(status);
355
20
        RETURN_IF_ERROR(
356
20
                _column_writers[cid]->append(column->get_nullmap(), column->get_data(), rows));
357
20
        _olap_data_convertor->clear_source_content(cid);
358
20
        pos += rows;
359
20
    }
360
20
    return Status::OK();
361
20
}
362
363
Status VerticalSegmentWriter::_probe_key_for_mow(
364
        const MowKeyProbe& probe, std::string key, std::size_t segment_pos,
365
        bool have_input_seq_column, bool have_delete_sign,
366
        const std::vector<RowsetSharedPtr>& specified_rowsets,
367
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
368
        bool& has_default_or_nullable, std::vector<bool>& use_default_or_null_flag,
369
        const std::function<void(const RowLocation& loc, const RowsetSharedPtr& rowset)>& found_cb,
370
60
        const std::function<Status()>& not_found_cb, PartialUpdateStats& stats) {
371
60
    ProbeOutcome outcome =
372
60
            DORIS_TRY(probe.probe(key, segment_pos, have_input_seq_column, have_delete_sign,
373
60
                                  specified_rowsets, segment_caches, stats));
374
60
    if (outcome.result == KeyProbeResult::NOT_FOUND) {
375
20
        if (!have_delete_sign) {
376
20
            RETURN_IF_ERROR(not_found_cb());
377
20
        }
378
20
        has_default_or_nullable = true;
379
20
        use_default_or_null_flag.emplace_back(true);
380
20
        return Status::OK();
381
20
    }
382
40
    if (outcome.use_default_or_null) {
383
8
        has_default_or_nullable = true;
384
8
        use_default_or_null_flag.emplace_back(true);
385
32
    } else {
386
        // partial update should not contain invisible columns
387
32
        use_default_or_null_flag.emplace_back(false);
388
32
        found_cb(outcome.loc, outcome.rowset);
389
32
    }
390
40
    return Status::OK();
391
60
}
392
393
1.26k
Status VerticalSegmentWriter::_check_column_writer_disk_capacity(size_t cid) {
394
1.26k
    if (_data_dir != nullptr &&
395
1.26k
        _data_dir->reach_capacity_limit(_column_writers[cid]->estimate_buffer_size())) {
396
0
        return Status::Error<DISK_REACH_CAPACITY_LIMIT>("disk {} exceed capacity limit.",
397
0
                                                        _data_dir->path_hash());
398
0
    }
399
1.26k
    return Status::OK();
400
1.26k
}
401
402
1.77k
Status VerticalSegmentWriter::_finalize_column_writer_and_update_meta(size_t cid) {
403
1.77k
    RETURN_IF_ERROR(_column_writers[cid]->finish());
404
1.77k
    RETURN_IF_ERROR(_column_writers[cid]->write_data());
405
406
1.77k
    auto* column_meta = _column_writers[cid]->get_column_meta();
407
1.77k
    column_meta->set_compressed_data_bytes(
408
1.77k
            _column_writers[cid]->get_total_compressed_data_pages_bytes());
409
1.77k
    column_meta->set_uncompressed_data_bytes(
410
1.77k
            _column_writers[cid]->get_total_uncompressed_data_pages_bytes());
411
1.77k
    column_meta->set_raw_data_bytes(_column_writers[cid]->get_raw_data_bytes());
412
1.77k
    return Status::OK();
413
1.77k
}
414
415
Status VerticalSegmentWriter::_partial_update_preconditions_check(size_t row_pos,
416
20
                                                                  bool is_flexible_update) {
417
20
    if (!_is_mow()) {
418
0
        auto msg = fmt::format(
419
0
                "Can only do partial update on merge-on-write unique table, but found: "
420
0
                "keys_type={}, _opts.enable_unique_key_merge_on_write={}, tablet_id={}",
421
0
                _tablet_schema->keys_type(), _opts.enable_unique_key_merge_on_write,
422
0
                _tablet->tablet_id());
423
0
        DCHECK(false) << msg;
424
0
        return Status::InternalError<false>(msg);
425
0
    }
426
20
    if (_opts.rowset_ctx->partial_update_info == nullptr) {
427
0
        auto msg =
428
0
                fmt::format("partial_update_info should not be nullptr, please check, tablet_id={}",
429
0
                            _tablet->tablet_id());
430
0
        DCHECK(false) << msg;
431
0
        return Status::InternalError<false>(msg);
432
0
    }
433
20
    if (!is_flexible_update) {
434
12
        if (!_opts.rowset_ctx->partial_update_info->is_fixed_partial_update()) {
435
0
            auto msg = fmt::format(
436
0
                    "in fixed partial update code, but update_mode={}, please check, tablet_id={}",
437
0
                    _opts.rowset_ctx->partial_update_info->update_mode(), _tablet->tablet_id());
438
0
            DCHECK(false) << msg;
439
0
            return Status::InternalError<false>(msg);
440
0
        }
441
12
    } else {
442
8
        if (!_opts.rowset_ctx->partial_update_info->is_flexible_partial_update()) {
443
0
            auto msg = fmt::format(
444
0
                    "in flexible partial update code, but update_mode={}, please check, "
445
0
                    "tablet_id={}",
446
0
                    _opts.rowset_ctx->partial_update_info->update_mode(), _tablet->tablet_id());
447
0
            DCHECK(false) << msg;
448
0
            return Status::InternalError<false>(msg);
449
0
        }
450
8
    }
451
20
    if (row_pos != 0) {
452
0
        auto msg = fmt::format("row_pos should be 0, but found {}, tablet_id={}", row_pos,
453
0
                               _tablet->tablet_id());
454
0
        DCHECK(false) << msg;
455
0
        return Status::InternalError<false>(msg);
456
0
    }
457
20
    return Status::OK();
458
20
}
459
460
// for partial update, we should do following steps to fill content of block:
461
// 1. set block data to data convertor, and get all key_column's converted slice
462
// 2. get pk of input block, and read missing columns
463
//       2.1 first find key location{rowset_id, segment_id, row_id}
464
//       2.2 build read plan to read by batch
465
//       2.3 fill block
466
// 3. set columns to data convertor and then write all columns
467
Status VerticalSegmentWriter::_append_block_with_partial_content(RowsInBlock& data,
468
12
                                                                 Block& full_block) {
469
12
    DBUG_EXECUTE_IF("_append_block_with_partial_content.block", DBUG_BLOCK);
470
471
12
    RETURN_IF_ERROR(_partial_update_preconditions_check(data.row_pos, false));
472
    // create full block and fill with input columns
473
12
    full_block = _tablet_schema->create_block();
474
12
    const auto& including_cids = _opts.rowset_ctx->partial_update_info->update_cids;
475
12
    size_t input_id = 0;
476
260
    for (auto i : including_cids) {
477
260
        full_block.replace_by_position(i, data.block->get_by_position(input_id++).column);
478
260
    }
479
480
12
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
481
12
        _tablet_schema->num_variant_columns() > 0) {
482
4
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
483
4
                full_block, *_tablet_schema, including_cids));
484
4
    }
485
12
    bool have_input_seq_column = false;
486
    // write including columns
487
12
    std::vector<IOlapColumnDataAccessor*> key_columns;
488
12
    IOlapColumnDataAccessor* seq_column = nullptr;
489
12
    uint32_t segment_start_pos = 0;
490
260
    for (auto cid : including_cids) {
491
260
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
492
260
        RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
493
260
                &full_block, data.row_pos, data.num_rows, std::vector<uint32_t> {cid}));
494
        // here we get segment column row num before append data.
495
260
        segment_start_pos = cast_set<uint32_t>(_column_writers[cid]->get_next_rowid());
496
        // olap data convertor alway start from id = 0
497
260
        auto [status, column] = _olap_data_convertor->convert_column_data(cid);
498
260
        if (!status.ok()) {
499
0
            return status;
500
0
        }
501
260
        if (cid < _key_encoder.num_sort_key_columns()) {
502
240
            key_columns.push_back(column);
503
240
        } else if (_tablet_schema->has_sequence_col() &&
504
20
                   cid == _tablet_schema->sequence_col_idx()) {
505
4
            seq_column = column;
506
4
            have_input_seq_column = true;
507
4
        }
508
260
        RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
509
260
                                                     data.num_rows));
510
260
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
511
        // Don't clear source content for key columns and sequence column here,
512
        // as they will be used later for key encoding and _generate_primary_key_index().
513
        // They will be cleared at the end of this method.
514
260
        bool is_key_column = (cid < _key_encoder.num_sort_key_columns());
515
260
        bool is_seq_column = (_tablet_schema->has_sequence_col() &&
516
260
                              cid == _tablet_schema->sequence_col_idx() && have_input_seq_column);
517
260
        if (!is_key_column && !is_seq_column) {
518
16
            _olap_data_convertor->clear_source_content(cid);
519
16
        }
520
260
    }
521
522
12
    bool has_default_or_nullable = false;
523
12
    std::vector<bool> use_default_or_null_flag;
524
12
    use_default_or_null_flag.reserve(data.num_rows);
525
12
    const auto* delete_signs =
526
12
            BaseTablet::get_delete_sign_column_data(full_block, data.row_pos + data.num_rows);
527
528
12
    DBUG_EXECUTE_IF("VerticalSegmentWriter._append_block_with_partial_content.sleep",
529
12
                    { sleep(60); })
530
12
    const std::vector<RowsetSharedPtr>& specified_rowsets = _mow_context->rowset_ptrs;
531
12
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
532
533
12
    MowKeyProbe probe = MowKeyProbe::for_partial_update(
534
12
            _tablet.get(), _tablet_schema.get(), _tablet_schema->has_sequence_col(), _mow_context,
535
12
            _opts.rowset_ctx->rowset_id, _segment_id, /*flexible=*/false);
536
    // owns the rowset pins and the read plan for the historical read below
537
12
    HistoricalRowFetcher fetcher {_opts.rowset_ctx->make_historical_row_retriever_context()};
538
539
    // locate rows in base data
540
12
    PartialUpdateStats stats;
541
542
48
    for (size_t block_pos = data.row_pos; block_pos < data.row_pos + data.num_rows; block_pos++) {
543
        // block   segment
544
        //   2   ->   0
545
        //   3   ->   1
546
        //   4   ->   2
547
        //   5   ->   3
548
        // here row_pos = 2, num_rows = 4.
549
36
        size_t delta_pos = block_pos - data.row_pos;
550
36
        size_t segment_pos = segment_start_pos + delta_pos;
551
36
        std::string key = encode_mow_key_invalidate_cache(
552
36
                _key_encoder, key_columns, seq_column, delta_pos, have_input_seq_column,
553
36
                _opts.rowset_ctx->tablet_id, *_tablet_schema, _opts.write_type);
554
        // If the table have sequence column, and the include-cids don't contain the sequence
555
        // column, we need to update the primary key index builder at the end of this method.
556
        // At that time, we have a valid sequence column to encode the key with seq col.
557
36
        if (!_tablet_schema->has_sequence_col() || have_input_seq_column) {
558
24
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
559
24
        }
560
561
        // mark key with delete sign as deleted.
562
36
        bool have_delete_sign = (delete_signs != nullptr && delete_signs[block_pos] != 0);
563
564
36
        auto not_found_cb = [&]() {
565
12
            return _opts.rowset_ctx->partial_update_info->handle_new_key(
566
12
                    *_tablet_schema, [&]() -> std::string {
567
0
                        return data.block->dump_one_line(
568
0
                                block_pos, cast_set<int>(_key_encoder.num_sort_key_columns()));
569
0
                    });
570
12
        };
571
36
        auto update_read_plan = [&](const RowLocation& loc, const RowsetSharedPtr& rowset) {
572
            // keep the rowset alive until the historical read below is done
573
24
            fetcher.pin_rowset(rowset);
574
24
            fetcher.plan_fixed_read(loc, segment_pos);
575
24
        };
576
36
        RETURN_IF_ERROR(_probe_key_for_mow(
577
36
                probe, std::move(key), segment_pos, have_input_seq_column, have_delete_sign,
578
36
                specified_rowsets, segment_caches, has_default_or_nullable,
579
36
                use_default_or_null_flag, update_read_plan, not_found_cb, stats));
580
36
    }
581
12
    CHECK_EQ(use_default_or_null_flag.size(), data.num_rows);
582
583
12
    if (config::enable_merge_on_write_correctness_check) {
584
12
        _tablet->add_sentinel_mark_to_delete_bitmap(_mow_context->delete_bitmap.get(),
585
12
                                                    *_mow_context->rowset_ids);
586
12
    }
587
588
    // read to fill full_block
589
12
    RETURN_IF_ERROR(fetcher.fill_missing_columns(*_tablet_schema, full_block,
590
12
                                                 use_default_or_null_flag, has_default_or_nullable,
591
12
                                                 segment_start_pos, data.block));
592
593
12
    if (_tablet_schema->num_variant_columns() > 0) {
594
4
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
595
4
                full_block, *_tablet_schema, _opts.rowset_ctx->partial_update_info->missing_cids));
596
4
    }
597
598
    // convert missing columns and send to column writer
599
12
    const auto& missing_cids = _opts.rowset_ctx->partial_update_info->missing_cids;
600
48
    for (auto cid : missing_cids) {
601
48
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
602
48
        if (_tablet_schema->column(cid).is_row_store_column()) {
603
4
            RETURN_IF_ERROR(_append_row_store_column(full_block, data.row_pos, data.num_rows, cid));
604
4
            RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
605
4
            continue;
606
4
        }
607
44
        RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
608
44
                &full_block, data.row_pos, data.num_rows, std::vector<uint32_t> {cid}));
609
44
        auto [status, column] = _olap_data_convertor->convert_column_data(cid);
610
44
        if (!status.ok()) {
611
0
            return status;
612
0
        }
613
44
        if (_tablet_schema->has_sequence_col() && !have_input_seq_column &&
614
44
            cid == _tablet_schema->sequence_col_idx()) {
615
4
            DCHECK_EQ(seq_column, nullptr);
616
4
            seq_column = column;
617
4
        }
618
44
        RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
619
44
                                                     data.num_rows));
620
44
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
621
        // Don't clear source content for sequence column here if it will be used later
622
        // in _generate_primary_key_index(). It will be cleared at the end of this method.
623
44
        bool is_seq_column = (_tablet_schema->has_sequence_col() && !have_input_seq_column &&
624
44
                              cid == _tablet_schema->sequence_col_idx());
625
44
        if (!is_seq_column) {
626
40
            _olap_data_convertor->clear_source_content(cid);
627
40
        }
628
44
    }
629
630
12
    _num_rows_updated += stats.num_rows_updated;
631
12
    _num_rows_deleted += stats.num_rows_deleted;
632
12
    _num_rows_new_added += stats.num_rows_new_added;
633
12
    _num_rows_filtered += stats.num_rows_filtered;
634
12
    if (_tablet_schema->has_sequence_col() && !have_input_seq_column) {
635
4
        DCHECK_NE(seq_column, nullptr);
636
4
        if (_num_rows_written != data.row_pos ||
637
4
            _primary_key_index_builder->num_rows() != _num_rows_written) {
638
0
            return Status::InternalError(
639
0
                    "Correctness check failed, _num_rows_written: {}, row_pos: {}, primary key "
640
0
                    "index builder num rows: {}",
641
0
                    _num_rows_written, data.row_pos, _primary_key_index_builder->num_rows());
642
0
        }
643
4
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, data.num_rows, false));
644
4
    }
645
646
12
    _num_rows_written += data.num_rows;
647
12
    DCHECK_EQ(_primary_key_index_builder->num_rows(), _num_rows_written)
648
0
            << "primary key index builder num rows(" << _primary_key_index_builder->num_rows()
649
0
            << ") not equal to segment writer's num rows written(" << _num_rows_written << ")";
650
12
    _olap_data_convertor->clear_source_content();
651
12
    return Status::OK();
652
12
}
653
654
Status VerticalSegmentWriter::_append_block_with_flexible_partial_content(RowsInBlock& data,
655
8
                                                                          Block& full_block) {
656
8
    RETURN_IF_ERROR(_partial_update_preconditions_check(data.row_pos, true));
657
658
    // data.block has the same schema with full_block
659
8
    DCHECK(data.block->columns() == _tablet_schema->num_columns());
660
661
    // create full block and fill with sort key columns
662
8
    full_block = _tablet_schema->create_block();
663
664
    // Use _num_rows_written instead of creating column writer 0, since all column writers
665
    // should have the same row count, which equals _num_rows_written.
666
8
    uint32_t segment_start_pos = cast_set<uint32_t>(_num_rows_written);
667
668
8
    DCHECK(_tablet_schema->has_skip_bitmap_col());
669
8
    auto skip_bitmap_col_idx = _tablet_schema->skip_bitmap_col_idx();
670
671
8
    bool has_default_or_nullable = false;
672
8
    std::vector<bool> use_default_or_null_flag;
673
8
    use_default_or_null_flag.reserve(data.num_rows);
674
675
8
    int32_t seq_map_col_unique_id = _opts.rowset_ctx->partial_update_info->sequence_map_col_uid();
676
8
    bool schema_has_sequence_col = _tablet_schema->has_sequence_col();
677
678
8
    DBUG_EXECUTE_IF("VerticalSegmentWriter._append_block_with_flexible_partial_content.sleep",
679
8
                    { sleep(60); })
680
8
    const std::vector<RowsetSharedPtr>& specified_rowsets = _mow_context->rowset_ptrs;
681
8
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
682
683
    // Ensure all primary key column writers and sequence column writer are created before
684
    // aggregate_for_flexible_partial_update, because it internally calls convert_pk_columns
685
    // and convert_seq_column which need the convertors in _olap_data_convertor
686
168
    for (uint32_t cid = 0; cid < _tablet_schema->num_key_columns(); ++cid) {
687
160
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
688
160
    }
689
8
    if (schema_has_sequence_col) {
690
4
        uint32_t cid = _tablet_schema->sequence_col_idx();
691
4
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
692
4
    }
693
694
    // 1. aggregate duplicate rows in block
695
8
    RETURN_IF_ERROR(_block_aggregator.aggregate_for_flexible_partial_update(
696
8
            const_cast<Block*>(data.block), data.num_rows, specified_rowsets, segment_caches));
697
8
    if (data.block->rows() != data.num_rows) {
698
8
        data.num_rows = data.block->rows();
699
8
        _olap_data_convertor->clear_source_content();
700
8
    }
701
702
    // 2. encode primary key columns
703
    // we can only encode primary key columns currently becasue all non-primary columns in flexible partial update
704
    // can have missing cells
705
8
    std::vector<IOlapColumnDataAccessor*> key_columns {};
706
8
    RETURN_IF_ERROR(_block_aggregator.convert_pk_columns(const_cast<Block*>(data.block),
707
8
                                                         data.row_pos, data.num_rows, key_columns));
708
    // 3. encode sequence column
709
    // We encode the seguence column even thought it may have invalid values in some rows because we need to
710
    // encode the value of sequence column in key for rows that have a valid value in sequence column during
711
    // lookup_raw_key. We will encode the sequence column again at the end of this method. At that time, we have
712
    // a valid sequence column to encode the key with seq col.
713
8
    IOlapColumnDataAccessor* seq_column {nullptr};
714
8
    RETURN_IF_ERROR(_block_aggregator.convert_seq_column(const_cast<Block*>(data.block),
715
8
                                                         data.row_pos, data.num_rows, seq_column));
716
717
8
    auto* mutable_block = const_cast<Block*>(data.block);
718
8
    std::vector<BitmapValue>* skip_bitmaps =
719
8
            &get_mutable_skip_bitmap_column(mutable_block, skip_bitmap_col_idx)->get_data();
720
8
    const auto* delete_signs =
721
8
            BaseTablet::get_delete_sign_column_data(*data.block, data.row_pos + data.num_rows);
722
8
    DCHECK(delete_signs != nullptr);
723
724
168
    for (std::size_t cid {0}; cid < _tablet_schema->num_key_columns(); cid++) {
725
160
        full_block.replace_by_position(cid, data.block->get_by_position(cid).column);
726
160
    }
727
728
    // 4. write primary key columns data
729
168
    for (std::size_t cid {0}; cid < _tablet_schema->num_key_columns(); cid++) {
730
160
        const auto& column = key_columns[cid];
731
160
        DCHECK(_column_writers[cid]->get_next_rowid() == _num_rows_written);
732
160
        RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
733
160
                                                     data.num_rows));
734
160
        DCHECK(_column_writers[cid]->get_next_rowid() == _num_rows_written + data.num_rows);
735
160
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
736
160
    }
737
738
    // 5. genreate read plan
739
8
    FlexibleReadPlan read_plan {_tablet_schema->has_row_store_for_all_columns()};
740
8
    PartialUpdateStats stats;
741
8
    RETURN_IF_ERROR(_generate_flexible_read_plan(
742
8
            read_plan, data, segment_start_pos, schema_has_sequence_col, seq_map_col_unique_id,
743
8
            skip_bitmaps, key_columns, seq_column, delete_signs, specified_rowsets, segment_caches,
744
8
            has_default_or_nullable, use_default_or_null_flag, stats));
745
8
    CHECK_EQ(use_default_or_null_flag.size(), data.num_rows);
746
747
8
    if (config::enable_merge_on_write_correctness_check) {
748
8
        _tablet->add_sentinel_mark_to_delete_bitmap(_mow_context->delete_bitmap.get(),
749
8
                                                    *_mow_context->rowset_ids);
750
8
    }
751
752
    // 6. read according plan to fill full_block
753
8
    RETURN_IF_ERROR(read_plan.fill_non_primary_key_columns(
754
8
            _opts.rowset_ctx->make_historical_row_retriever_context(), _rsid_to_rowset,
755
8
            *_tablet_schema, full_block, use_default_or_null_flag, has_default_or_nullable,
756
8
            segment_start_pos, cast_set<uint32_t>(data.row_pos), data.block, skip_bitmaps));
757
758
    // TODO(bobhan1): should we replace the skip bitmap column with empty bitmaps to reduce storage occupation?
759
    // this column is not needed in read path for merge-on-write table
760
761
    // 7. fill row store column
762
56
    for (auto cid = _tablet_schema->num_key_columns(); cid < _tablet_schema->num_columns(); cid++) {
763
48
        if (!_tablet_schema->column(cid).is_row_store_column()) {
764
44
            continue;
765
44
        }
766
4
        RETURN_IF_ERROR(_create_column_writer(cast_set<uint32_t>(cid), _tablet_schema->column(cid),
767
4
                                              _tablet_schema));
768
4
        RETURN_IF_ERROR(_append_row_store_column(full_block, data.row_pos, data.num_rows,
769
4
                                                 cast_set<uint32_t>(cid)));
770
4
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
771
4
    }
772
773
8
    std::vector<uint32_t> column_ids;
774
216
    for (uint32_t i = 0; i < _tablet_schema->num_columns(); ++i) {
775
208
        column_ids.emplace_back(i);
776
208
    }
777
8
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
778
8
        _tablet_schema->num_variant_columns() > 0) {
779
0
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
780
0
                full_block, *_tablet_schema, column_ids));
781
0
    }
782
783
    // 8. encode and write all non-primary key columns(including sequence column if exists)
784
56
    for (auto cid = _tablet_schema->num_key_columns(); cid < _tablet_schema->num_columns(); cid++) {
785
48
        if (_tablet_schema->column(cid).is_row_store_column()) {
786
4
            continue;
787
4
        }
788
44
        if (cid != _tablet_schema->sequence_col_idx()) {
789
40
            RETURN_IF_ERROR(_create_column_writer(cast_set<uint32_t>(cid),
790
40
                                                  _tablet_schema->column(cid), _tablet_schema));
791
40
        }
792
44
        RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_column(
793
44
                full_block.get_by_position(cid), data.row_pos, data.num_rows,
794
44
                cast_set<uint32_t>(cid)));
795
44
        auto [status, column] = _olap_data_convertor->convert_column_data(cid);
796
44
        if (!status.ok()) {
797
0
            return status;
798
0
        }
799
44
        if (cid == _tablet_schema->sequence_col_idx()) {
800
            // should use the latest encoded sequence column to build the primary index
801
4
            seq_column = column;
802
4
        }
803
44
        DCHECK(_column_writers[cid]->get_next_rowid() == _num_rows_written);
804
44
        RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
805
44
                                                     data.num_rows));
806
44
        DCHECK(_column_writers[cid]->get_next_rowid() == _num_rows_written + data.num_rows);
807
44
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
808
44
    }
809
810
8
    _num_rows_updated += stats.num_rows_updated;
811
8
    _num_rows_deleted += stats.num_rows_deleted;
812
8
    _num_rows_new_added += stats.num_rows_new_added;
813
8
    _num_rows_filtered += stats.num_rows_filtered;
814
815
8
    if (_num_rows_written != data.row_pos ||
816
8
        _primary_key_index_builder->num_rows() != _num_rows_written) {
817
0
        return Status::InternalError(
818
0
                "Correctness check failed, _num_rows_written: {}, row_pos: {}, primary key "
819
0
                "index builder num rows: {}",
820
0
                _num_rows_written, data.row_pos, _primary_key_index_builder->num_rows());
821
0
    }
822
823
    // 9. build primary key index
824
8
    RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, data.num_rows, false));
825
826
8
    _num_rows_written += data.num_rows;
827
8
    DCHECK_EQ(_primary_key_index_builder->num_rows(), _num_rows_written)
828
0
            << "primary key index builder num rows(" << _primary_key_index_builder->num_rows()
829
0
            << ") not equal to segment writer's num rows written(" << _num_rows_written << ")";
830
8
    _olap_data_convertor->clear_source_content();
831
8
    return Status::OK();
832
8
}
833
834
Status VerticalSegmentWriter::_generate_encoded_default_seq_value(const TabletSchema& tablet_schema,
835
                                                                  const PartialUpdateInfo& info,
836
0
                                                                  std::string* encoded_value) {
837
0
    const auto& seq_column = tablet_schema.column(tablet_schema.sequence_col_idx());
838
0
    auto block = tablet_schema.create_block_by_cids(
839
0
            {cast_set<uint32_t>(tablet_schema.sequence_col_idx())});
840
0
    if (seq_column.has_default_value()) {
841
0
        auto idx = tablet_schema.sequence_col_idx() - tablet_schema.num_key_columns();
842
0
        const auto& default_value = info.default_values[idx];
843
0
        StringRef str {default_value};
844
0
        RETURN_IF_ERROR(block.get_by_position(0).type->get_serde()->default_from_string(
845
0
                str, *block.get_by_position(0).column->assert_mutable().get()));
846
847
0
    } else {
848
0
        block.get_by_position(0).column->assert_mutable()->insert_default();
849
0
    }
850
0
    DCHECK_EQ(block.rows(), 1);
851
0
    auto olap_data_convertor = std::make_unique<OlapBlockDataConvertor>();
852
0
    olap_data_convertor->add_column_data_convertor(seq_column);
853
0
    olap_data_convertor->set_source_content(&block, 0, 1);
854
0
    auto [status, column] = olap_data_convertor->convert_column_data(0);
855
0
    if (!status.ok()) {
856
0
        return status;
857
0
    }
858
    // include marker
859
0
    _key_encoder.append_seq_suffix(encoded_value, column, 0);
860
0
    return Status::OK();
861
0
}
862
863
Status VerticalSegmentWriter::_generate_flexible_read_plan(
864
        FlexibleReadPlan& read_plan, RowsInBlock& data, size_t segment_start_pos,
865
        bool schema_has_sequence_col, int32_t seq_map_col_unique_id,
866
        std::vector<BitmapValue>* skip_bitmaps,
867
        const std::vector<IOlapColumnDataAccessor*>& key_columns,
868
        IOlapColumnDataAccessor* seq_column, const signed char* delete_signs,
869
        const std::vector<RowsetSharedPtr>& specified_rowsets,
870
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
871
        bool& has_default_or_nullable, std::vector<bool>& use_default_or_null_flag,
872
8
        PartialUpdateStats& stats) {
873
8
    int32_t delete_sign_col_unique_id =
874
8
            _tablet_schema->column(_tablet_schema->delete_sign_idx()).unique_id();
875
8
    int32_t seq_col_unique_id =
876
8
            (_tablet_schema->has_sequence_col()
877
8
                     ? _tablet_schema->column(_tablet_schema->sequence_col_idx()).unique_id()
878
8
                     : -1);
879
8
    MowKeyProbe probe = MowKeyProbe::for_partial_update(
880
8
            _tablet.get(), _tablet_schema.get(), _tablet_schema->has_sequence_col(), _mow_context,
881
8
            _opts.rowset_ctx->rowset_id, _segment_id, /*flexible=*/true);
882
32
    for (size_t block_pos = data.row_pos; block_pos < data.row_pos + data.num_rows; block_pos++) {
883
24
        size_t delta_pos = block_pos - data.row_pos;
884
24
        size_t segment_pos = segment_start_pos + delta_pos;
885
24
        auto& skip_bitmap = skip_bitmaps->at(block_pos);
886
887
24
        bool row_has_sequence_col =
888
24
                (schema_has_sequence_col && !skip_bitmap.contains(seq_col_unique_id));
889
24
        std::string key = encode_mow_key_invalidate_cache(
890
24
                _key_encoder, key_columns, seq_column, delta_pos, row_has_sequence_col,
891
24
                _opts.rowset_ctx->tablet_id, *_tablet_schema, _opts.write_type);
892
893
        // mark key with delete sign as deleted.
894
24
        bool have_delete_sign =
895
24
                (!skip_bitmap.contains(delete_sign_col_unique_id) && delete_signs[block_pos] != 0);
896
897
24
        auto not_found_cb = [&]() {
898
8
            return _opts.rowset_ctx->partial_update_info->handle_new_key(
899
8
                    *_tablet_schema,
900
8
                    [&]() -> std::string {
901
0
                        return data.block->dump_one_line(
902
0
                                block_pos, cast_set<int>(_key_encoder.num_sort_key_columns()));
903
0
                    },
904
8
                    &skip_bitmap);
905
8
        };
906
24
        auto update_read_plan = [&](const RowLocation& loc, const RowsetSharedPtr& rowset) {
907
            // the flexible fill still reads through the writer's pin map, which the block
908
            // aggregator also feeds
909
8
            _rsid_to_rowset.emplace(rowset->rowset_id(), rowset);
910
8
            read_plan.prepare_to_read(loc, segment_pos, skip_bitmap);
911
8
        };
912
913
24
        RETURN_IF_ERROR(_probe_key_for_mow(probe, std::move(key), segment_pos, row_has_sequence_col,
914
24
                                           have_delete_sign, specified_rowsets, segment_caches,
915
24
                                           has_default_or_nullable, use_default_or_null_flag,
916
24
                                           update_read_plan, not_found_cb, stats));
917
24
    }
918
8
    return Status::OK();
919
8
}
920
921
136
Status VerticalSegmentWriter::batch_block(const Block* block, size_t row_pos, size_t num_rows) {
922
136
    if (_opts.rowset_ctx->partial_update_info &&
923
136
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
924
136
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
925
136
        !_opts.rowset_ctx->is_transient_rowset_writer) {
926
20
        if (_opts.rowset_ctx->partial_update_info->is_flexible_partial_update()) {
927
8
            if (block->columns() != _tablet_schema->num_columns()) {
928
0
                return Status::InvalidArgument(
929
0
                        "illegal flexible partial update block columns, block columns = {}, "
930
0
                        "tablet_schema columns = {}",
931
0
                        block->dump_structure(), _tablet_schema->dump_structure());
932
0
            }
933
12
        } else {
934
12
            if (block->columns() < _tablet_schema->num_key_columns() ||
935
12
                block->columns() >= _tablet_schema->num_columns()) {
936
0
                return Status::InvalidArgument(fmt::format(
937
0
                        "illegal partial update block columns: {}, num key columns: {}, total "
938
0
                        "schema columns: {}",
939
0
                        block->columns(), _tablet_schema->num_key_columns(),
940
0
                        _tablet_schema->num_columns()));
941
0
            }
942
12
        }
943
116
    } else if (block->columns() != _tablet_schema->num_columns()) {
944
0
        return Status::InvalidArgument(
945
0
                "illegal block columns, block columns = {}, tablet_schema columns = {}",
946
0
                block->dump_structure(), _tablet_schema->dump_structure());
947
0
    }
948
136
    _batched_blocks.emplace_back(block, row_pos, num_rows);
949
136
    return Status::OK();
950
136
}
951
952
136
Status VerticalSegmentWriter::write_batch() {
953
136
    if (_opts.rowset_ctx->partial_update_info &&
954
136
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
955
136
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
956
136
        !_opts.rowset_ctx->is_transient_rowset_writer) {
957
20
        bool is_flexible_partial_update =
958
20
                _opts.rowset_ctx->partial_update_info->is_flexible_partial_update();
959
20
        Block full_block;
960
20
        for (auto& data : _batched_blocks) {
961
20
            if (is_flexible_partial_update) {
962
8
                RETURN_IF_ERROR(_append_block_with_flexible_partial_content(data, full_block));
963
12
            } else {
964
12
                RETURN_IF_ERROR(_append_block_with_partial_content(data, full_block));
965
12
            }
966
20
        }
967
20
        return Status::OK();
968
20
    }
969
    // Row column should be filled here when it's a directly write from memtable
970
    // or it's schema change write(since column data type maybe changed, so we should reubild)
971
116
    bool should_write_row_store_column = _opts.write_type == DataWriteType::TYPE_DIRECT ||
972
116
                                         _opts.write_type == DataWriteType::TYPE_SCHEMA_CHANGE;
973
116
    if (should_write_row_store_column) {
974
1.33k
        for (uint32_t cid = 0; cid < _tablet_schema->num_columns(); ++cid) {
975
1.22k
            if (!_tablet_schema->column(cid).is_row_store_column()) {
976
1.21k
                continue;
977
1.21k
            }
978
12
            RETURN_IF_ERROR(
979
12
                    _create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
980
12
            for (auto& data : _batched_blocks) {
981
12
                RETURN_IF_ERROR(
982
12
                        _append_row_store_column(*data.block, data.row_pos, data.num_rows, cid));
983
12
            }
984
12
            RETURN_IF_ERROR(_check_column_writer_disk_capacity(cid));
985
12
            RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
986
12
        }
987
106
    }
988
989
116
    std::vector<uint32_t> column_ids;
990
1.37k
    for (uint32_t i = 0; i < _tablet_schema->num_columns(); ++i) {
991
1.26k
        column_ids.emplace_back(i);
992
1.26k
    }
993
116
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
994
116
        _tablet_schema->num_variant_columns() > 0) {
995
20
        for (auto& data : _batched_blocks) {
996
20
            RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
997
20
                    const_cast<Block&>(*data.block), *_tablet_schema, column_ids));
998
20
        }
999
20
    }
1000
1001
116
    std::vector<IOlapColumnDataAccessor*> key_columns;
1002
116
    IOlapColumnDataAccessor* seq_column = nullptr;
1003
    // the key is cluster key column unique id
1004
116
    std::map<uint32_t, IOlapColumnDataAccessor*> cid_to_column;
1005
1.37k
    for (uint32_t cid = 0; cid < _tablet_schema->num_columns(); ++cid) {
1006
1.26k
        if (should_write_row_store_column && _tablet_schema->column(cid).is_row_store_column()) {
1007
12
            continue;
1008
12
        }
1009
1.24k
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
1010
1.24k
        for (auto& data : _batched_blocks) {
1011
1.24k
            RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
1012
1.24k
                    data.block, data.row_pos, data.num_rows, std::vector<uint32_t> {cid}));
1013
1014
            // convert column data from engine format to storage layer format
1015
1.24k
            auto [status, column] = _olap_data_convertor->convert_column_data(cid);
1016
1.24k
            if (!status.ok()) {
1017
0
                return status;
1018
0
            }
1019
1.24k
            if (cid < _tablet_schema->num_key_columns()) {
1020
669
                key_columns.push_back(column);
1021
669
            }
1022
1.24k
            if (_tablet_schema->has_sequence_col() && cid == _tablet_schema->sequence_col_idx()) {
1023
15
                seq_column = column;
1024
15
            }
1025
1.24k
            auto column_unique_id = _tablet_schema->column(cid).unique_id();
1026
1.24k
            if (_is_mow_with_cluster_key() &&
1027
1.24k
                std::find(_tablet_schema->cluster_key_uids().begin(),
1028
193
                          _tablet_schema->cluster_key_uids().end(),
1029
193
                          column_unique_id) != _tablet_schema->cluster_key_uids().end()) {
1030
162
                cid_to_column[column_unique_id] = column;
1031
162
            }
1032
1.24k
            RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
1033
1.24k
                                                         data.num_rows));
1034
1.24k
            _olap_data_convertor->clear_source_content();
1035
1.24k
        }
1036
1.24k
        RETURN_IF_ERROR(_check_column_writer_disk_capacity(cid));
1037
1.24k
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
1038
1.24k
    }
1039
1040
116
    for (auto& data : _batched_blocks) {
1041
116
        _olap_data_convertor->set_source_content(data.block, data.row_pos, data.num_rows);
1042
116
        RETURN_IF_ERROR(_generate_key_index(data, key_columns, seq_column, cid_to_column));
1043
116
        _olap_data_convertor->clear_source_content();
1044
116
        _num_rows_written += data.num_rows;
1045
116
    }
1046
1047
116
    _batched_blocks.clear();
1048
116
    return Status::OK();
1049
116
}
1050
1051
Status VerticalSegmentWriter::_generate_key_index(
1052
        RowsInBlock& data, std::vector<IOlapColumnDataAccessor*>& key_columns,
1053
        IOlapColumnDataAccessor* seq_column,
1054
116
        std::map<uint32_t, IOlapColumnDataAccessor*>& cid_to_column) {
1055
    // find all row pos for short key indexes
1056
116
    std::vector<size_t> short_key_pos;
1057
    // We build a short key index every `_opts.num_rows_per_block` rows. Specifically, we
1058
    // build a short key index using 1st rows for first block and `_short_key_row_pos - _row_count`
1059
    // for next blocks.
1060
116
    if (_short_key_row_pos == 0 && _num_rows_written == 0) {
1061
116
        short_key_pos.push_back(0);
1062
116
    }
1063
116
    while (_short_key_row_pos + _opts.num_rows_per_block < _num_rows_written + data.num_rows) {
1064
0
        _short_key_row_pos += _opts.num_rows_per_block;
1065
0
        short_key_pos.push_back(_short_key_row_pos - _num_rows_written);
1066
0
    }
1067
116
    if (_is_mow_with_cluster_key()) {
1068
        // 1. generate primary key index
1069
9
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, data.num_rows, true));
1070
        // 2. generate short key index (use cluster key)
1071
9
        std::vector<IOlapColumnDataAccessor*> short_key_columns;
1072
162
        for (const auto& cid : _tablet_schema->cluster_key_uids()) {
1073
162
            short_key_columns.push_back(cid_to_column[cid]);
1074
162
        }
1075
9
        RETURN_IF_ERROR(_generate_short_key_index(short_key_columns, data.num_rows, short_key_pos));
1076
107
    } else if (_is_mow()) {
1077
16
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, data.num_rows, false));
1078
91
    } else { // other tables
1079
91
        RETURN_IF_ERROR(_generate_short_key_index(key_columns, data.num_rows, short_key_pos));
1080
91
    }
1081
116
    return Status::OK();
1082
116
}
1083
1084
Status VerticalSegmentWriter::_generate_primary_key_index(
1085
        const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
1086
37
        IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort) {
1087
37
    if (!need_sort) { // mow table without cluster key
1088
28
        std::string last_key;
1089
108
        for (size_t pos = 0; pos < num_rows; pos++) {
1090
80
            std::string key = encode_mow_key_invalidate_cache(
1091
80
                    _key_encoder, primary_key_columns, seq_column, pos,
1092
80
                    _tablet_schema->has_sequence_col(), _opts.rowset_ctx->tablet_id,
1093
80
                    *_tablet_schema, _opts.write_type);
1094
80
            DCHECK(key.compare(last_key) > 0)
1095
0
                    << "found duplicate key or key is not sorted! current key: " << key
1096
0
                    << ", last key: " << last_key;
1097
80
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1098
80
            last_key = std::move(key);
1099
80
        }
1100
28
    } else { // mow table with cluster key
1101
        // 1. generate primary keys in memory
1102
9
        std::vector<std::string> primary_keys;
1103
37
        for (uint32_t pos = 0; pos < num_rows; pos++) {
1104
28
            std::string key = _key_encoder.full_encode_primary_keys(primary_key_columns, pos);
1105
28
            MowKeyProbe::maybe_invalidate_row_cache(_opts.rowset_ctx->tablet_id, *_tablet_schema,
1106
28
                                                    _opts.write_type, key);
1107
28
            if (_tablet_schema->has_sequence_col()) {
1108
16
                _key_encoder.append_seq_suffix(&key, seq_column, pos);
1109
16
            }
1110
28
            _key_encoder.append_rowid_suffix(&key, pos);
1111
28
            primary_keys.emplace_back(std::move(key));
1112
28
        }
1113
        // 2. sort primary keys
1114
9
        std::sort(primary_keys.begin(), primary_keys.end());
1115
        // 3. write primary keys index
1116
9
        std::string last_key;
1117
28
        for (const auto& key : primary_keys) {
1118
28
            DCHECK(key.compare(last_key) > 0)
1119
0
                    << "found duplicate key or key is not sorted! current key: " << key
1120
0
                    << ", last key: " << last_key;
1121
28
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1122
28
            last_key = key;
1123
28
        }
1124
9
    }
1125
37
    return Status::OK();
1126
37
}
1127
1128
Status VerticalSegmentWriter::_generate_short_key_index(
1129
        std::vector<IOlapColumnDataAccessor*>& key_columns, size_t num_rows,
1130
100
        const std::vector<size_t>& short_key_pos) {
1131
100
    _set_min_key(_key_encoder.full_encode(key_columns, 0));
1132
100
    _set_max_key(_key_encoder.full_encode(key_columns, num_rows - 1));
1133
100
    DCHECK(Slice(_max_key.data(), _max_key.size())
1134
0
                   .compare(Slice(_min_key.data(), _min_key.size())) >= 0)
1135
0
            << "key is not sorted! min key: " << _min_key << ", max key: " << _max_key;
1136
1137
100
    key_columns.resize(_num_short_key_columns);
1138
100
    std::string last_key;
1139
100
    for (const auto pos : short_key_pos) {
1140
100
        std::string key = _key_encoder.encode_short_keys(key_columns, pos);
1141
100
        DCHECK(key.compare(last_key) >= 0)
1142
0
                << "key is not sorted! current key: " << key << ", last key: " << last_key;
1143
100
        RETURN_IF_ERROR(_short_key_index_builder->add_item(key));
1144
100
        last_key = std::move(key);
1145
100
    }
1146
100
    return Status::OK();
1147
100
}
1148
1149
// TODO(lingbin): Currently this function does not include the size of various indexes,
1150
// We should make this more precise.
1151
34
uint64_t VerticalSegmentWriter::_estimated_remaining_size() {
1152
    // footer_size(4) + checksum(4) + segment_magic(4)
1153
34
    uint64_t size = 12;
1154
34
    if (_is_mow_with_cluster_key()) {
1155
1
        size += _primary_key_index_builder->size() + _short_key_index_builder->size();
1156
33
    } else if (_is_mow()) {
1157
24
        size += _primary_key_index_builder->size();
1158
24
    } else {
1159
9
        size += _short_key_index_builder->size();
1160
9
    }
1161
1162
    // update the mem_tracker of segment size
1163
34
    _mem_tracker->consume(size - _mem_tracker->consumption());
1164
34
    return size;
1165
34
}
1166
1167
136
Status VerticalSegmentWriter::finalize_columns_index(uint64_t* index_size) {
1168
136
    uint64_t index_start = _file_writer->bytes_appended();
1169
    // Record the common index range for cloud index-only file-cache preload.
1170
    // This VerticalSegmentWriter path is used when cloud load, compaction, or schema change flushes
1171
    // a whole block through SegmentCreator with enable_vertical_segment_writer enabled.
1172
136
    RETURN_IF_ERROR(_write_ordinal_index());
1173
136
    RETURN_IF_ERROR(_write_zone_map());
1174
136
    RETURN_IF_ERROR(_write_inverted_index());
1175
136
    RETURN_IF_ERROR(_write_ann_index());
1176
136
    RETURN_IF_ERROR(_write_bloom_filter_index());
1177
1178
136
    *index_size = _file_writer->bytes_appended() - index_start;
1179
136
    if (_is_mow_with_cluster_key()) {
1180
9
        RETURN_IF_ERROR(_write_short_key_index());
1181
9
        *index_size = _file_writer->bytes_appended() - index_start;
1182
9
        RETURN_IF_ERROR(_write_primary_key_index());
1183
9
        *index_size += _primary_key_index_builder->disk_size();
1184
127
    } else if (_is_mow()) {
1185
36
        RETURN_IF_ERROR(_write_primary_key_index());
1186
        // IndexedColumnWriter write data pages mixed with segment data, we should use
1187
        // the stat from primary key index builder.
1188
36
        *index_size += _primary_key_index_builder->disk_size();
1189
91
    } else {
1190
91
        RETURN_IF_ERROR(_write_short_key_index());
1191
91
        *index_size = _file_writer->bytes_appended() - index_start;
1192
91
    }
1193
136
    uint64_t file_index_end = _file_writer->bytes_appended();
1194
136
    _index_file_cache_info.add_index_range(index_start, file_index_end - index_start);
1195
1196
    // reset all column writers and data_conveter
1197
136
    clear();
1198
1199
136
    return Status::OK();
1200
136
}
1201
1202
Status VerticalSegmentWriter::finalize_footer(uint64_t* segment_file_size,
1203
136
                                              SegmentIndexFileCacheInfo* index_file_cache_info) {
1204
136
    uint64_t footer_start = _file_writer->bytes_appended();
1205
136
    RETURN_IF_ERROR(_write_footer());
1206
    // finish
1207
136
    RETURN_IF_ERROR(_file_writer->close(true));
1208
136
    *segment_file_size = _file_writer->bytes_appended();
1209
    // The closed size completes the preload range recorded above. SegmentIndexFileCacheLoader
1210
    // later decides whether this is a remote cloud rowset that should actually be preloaded.
1211
136
    _index_file_cache_info.segment_file_size = *segment_file_size;
1212
136
    _index_file_cache_info.add_index_range(footer_start, *segment_file_size - footer_start);
1213
136
    if (index_file_cache_info != nullptr) {
1214
136
        *index_file_cache_info = _index_file_cache_info;
1215
136
    }
1216
136
    if (*segment_file_size == 0) {
1217
0
        return Status::Corruption("Bad segment, file size = 0");
1218
0
    }
1219
136
    return Status::OK();
1220
136
}
1221
1222
Status VerticalSegmentWriter::finalize(uint64_t* segment_file_size, uint64_t* index_size,
1223
136
                                       SegmentIndexFileCacheInfo* index_file_cache_info) {
1224
136
    MonotonicStopWatch timer;
1225
136
    timer.start();
1226
    // check disk capacity
1227
136
    if (_data_dir != nullptr &&
1228
136
        _data_dir->reach_capacity_limit((int64_t)_estimated_remaining_size())) {
1229
0
        return Status::Error<DISK_REACH_CAPACITY_LIMIT>("disk {} exceed capacity limit.",
1230
0
                                                        _data_dir->path_hash());
1231
0
    }
1232
136
    _row_count = _num_rows_written;
1233
136
    _num_rows_written = 0;
1234
    // write index
1235
136
    RETURN_IF_ERROR(finalize_columns_index(index_size));
1236
    // write footer
1237
136
    RETURN_IF_ERROR(finalize_footer(segment_file_size, index_file_cache_info));
1238
1239
136
    if (timer.elapsed_time() > 5000000000L) {
1240
0
        LOG(INFO) << "segment flush consumes a lot time_ns " << timer.elapsed_time()
1241
0
                  << ", segmemt_size " << *segment_file_size;
1242
0
    }
1243
136
    return Status::OK();
1244
136
}
1245
1246
136
void VerticalSegmentWriter::clear() {
1247
1.77k
    for (auto& column_writer : _column_writers) {
1248
1.77k
        column_writer.reset();
1249
1.77k
    }
1250
136
    _column_writers.clear();
1251
136
    _olap_data_convertor.reset();
1252
136
}
1253
1254
// write ordinal index after data has been written
1255
136
Status VerticalSegmentWriter::_write_ordinal_index() {
1256
1.77k
    for (auto& column_writer : _column_writers) {
1257
1.77k
        RETURN_IF_ERROR(column_writer->write_ordinal_index());
1258
1.77k
    }
1259
136
    return Status::OK();
1260
136
}
1261
1262
136
Status VerticalSegmentWriter::_write_zone_map() {
1263
1.77k
    for (auto& column_writer : _column_writers) {
1264
1.77k
        RETURN_IF_ERROR(column_writer->write_zone_map());
1265
1.77k
    }
1266
136
    return Status::OK();
1267
136
}
1268
1269
136
Status VerticalSegmentWriter::_write_inverted_index() {
1270
1.77k
    for (auto& column_writer : _column_writers) {
1271
1.77k
        RETURN_IF_ERROR(column_writer->write_inverted_index());
1272
1.77k
    }
1273
136
    return Status::OK();
1274
136
}
1275
1276
136
Status VerticalSegmentWriter::_write_ann_index() {
1277
1.77k
    for (auto& column_writer : _column_writers) {
1278
1.77k
        RETURN_IF_ERROR(column_writer->write_ann_index());
1279
1.77k
    }
1280
136
    return Status::OK();
1281
136
}
1282
1283
136
Status VerticalSegmentWriter::_write_bloom_filter_index() {
1284
1.77k
    for (auto& column_writer : _column_writers) {
1285
1.77k
        RETURN_IF_ERROR(column_writer->write_bloom_filter_index());
1286
1.77k
    }
1287
136
    return Status::OK();
1288
136
}
1289
1290
100
Status VerticalSegmentWriter::_write_short_key_index() {
1291
100
    std::vector<Slice> body;
1292
100
    PageFooterPB footer;
1293
100
    RETURN_IF_ERROR(_short_key_index_builder->finalize(_row_count, &body, &footer));
1294
100
    PagePointer pp;
1295
    // short key index page is not compressed right now
1296
100
    RETURN_IF_ERROR(PageIO::write_page(_file_writer, body, footer, &pp));
1297
100
    pp.to_proto(_footer.mutable_short_key_index_page());
1298
100
    return Status::OK();
1299
100
}
1300
1301
45
Status VerticalSegmentWriter::_write_primary_key_index() {
1302
45
    CHECK_EQ(_primary_key_index_builder->num_rows(), _row_count);
1303
45
    return _primary_key_index_builder->finalize(_footer.mutable_primary_key_index_meta());
1304
45
}
1305
1306
136
Status VerticalSegmentWriter::_write_footer() {
1307
136
    _footer.set_num_rows(_row_count);
1308
1309
    // Decide whether to externalize ColumnMetaPB by tablet default, and stamp footer version
1310
1311
136
    if (_tablet_schema->storage_format() == TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V3) {
1312
32
        _footer.set_version(SEGMENT_FOOTER_VERSION_V3_EXT_COL_META);
1313
32
        VLOG_DEBUG << "use external column meta";
1314
        // External ColumnMetaPB writing (optional)
1315
32
        RETURN_IF_ERROR(ExternalColMetaUtil::write_external_column_meta(
1316
32
                _file_writer, &_footer, _opts.compression_type,
1317
32
                [this](const std::vector<Slice>& slices) { return _write_raw_data(slices); }));
1318
32
    }
1319
1320
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
1321
136
    VLOG_DEBUG << "footer " << _footer.DebugString();
1322
136
    std::string footer_buf;
1323
136
    if (!_footer.SerializeToString(&footer_buf)) {
1324
0
        return Status::InternalError("failed to serialize segment footer");
1325
0
    }
1326
1327
136
    faststring fixed_buf;
1328
    // footer's size
1329
136
    put_fixed32_le(&fixed_buf, cast_set<uint32_t>(footer_buf.size()));
1330
    // footer's checksum
1331
136
    uint32_t checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
1332
136
    put_fixed32_le(&fixed_buf, checksum);
1333
    // Append magic number. we don't write magic number in the header because
1334
    // that will need an extra seek when reading
1335
136
    fixed_buf.append(k_segment_magic, k_segment_magic_length);
1336
1337
136
    std::vector<Slice> slices {footer_buf, fixed_buf};
1338
136
    return _write_raw_data(slices);
1339
136
}
1340
1341
760
Status VerticalSegmentWriter::_write_raw_data(const std::vector<Slice>& slices) {
1342
760
    RETURN_IF_ERROR(_file_writer->appendv(&slices[0], slices.size()));
1343
760
    return Status::OK();
1344
760
}
1345
1346
136
Slice VerticalSegmentWriter::min_encoded_key() {
1347
136
    return (_primary_key_index_builder == nullptr) ? Slice(_min_key.data(), _min_key.size())
1348
136
                                                   : _primary_key_index_builder->min_key();
1349
136
}
1350
136
Slice VerticalSegmentWriter::max_encoded_key() {
1351
136
    return (_primary_key_index_builder == nullptr) ? Slice(_max_key.data(), _max_key.size())
1352
136
                                                   : _primary_key_index_builder->max_key();
1353
136
}
1354
1355
0
void VerticalSegmentWriter::_set_min_max_key(const Slice& key) {
1356
0
    if (UNLIKELY(_is_first_row)) {
1357
0
        _min_key.append(key.get_data(), key.get_size());
1358
0
        _is_first_row = false;
1359
0
    }
1360
0
    if (key.compare(_max_key) > 0) {
1361
0
        _max_key.clear();
1362
0
        _max_key.append(key.get_data(), key.get_size());
1363
0
    }
1364
0
}
1365
1366
100
void VerticalSegmentWriter::_set_min_key(const Slice& key) {
1367
100
    if (UNLIKELY(_is_first_row)) {
1368
100
        _min_key.append(key.get_data(), key.get_size());
1369
100
        _is_first_row = false;
1370
100
    }
1371
100
}
1372
1373
100
void VerticalSegmentWriter::_set_max_key(const Slice& key) {
1374
100
    _max_key.clear();
1375
100
    _max_key.append(key.get_data(), key.get_size());
1376
100
}
1377
1378
} // namespace doris::segment_v2