Coverage Report

Created: 2026-05-28 14:31

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