Coverage Report

Created: 2026-05-18 03:48

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