Coverage Report

Created: 2026-07-27 03:07

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