Coverage Report

Created: 2026-08-10 15:19

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