Coverage Report

Created: 2026-04-10 04:05

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