Coverage Report

Created: 2026-05-25 21:24

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