Coverage Report

Created: 2026-08-13 19:37

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
        const auto& input_column = data.block->get_by_position(input_id++);
512
260
        auto& full_column = full_block.get_by_position(i);
513
260
        full_column.column = input_column.column;
514
260
        full_column.type = input_column.type;
515
260
    }
516
517
12
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
518
12
        _tablet_schema->num_variant_columns() > 0) {
519
4
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
520
4
                full_block, *_tablet_schema, including_cids));
521
4
    }
522
12
    bool have_input_seq_column = false;
523
    // write including columns
524
12
    std::vector<IOlapColumnDataAccessor*> key_columns;
525
12
    IOlapColumnDataAccessor* seq_column = nullptr;
526
12
    uint32_t segment_start_pos = 0;
527
260
    for (auto cid : including_cids) {
528
260
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
529
260
        RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
530
260
                &full_block, data.row_pos, data.num_rows, std::vector<uint32_t> {cid}));
531
        // here we get segment column row num before append data.
532
260
        segment_start_pos = cast_set<uint32_t>(_column_writers[cid]->get_next_rowid());
533
        // olap data convertor alway start from id = 0
534
260
        auto [status, column] = _olap_data_convertor->convert_column_data(cid);
535
260
        if (!status.ok()) {
536
0
            return status;
537
0
        }
538
260
        if (cid < _key_encoder.num_sort_key_columns()) {
539
240
            key_columns.push_back(column);
540
240
        } else if (_tablet_schema->has_sequence_col() &&
541
20
                   cid == _tablet_schema->sequence_col_idx()) {
542
4
            seq_column = column;
543
4
            have_input_seq_column = true;
544
4
        }
545
260
        RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
546
260
                                                     data.num_rows));
547
260
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
548
        // Don't clear source content for key columns and sequence column here,
549
        // as they will be used later for key encoding and _generate_primary_key_index().
550
        // They will be cleared at the end of this method.
551
260
        bool is_key_column = (cid < _key_encoder.num_sort_key_columns());
552
260
        bool is_seq_column = (_tablet_schema->has_sequence_col() &&
553
260
                              cid == _tablet_schema->sequence_col_idx() && have_input_seq_column);
554
260
        if (!is_key_column && !is_seq_column) {
555
16
            _olap_data_convertor->clear_source_content(cid);
556
16
        }
557
260
    }
558
559
12
    bool has_default_or_nullable = false;
560
12
    std::vector<bool> use_default_or_null_flag;
561
12
    use_default_or_null_flag.reserve(data.num_rows);
562
12
    const auto* delete_signs =
563
12
            BaseTablet::get_delete_sign_column_data(full_block, data.row_pos + data.num_rows);
564
565
12
    DBUG_EXECUTE_IF("VerticalSegmentWriter._append_block_with_partial_content.sleep",
566
12
                    { sleep(60); })
567
12
    const std::vector<RowsetSharedPtr>& specified_rowsets = _mow_context->rowset_ptrs;
568
12
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
569
570
12
    MowKeyProbe probe = MowKeyProbe::for_partial_update(
571
12
            _tablet.get(), _tablet_schema.get(), _tablet_schema->has_sequence_col(), _mow_context,
572
12
            _opts.rowset_ctx->rowset_id, _segment_id, /*flexible=*/false);
573
    // owns the rowset pins and the read plan for the historical read below
574
12
    HistoricalRowFetcher fetcher {_opts.rowset_ctx->make_historical_row_retriever_context()};
575
576
    // locate rows in base data
577
12
    PartialUpdateStats stats;
578
579
48
    for (size_t block_pos = data.row_pos; block_pos < data.row_pos + data.num_rows; block_pos++) {
580
        // block   segment
581
        //   2   ->   0
582
        //   3   ->   1
583
        //   4   ->   2
584
        //   5   ->   3
585
        // here row_pos = 2, num_rows = 4.
586
36
        size_t delta_pos = block_pos - data.row_pos;
587
36
        size_t segment_pos = segment_start_pos + delta_pos;
588
36
        std::string key = encode_mow_key_invalidate_cache(
589
36
                _key_encoder, key_columns, seq_column, delta_pos, have_input_seq_column,
590
36
                _opts.rowset_ctx->tablet_id, *_tablet_schema, _opts.write_type);
591
        // If the table have sequence column, and the include-cids don't contain the sequence
592
        // column, we need to update the primary key index builder at the end of this method.
593
        // At that time, we have a valid sequence column to encode the key with seq col.
594
36
        if (!_tablet_schema->has_sequence_col() || have_input_seq_column) {
595
24
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
596
24
        }
597
598
        // mark key with delete sign as deleted.
599
36
        bool have_delete_sign = (delete_signs != nullptr && delete_signs[block_pos] != 0);
600
601
36
        auto not_found_cb = [&]() {
602
12
            return _opts.rowset_ctx->partial_update_info->handle_new_key(
603
12
                    *_tablet_schema, [&]() -> std::string {
604
0
                        return data.block->dump_one_line(
605
0
                                block_pos, cast_set<int>(_key_encoder.num_sort_key_columns()));
606
0
                    });
607
12
        };
608
36
        auto update_read_plan = [&](const RowLocation& loc, const RowsetSharedPtr& rowset) {
609
            // keep the rowset alive until the historical read below is done
610
24
            fetcher.pin_rowset(rowset);
611
24
            fetcher.plan_fixed_read(loc, segment_pos);
612
24
        };
613
36
        RETURN_IF_ERROR(_probe_key_for_mow(
614
36
                probe, std::move(key), segment_pos, have_input_seq_column, have_delete_sign,
615
36
                specified_rowsets, segment_caches, has_default_or_nullable,
616
36
                use_default_or_null_flag, update_read_plan, not_found_cb, stats));
617
36
    }
618
12
    CHECK_EQ(use_default_or_null_flag.size(), data.num_rows);
619
620
12
    if (config::enable_merge_on_write_correctness_check) {
621
12
        _tablet->add_sentinel_mark_to_delete_bitmap(_mow_context->delete_bitmap.get(),
622
12
                                                    *_mow_context->rowset_ids);
623
12
    }
624
625
    // read to fill full_block
626
12
    RETURN_IF_ERROR(fetcher.fill_missing_columns(*_tablet_schema, full_block,
627
12
                                                 use_default_or_null_flag, has_default_or_nullable,
628
12
                                                 segment_start_pos, data.block));
629
630
12
    if (_tablet_schema->num_variant_columns() > 0) {
631
4
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
632
4
                full_block, *_tablet_schema, _opts.rowset_ctx->partial_update_info->missing_cids));
633
4
    }
634
635
    // convert missing columns and send to column writer
636
12
    const auto& missing_cids = _opts.rowset_ctx->partial_update_info->missing_cids;
637
48
    for (auto cid : missing_cids) {
638
48
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
639
48
        if (_tablet_schema->column(cid).is_row_store_column()) {
640
4
            RETURN_IF_ERROR(_append_row_store_column(full_block, data.row_pos, data.num_rows, cid));
641
4
            RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
642
4
            continue;
643
4
        }
644
44
        RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
645
44
                &full_block, data.row_pos, data.num_rows, std::vector<uint32_t> {cid}));
646
44
        auto [status, column] = _olap_data_convertor->convert_column_data(cid);
647
44
        if (!status.ok()) {
648
0
            return status;
649
0
        }
650
44
        if (_tablet_schema->has_sequence_col() && !have_input_seq_column &&
651
44
            cid == _tablet_schema->sequence_col_idx()) {
652
4
            DCHECK_EQ(seq_column, nullptr);
653
4
            seq_column = column;
654
4
        }
655
44
        RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
656
44
                                                     data.num_rows));
657
44
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
658
        // Don't clear source content for sequence column here if it will be used later
659
        // in _generate_primary_key_index(). It will be cleared at the end of this method.
660
44
        bool is_seq_column = (_tablet_schema->has_sequence_col() && !have_input_seq_column &&
661
44
                              cid == _tablet_schema->sequence_col_idx());
662
44
        if (!is_seq_column) {
663
40
            _olap_data_convertor->clear_source_content(cid);
664
40
        }
665
44
    }
666
667
12
    _num_rows_updated += stats.num_rows_updated;
668
12
    _num_rows_deleted += stats.num_rows_deleted;
669
12
    _num_rows_new_added += stats.num_rows_new_added;
670
12
    _num_rows_filtered += stats.num_rows_filtered;
671
12
    if (_tablet_schema->has_sequence_col() && !have_input_seq_column) {
672
4
        DCHECK_NE(seq_column, nullptr);
673
4
        if (_num_rows_written != data.row_pos ||
674
4
            _primary_key_index_builder->num_rows() != _num_rows_written) {
675
0
            return Status::InternalError(
676
0
                    "Correctness check failed, _num_rows_written: {}, row_pos: {}, primary key "
677
0
                    "index builder num rows: {}",
678
0
                    _num_rows_written, data.row_pos, _primary_key_index_builder->num_rows());
679
0
        }
680
4
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, data.num_rows, false));
681
4
    }
682
683
12
    _num_rows_written += data.num_rows;
684
12
    DCHECK_EQ(_primary_key_index_builder->num_rows(), _num_rows_written)
685
0
            << "primary key index builder num rows(" << _primary_key_index_builder->num_rows()
686
0
            << ") not equal to segment writer's num rows written(" << _num_rows_written << ")";
687
12
    _olap_data_convertor->clear_source_content();
688
12
    return Status::OK();
689
12
}
690
691
Status VerticalSegmentWriter::_append_block_with_flexible_partial_content(RowsInBlock& data,
692
8
                                                                          Block& full_block) {
693
8
    RETURN_IF_ERROR(_partial_update_preconditions_check(data.row_pos, true));
694
695
    // data.block has the same schema with full_block
696
8
    DCHECK(data.block->columns() == _tablet_schema->num_columns());
697
698
    // create full block and fill with sort key columns
699
8
    full_block = _tablet_schema->create_block();
700
701
    // Use _num_rows_written instead of creating column writer 0, since all column writers
702
    // should have the same row count, which equals _num_rows_written.
703
8
    uint32_t segment_start_pos = cast_set<uint32_t>(_num_rows_written);
704
705
8
    DCHECK(_tablet_schema->has_skip_bitmap_col());
706
8
    auto skip_bitmap_col_idx = _tablet_schema->skip_bitmap_col_idx();
707
708
8
    bool has_default_or_nullable = false;
709
8
    std::vector<bool> use_default_or_null_flag;
710
8
    use_default_or_null_flag.reserve(data.num_rows);
711
712
8
    int32_t seq_map_col_unique_id = _opts.rowset_ctx->partial_update_info->sequence_map_col_uid();
713
8
    bool schema_has_sequence_col = _tablet_schema->has_sequence_col();
714
715
8
    DBUG_EXECUTE_IF("VerticalSegmentWriter._append_block_with_flexible_partial_content.sleep",
716
8
                    { sleep(60); })
717
8
    const std::vector<RowsetSharedPtr>& specified_rowsets = _mow_context->rowset_ptrs;
718
8
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
719
720
    // Ensure all primary key column writers and sequence column writer are created before
721
    // aggregate_for_flexible_partial_update, because it internally calls convert_pk_columns
722
    // and convert_seq_column which need the convertors in _olap_data_convertor
723
168
    for (uint32_t cid = 0; cid < _tablet_schema->num_key_columns(); ++cid) {
724
160
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
725
160
    }
726
8
    if (schema_has_sequence_col) {
727
4
        uint32_t cid = _tablet_schema->sequence_col_idx();
728
4
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
729
4
    }
730
731
    // 1. aggregate duplicate rows in block
732
8
    RETURN_IF_ERROR(_block_aggregator.aggregate_for_flexible_partial_update(
733
8
            const_cast<Block*>(data.block), data.num_rows, specified_rowsets, segment_caches));
734
8
    if (data.block->rows() != data.num_rows) {
735
8
        data.num_rows = data.block->rows();
736
8
        _olap_data_convertor->clear_source_content();
737
8
    }
738
739
    // 2. encode primary key columns
740
    // we can only encode primary key columns currently becasue all non-primary columns in flexible partial update
741
    // can have missing cells
742
8
    std::vector<IOlapColumnDataAccessor*> key_columns {};
743
8
    RETURN_IF_ERROR(_block_aggregator.convert_pk_columns(const_cast<Block*>(data.block),
744
8
                                                         data.row_pos, data.num_rows, key_columns));
745
    // 3. encode sequence column
746
    // We encode the seguence column even thought it may have invalid values in some rows because we need to
747
    // encode the value of sequence column in key for rows that have a valid value in sequence column during
748
    // lookup_raw_key. We will encode the sequence column again at the end of this method. At that time, we have
749
    // a valid sequence column to encode the key with seq col.
750
8
    IOlapColumnDataAccessor* seq_column {nullptr};
751
8
    RETURN_IF_ERROR(_block_aggregator.convert_seq_column(const_cast<Block*>(data.block),
752
8
                                                         data.row_pos, data.num_rows, seq_column));
753
754
8
    auto* mutable_block = const_cast<Block*>(data.block);
755
8
    std::vector<BitmapValue>* skip_bitmaps =
756
8
            &get_mutable_skip_bitmap_column(mutable_block, skip_bitmap_col_idx)->get_data();
757
8
    const auto* delete_signs =
758
8
            BaseTablet::get_delete_sign_column_data(*data.block, data.row_pos + data.num_rows);
759
8
    DCHECK(delete_signs != nullptr);
760
761
168
    for (std::size_t cid {0}; cid < _tablet_schema->num_key_columns(); cid++) {
762
160
        const auto& input_column = data.block->get_by_position(cid);
763
160
        auto& full_column = full_block.get_by_position(cid);
764
160
        full_column.column = input_column.column;
765
160
        full_column.type = input_column.type;
766
160
    }
767
768
    // 4. write primary key columns data
769
168
    for (std::size_t cid {0}; cid < _tablet_schema->num_key_columns(); cid++) {
770
160
        const auto& column = key_columns[cid];
771
160
        DCHECK(_column_writers[cid]->get_next_rowid() == _num_rows_written);
772
160
        RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
773
160
                                                     data.num_rows));
774
160
        DCHECK(_column_writers[cid]->get_next_rowid() == _num_rows_written + data.num_rows);
775
160
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
776
160
    }
777
778
    // 5. genreate read plan
779
8
    FlexibleReadPlan read_plan {_tablet_schema->has_row_store_for_all_columns()};
780
8
    PartialUpdateStats stats;
781
8
    RETURN_IF_ERROR(_generate_flexible_read_plan(
782
8
            read_plan, data, segment_start_pos, schema_has_sequence_col, seq_map_col_unique_id,
783
8
            skip_bitmaps, key_columns, seq_column, delete_signs, specified_rowsets, segment_caches,
784
8
            has_default_or_nullable, use_default_or_null_flag, stats));
785
8
    CHECK_EQ(use_default_or_null_flag.size(), data.num_rows);
786
787
8
    if (config::enable_merge_on_write_correctness_check) {
788
8
        _tablet->add_sentinel_mark_to_delete_bitmap(_mow_context->delete_bitmap.get(),
789
8
                                                    *_mow_context->rowset_ids);
790
8
    }
791
792
    // 6. read according plan to fill full_block
793
8
    RETURN_IF_ERROR(read_plan.fill_non_primary_key_columns(
794
8
            _opts.rowset_ctx->make_historical_row_retriever_context(), _rsid_to_rowset,
795
8
            *_tablet_schema, full_block, use_default_or_null_flag, has_default_or_nullable,
796
8
            segment_start_pos, cast_set<uint32_t>(data.row_pos), data.block, skip_bitmaps));
797
798
    // TODO(bobhan1): should we replace the skip bitmap column with empty bitmaps to reduce storage occupation?
799
    // this column is not needed in read path for merge-on-write table
800
801
    // 7. fill row store column
802
56
    for (auto cid = _tablet_schema->num_key_columns(); cid < _tablet_schema->num_columns(); cid++) {
803
48
        if (!_tablet_schema->column(cid).is_row_store_column()) {
804
44
            continue;
805
44
        }
806
4
        RETURN_IF_ERROR(_create_column_writer(cast_set<uint32_t>(cid), _tablet_schema->column(cid),
807
4
                                              _tablet_schema));
808
4
        RETURN_IF_ERROR(_append_row_store_column(full_block, data.row_pos, data.num_rows,
809
4
                                                 cast_set<uint32_t>(cid)));
810
4
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
811
4
    }
812
813
8
    std::vector<uint32_t> column_ids;
814
216
    for (uint32_t i = 0; i < _tablet_schema->num_columns(); ++i) {
815
208
        column_ids.emplace_back(i);
816
208
    }
817
8
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
818
8
        _tablet_schema->num_variant_columns() > 0) {
819
0
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
820
0
                full_block, *_tablet_schema, column_ids));
821
0
    }
822
823
    // 8. encode and write all non-primary key columns(including sequence column if exists)
824
56
    for (auto cid = _tablet_schema->num_key_columns(); cid < _tablet_schema->num_columns(); cid++) {
825
48
        if (_tablet_schema->column(cid).is_row_store_column()) {
826
4
            continue;
827
4
        }
828
44
        if (cid != _tablet_schema->sequence_col_idx()) {
829
40
            RETURN_IF_ERROR(_create_column_writer(cast_set<uint32_t>(cid),
830
40
                                                  _tablet_schema->column(cid), _tablet_schema));
831
40
        }
832
44
        RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_column(
833
44
                full_block.get_by_position(cid), data.row_pos, data.num_rows,
834
44
                cast_set<uint32_t>(cid)));
835
44
        auto [status, column] = _olap_data_convertor->convert_column_data(cid);
836
44
        if (!status.ok()) {
837
0
            return status;
838
0
        }
839
44
        if (cid == _tablet_schema->sequence_col_idx()) {
840
            // should use the latest encoded sequence column to build the primary index
841
4
            seq_column = column;
842
4
        }
843
44
        DCHECK(_column_writers[cid]->get_next_rowid() == _num_rows_written);
844
44
        RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
845
44
                                                     data.num_rows));
846
44
        DCHECK(_column_writers[cid]->get_next_rowid() == _num_rows_written + data.num_rows);
847
44
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
848
44
    }
849
850
8
    _num_rows_updated += stats.num_rows_updated;
851
8
    _num_rows_deleted += stats.num_rows_deleted;
852
8
    _num_rows_new_added += stats.num_rows_new_added;
853
8
    _num_rows_filtered += stats.num_rows_filtered;
854
855
8
    if (_num_rows_written != data.row_pos ||
856
8
        _primary_key_index_builder->num_rows() != _num_rows_written) {
857
0
        return Status::InternalError(
858
0
                "Correctness check failed, _num_rows_written: {}, row_pos: {}, primary key "
859
0
                "index builder num rows: {}",
860
0
                _num_rows_written, data.row_pos, _primary_key_index_builder->num_rows());
861
0
    }
862
863
    // 9. build primary key index
864
8
    RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, data.num_rows, false));
865
866
8
    _num_rows_written += data.num_rows;
867
8
    DCHECK_EQ(_primary_key_index_builder->num_rows(), _num_rows_written)
868
0
            << "primary key index builder num rows(" << _primary_key_index_builder->num_rows()
869
0
            << ") not equal to segment writer's num rows written(" << _num_rows_written << ")";
870
8
    _olap_data_convertor->clear_source_content();
871
8
    return Status::OK();
872
8
}
873
874
Status VerticalSegmentWriter::_generate_encoded_default_seq_value(const TabletSchema& tablet_schema,
875
                                                                  const PartialUpdateInfo& info,
876
0
                                                                  std::string* encoded_value) {
877
0
    const auto& seq_column = tablet_schema.column(tablet_schema.sequence_col_idx());
878
0
    auto block = tablet_schema.create_block_by_cids(
879
0
            {cast_set<uint32_t>(tablet_schema.sequence_col_idx())});
880
0
    if (seq_column.has_default_value()) {
881
0
        auto idx = tablet_schema.sequence_col_idx() - tablet_schema.num_key_columns();
882
0
        const auto& default_value = info.default_values[idx];
883
0
        StringRef str {default_value};
884
0
        RETURN_IF_ERROR(block.get_by_position(0).type->get_serde()->default_from_string(
885
0
                str, *block.get_by_position(0).column->assert_mutable().get()));
886
887
0
    } else {
888
0
        block.get_by_position(0).column->assert_mutable()->insert_default();
889
0
    }
890
0
    DCHECK_EQ(block.rows(), 1);
891
0
    auto olap_data_convertor = std::make_unique<OlapBlockDataConvertor>();
892
0
    olap_data_convertor->add_column_data_convertor(seq_column);
893
0
    olap_data_convertor->set_source_content(&block, 0, 1);
894
0
    auto [status, column] = olap_data_convertor->convert_column_data(0);
895
0
    if (!status.ok()) {
896
0
        return status;
897
0
    }
898
    // include marker
899
0
    _key_encoder.append_seq_suffix(encoded_value, column, 0);
900
0
    return Status::OK();
901
0
}
902
903
Status VerticalSegmentWriter::_generate_flexible_read_plan(
904
        FlexibleReadPlan& read_plan, RowsInBlock& data, size_t segment_start_pos,
905
        bool schema_has_sequence_col, int32_t seq_map_col_unique_id,
906
        std::vector<BitmapValue>* skip_bitmaps,
907
        const std::vector<IOlapColumnDataAccessor*>& key_columns,
908
        IOlapColumnDataAccessor* seq_column, const signed char* delete_signs,
909
        const std::vector<RowsetSharedPtr>& specified_rowsets,
910
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
911
        bool& has_default_or_nullable, std::vector<bool>& use_default_or_null_flag,
912
8
        PartialUpdateStats& stats) {
913
8
    int32_t delete_sign_col_unique_id =
914
8
            _tablet_schema->column(_tablet_schema->delete_sign_idx()).unique_id();
915
8
    int32_t seq_col_unique_id =
916
8
            (_tablet_schema->has_sequence_col()
917
8
                     ? _tablet_schema->column(_tablet_schema->sequence_col_idx()).unique_id()
918
8
                     : -1);
919
8
    MowKeyProbe probe = MowKeyProbe::for_partial_update(
920
8
            _tablet.get(), _tablet_schema.get(), _tablet_schema->has_sequence_col(), _mow_context,
921
8
            _opts.rowset_ctx->rowset_id, _segment_id, /*flexible=*/true);
922
32
    for (size_t block_pos = data.row_pos; block_pos < data.row_pos + data.num_rows; block_pos++) {
923
24
        size_t delta_pos = block_pos - data.row_pos;
924
24
        size_t segment_pos = segment_start_pos + delta_pos;
925
24
        auto& skip_bitmap = skip_bitmaps->at(block_pos);
926
927
24
        bool row_has_sequence_col =
928
24
                (schema_has_sequence_col && !skip_bitmap.contains(seq_col_unique_id));
929
24
        std::string key = encode_mow_key_invalidate_cache(
930
24
                _key_encoder, key_columns, seq_column, delta_pos, row_has_sequence_col,
931
24
                _opts.rowset_ctx->tablet_id, *_tablet_schema, _opts.write_type);
932
933
        // mark key with delete sign as deleted.
934
24
        bool have_delete_sign =
935
24
                (!skip_bitmap.contains(delete_sign_col_unique_id) && delete_signs[block_pos] != 0);
936
937
24
        auto not_found_cb = [&]() {
938
8
            return _opts.rowset_ctx->partial_update_info->handle_new_key(
939
8
                    *_tablet_schema,
940
8
                    [&]() -> std::string {
941
0
                        return data.block->dump_one_line(
942
0
                                block_pos, cast_set<int>(_key_encoder.num_sort_key_columns()));
943
0
                    },
944
8
                    &skip_bitmap);
945
8
        };
946
24
        auto update_read_plan = [&](const RowLocation& loc, const RowsetSharedPtr& rowset) {
947
            // the flexible fill still reads through the writer's pin map, which the block
948
            // aggregator also feeds
949
8
            _rsid_to_rowset.emplace(rowset->rowset_id(), rowset);
950
8
            read_plan.prepare_to_read(loc, segment_pos, skip_bitmap);
951
8
        };
952
953
24
        RETURN_IF_ERROR(_probe_key_for_mow(probe, std::move(key), segment_pos, row_has_sequence_col,
954
24
                                           have_delete_sign, specified_rowsets, segment_caches,
955
24
                                           has_default_or_nullable, use_default_or_null_flag,
956
24
                                           update_read_plan, not_found_cb, stats));
957
24
    }
958
8
    return Status::OK();
959
8
}
960
961
137
Status VerticalSegmentWriter::batch_block(const Block* block, size_t row_pos, size_t num_rows) {
962
137
    if (_opts.rowset_ctx->partial_update_info &&
963
137
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
964
137
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
965
137
        !_opts.rowset_ctx->is_transient_rowset_writer) {
966
20
        if (_opts.rowset_ctx->partial_update_info->is_flexible_partial_update()) {
967
8
            if (block->columns() != _tablet_schema->num_columns()) {
968
0
                return Status::InvalidArgument(
969
0
                        "illegal flexible partial update block columns, block columns = {}, "
970
0
                        "tablet_schema columns = {}",
971
0
                        block->dump_structure(), _tablet_schema->dump_structure());
972
0
            }
973
12
        } else {
974
12
            if (block->columns() < _tablet_schema->num_key_columns() ||
975
12
                block->columns() >= _tablet_schema->num_columns()) {
976
0
                return Status::InvalidArgument(fmt::format(
977
0
                        "illegal partial update block columns: {}, num key columns: {}, total "
978
0
                        "schema columns: {}",
979
0
                        block->columns(), _tablet_schema->num_key_columns(),
980
0
                        _tablet_schema->num_columns()));
981
0
            }
982
12
        }
983
117
    } else if (block->columns() != _tablet_schema->num_columns()) {
984
0
        return Status::InvalidArgument(
985
0
                "illegal block columns, block columns = {}, tablet_schema columns = {}",
986
0
                block->dump_structure(), _tablet_schema->dump_structure());
987
0
    }
988
137
    _batched_blocks.emplace_back(block, row_pos, num_rows);
989
137
    return Status::OK();
990
137
}
991
992
137
Status VerticalSegmentWriter::write_batch() {
993
137
    if (_opts.rowset_ctx->partial_update_info &&
994
137
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
995
137
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
996
137
        !_opts.rowset_ctx->is_transient_rowset_writer) {
997
20
        bool is_flexible_partial_update =
998
20
                _opts.rowset_ctx->partial_update_info->is_flexible_partial_update();
999
20
        Block full_block;
1000
20
        for (auto& data : _batched_blocks) {
1001
20
            if (is_flexible_partial_update) {
1002
8
                RETURN_IF_ERROR(_append_block_with_flexible_partial_content(data, full_block));
1003
12
            } else {
1004
12
                RETURN_IF_ERROR(_append_block_with_partial_content(data, full_block));
1005
12
            }
1006
20
        }
1007
20
        return Status::OK();
1008
20
    }
1009
    // The transform chain already validated, parsed variants and decided the derived
1010
    // (row-store) column; this writer only pumps the generator in bounded batches.
1011
117
    if (_derived_column.second) {
1012
12
        const auto& [cid, generator] = _derived_column;
1013
12
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
1014
12
        for (auto& data : _batched_blocks) {
1015
12
            RETURN_IF_ERROR(_append_generated_column(*generator, *data.block, data.row_pos,
1016
12
                                                     data.num_rows, cid));
1017
12
        }
1018
12
        RETURN_IF_ERROR(_check_column_writer_disk_capacity(cid));
1019
12
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
1020
12
    }
1021
1022
117
    std::vector<IOlapColumnDataAccessor*> key_columns;
1023
117
    IOlapColumnDataAccessor* seq_column = nullptr;
1024
    // the key is cluster key column unique id
1025
117
    std::map<uint32_t, IOlapColumnDataAccessor*> cid_to_column;
1026
1.38k
    for (uint32_t cid = 0; cid < _tablet_schema->num_columns(); ++cid) {
1027
1.26k
        if (_derived_column.second && _derived_column.first == cid) {
1028
12
            continue;
1029
12
        }
1030
1.25k
        RETURN_IF_ERROR(_create_column_writer(cid, _tablet_schema->column(cid), _tablet_schema));
1031
1.25k
        for (auto& data : _batched_blocks) {
1032
1.25k
            RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
1033
1.25k
                    data.block, data.row_pos, data.num_rows, std::vector<uint32_t> {cid}));
1034
1035
            // convert column data from engine format to storage layer format
1036
1.25k
            auto [status, column] = _olap_data_convertor->convert_column_data(cid);
1037
1.25k
            if (!status.ok()) {
1038
0
                return status;
1039
0
            }
1040
1.25k
            if (cid < _tablet_schema->num_key_columns()) {
1041
670
                key_columns.push_back(column);
1042
670
            }
1043
1.25k
            if (_tablet_schema->has_sequence_col() && cid == _tablet_schema->sequence_col_idx()) {
1044
15
                seq_column = column;
1045
15
            }
1046
1.25k
            auto column_unique_id = _tablet_schema->column(cid).unique_id();
1047
1.25k
            if (_is_mow_with_cluster_key() &&
1048
1.25k
                std::find(_tablet_schema->cluster_key_uids().begin(),
1049
193
                          _tablet_schema->cluster_key_uids().end(),
1050
193
                          column_unique_id) != _tablet_schema->cluster_key_uids().end()) {
1051
162
                cid_to_column[column_unique_id] = column;
1052
162
            }
1053
1.25k
            RETURN_IF_ERROR(_column_writers[cid]->append(column->get_nullmap(), column->get_data(),
1054
1.25k
                                                         data.num_rows));
1055
1.25k
            _olap_data_convertor->clear_source_content();
1056
1.25k
        }
1057
1.25k
        RETURN_IF_ERROR(_check_column_writer_disk_capacity(cid));
1058
1.25k
        RETURN_IF_ERROR(_finalize_column_writer_and_update_meta(cid));
1059
1.25k
    }
1060
1061
117
    for (auto& data : _batched_blocks) {
1062
117
        _olap_data_convertor->set_source_content(data.block, data.row_pos, data.num_rows);
1063
117
        RETURN_IF_ERROR(_generate_key_index(data, key_columns, seq_column, cid_to_column));
1064
117
        _olap_data_convertor->clear_source_content();
1065
117
        _num_rows_written += data.num_rows;
1066
117
    }
1067
1068
117
    _batched_blocks.clear();
1069
    // The generator snapshots the batched blocks' rows; it must not survive them.
1070
117
    _derived_column = {};
1071
117
    return Status::OK();
1072
117
}
1073
1074
Status VerticalSegmentWriter::_generate_key_index(
1075
        RowsInBlock& data, std::vector<IOlapColumnDataAccessor*>& key_columns,
1076
        IOlapColumnDataAccessor* seq_column,
1077
117
        std::map<uint32_t, IOlapColumnDataAccessor*>& cid_to_column) {
1078
    // find all row pos for short key indexes
1079
117
    std::vector<size_t> short_key_pos;
1080
    // We build a short key index every `_opts.num_rows_per_block` rows. Specifically, we
1081
    // build a short key index using 1st rows for first block and `_short_key_row_pos - _row_count`
1082
    // for next blocks.
1083
117
    if (_short_key_row_pos == 0 && _num_rows_written == 0) {
1084
117
        short_key_pos.push_back(0);
1085
117
    }
1086
117
    while (_short_key_row_pos + _opts.num_rows_per_block < _num_rows_written + data.num_rows) {
1087
0
        _short_key_row_pos += _opts.num_rows_per_block;
1088
0
        short_key_pos.push_back(_short_key_row_pos - _num_rows_written);
1089
0
    }
1090
117
    if (_is_mow_with_cluster_key()) {
1091
        // 1. generate primary key index
1092
9
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, data.num_rows, true));
1093
        // 2. generate short key index (use cluster key)
1094
9
        std::vector<IOlapColumnDataAccessor*> short_key_columns;
1095
162
        for (const auto& cid : _tablet_schema->cluster_key_uids()) {
1096
162
            short_key_columns.push_back(cid_to_column[cid]);
1097
162
        }
1098
9
        RETURN_IF_ERROR(_generate_short_key_index(short_key_columns, data.num_rows, short_key_pos));
1099
108
    } else if (_is_mow()) {
1100
17
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, data.num_rows, false));
1101
91
    } else { // other tables
1102
91
        RETURN_IF_ERROR(_generate_short_key_index(key_columns, data.num_rows, short_key_pos));
1103
91
    }
1104
117
    return Status::OK();
1105
117
}
1106
1107
Status VerticalSegmentWriter::_generate_primary_key_index(
1108
        const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
1109
38
        IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort) {
1110
38
    if (!need_sort) { // mow table without cluster key
1111
29
        std::string last_key;
1112
111
        for (size_t pos = 0; pos < num_rows; pos++) {
1113
82
            std::string key = encode_mow_key_invalidate_cache(
1114
82
                    _key_encoder, primary_key_columns, seq_column, pos,
1115
82
                    _tablet_schema->has_sequence_col(), _opts.rowset_ctx->tablet_id,
1116
82
                    *_tablet_schema, _opts.write_type);
1117
82
            DCHECK(key.compare(last_key) > 0)
1118
0
                    << "found duplicate key or key is not sorted! current key: " << key
1119
0
                    << ", last key: " << last_key;
1120
82
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1121
82
            last_key = std::move(key);
1122
82
        }
1123
29
    } else { // mow table with cluster key
1124
        // 1. generate primary keys in memory
1125
9
        std::vector<std::string> primary_keys;
1126
37
        for (uint32_t pos = 0; pos < num_rows; pos++) {
1127
28
            std::string key = _key_encoder.full_encode_primary_keys(primary_key_columns, pos);
1128
28
            MowKeyProbe::maybe_invalidate_row_cache(_opts.rowset_ctx->tablet_id, *_tablet_schema,
1129
28
                                                    _opts.write_type, key);
1130
28
            if (_tablet_schema->has_sequence_col()) {
1131
16
                _key_encoder.append_seq_suffix(&key, seq_column, pos);
1132
16
            }
1133
28
            _key_encoder.append_rowid_suffix(&key, pos);
1134
28
            primary_keys.emplace_back(std::move(key));
1135
28
        }
1136
        // 2. sort primary keys
1137
9
        std::sort(primary_keys.begin(), primary_keys.end());
1138
        // 3. write primary keys index
1139
9
        std::string last_key;
1140
28
        for (const auto& key : primary_keys) {
1141
28
            DCHECK(key.compare(last_key) > 0)
1142
0
                    << "found duplicate key or key is not sorted! current key: " << key
1143
0
                    << ", last key: " << last_key;
1144
28
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1145
28
            last_key = key;
1146
28
        }
1147
9
    }
1148
38
    return Status::OK();
1149
38
}
1150
1151
Status VerticalSegmentWriter::_generate_short_key_index(
1152
        std::vector<IOlapColumnDataAccessor*>& key_columns, size_t num_rows,
1153
100
        const std::vector<size_t>& short_key_pos) {
1154
100
    _set_min_key(_key_encoder.full_encode(key_columns, 0));
1155
100
    _set_max_key(_key_encoder.full_encode(key_columns, num_rows - 1));
1156
100
    DCHECK(Slice(_max_key.data(), _max_key.size())
1157
0
                   .compare(Slice(_min_key.data(), _min_key.size())) >= 0)
1158
0
            << "key is not sorted! min key: " << _min_key << ", max key: " << _max_key;
1159
1160
100
    key_columns.resize(_num_short_key_columns);
1161
100
    std::string last_key;
1162
100
    for (const auto pos : short_key_pos) {
1163
100
        std::string key = _key_encoder.encode_short_keys(key_columns, pos);
1164
100
        DCHECK(key.compare(last_key) >= 0)
1165
0
                << "key is not sorted! current key: " << key << ", last key: " << last_key;
1166
100
        RETURN_IF_ERROR(_short_key_index_builder->add_item(key));
1167
100
        last_key = std::move(key);
1168
100
    }
1169
100
    return Status::OK();
1170
100
}
1171
1172
// TODO(lingbin): Currently this function does not include the size of various indexes,
1173
// We should make this more precise.
1174
34
uint64_t VerticalSegmentWriter::_estimated_remaining_size() {
1175
    // footer_size(4) + checksum(4) + segment_magic(4)
1176
34
    uint64_t size = 12;
1177
34
    if (_is_mow_with_cluster_key()) {
1178
1
        size += _primary_key_index_builder->size() + _short_key_index_builder->size();
1179
33
    } else if (_is_mow()) {
1180
24
        size += _primary_key_index_builder->size();
1181
24
    } else {
1182
9
        size += _short_key_index_builder->size();
1183
9
    }
1184
1185
    // update the mem_tracker of segment size
1186
34
    _mem_tracker->consume(size - _mem_tracker->consumption());
1187
34
    return size;
1188
34
}
1189
1190
137
Status VerticalSegmentWriter::finalize_columns_index(uint64_t* index_size) {
1191
137
    uint64_t index_start = _file_writer->bytes_appended();
1192
    // Record the common index range for cloud index-only file-cache preload.
1193
    // This VerticalSegmentWriter path is used when cloud load, compaction, or schema change flushes
1194
    // a whole block through SegmentCreator with enable_vertical_segment_writer enabled.
1195
137
    RETURN_IF_ERROR(_write_ordinal_index());
1196
137
    RETURN_IF_ERROR(_write_zone_map());
1197
137
    RETURN_IF_ERROR(_write_inverted_index());
1198
137
    RETURN_IF_ERROR(_write_ann_index());
1199
137
    RETURN_IF_ERROR(_write_bloom_filter_index());
1200
1201
137
    *index_size = _file_writer->bytes_appended() - index_start;
1202
137
    if (_is_mow_with_cluster_key()) {
1203
9
        RETURN_IF_ERROR(_write_short_key_index());
1204
9
        *index_size = _file_writer->bytes_appended() - index_start;
1205
9
        RETURN_IF_ERROR(_write_primary_key_index());
1206
9
        *index_size += _primary_key_index_builder->disk_size();
1207
128
    } else if (_is_mow()) {
1208
37
        RETURN_IF_ERROR(_write_primary_key_index());
1209
        // IndexedColumnWriter write data pages mixed with segment data, we should use
1210
        // the stat from primary key index builder.
1211
37
        *index_size += _primary_key_index_builder->disk_size();
1212
91
    } else {
1213
91
        RETURN_IF_ERROR(_write_short_key_index());
1214
91
        *index_size = _file_writer->bytes_appended() - index_start;
1215
91
    }
1216
137
    uint64_t file_index_end = _file_writer->bytes_appended();
1217
137
    _index_file_cache_info.add_index_range(index_start, file_index_end - index_start);
1218
1219
    // reset all column writers and data_conveter
1220
137
    clear();
1221
1222
137
    return Status::OK();
1223
137
}
1224
1225
Status VerticalSegmentWriter::finalize_footer(uint64_t* segment_file_size,
1226
137
                                              SegmentIndexFileCacheInfo* index_file_cache_info) {
1227
137
    uint64_t footer_start = _file_writer->bytes_appended();
1228
137
    RETURN_IF_ERROR(_write_footer());
1229
    // finish
1230
137
    RETURN_IF_ERROR(_file_writer->close(true));
1231
137
    *segment_file_size = _file_writer->bytes_appended();
1232
    // The closed size completes the preload range recorded above. SegmentIndexFileCacheLoader
1233
    // later decides whether this is a remote cloud rowset that should actually be preloaded.
1234
137
    _index_file_cache_info.segment_file_size = *segment_file_size;
1235
137
    _index_file_cache_info.add_index_range(footer_start, *segment_file_size - footer_start);
1236
137
    if (index_file_cache_info != nullptr) {
1237
137
        *index_file_cache_info = _index_file_cache_info;
1238
137
    }
1239
137
    if (*segment_file_size == 0) {
1240
0
        return Status::Corruption("Bad segment, file size = 0");
1241
0
    }
1242
137
    return Status::OK();
1243
137
}
1244
1245
Status VerticalSegmentWriter::finalize(uint64_t* segment_file_size, uint64_t* index_size,
1246
137
                                       SegmentIndexFileCacheInfo* index_file_cache_info) {
1247
137
    MonotonicStopWatch timer;
1248
137
    timer.start();
1249
    // check disk capacity
1250
137
    if (_data_dir != nullptr &&
1251
137
        _data_dir->reach_capacity_limit((int64_t)_estimated_remaining_size())) {
1252
0
        return Status::Error<DISK_REACH_CAPACITY_LIMIT>("disk {} exceed capacity limit.",
1253
0
                                                        _data_dir->path_hash());
1254
0
    }
1255
137
    _row_count = _num_rows_written;
1256
137
    _num_rows_written = 0;
1257
    // write index
1258
137
    RETURN_IF_ERROR(finalize_columns_index(index_size));
1259
    // write footer
1260
137
    RETURN_IF_ERROR(finalize_footer(segment_file_size, index_file_cache_info));
1261
1262
137
    if (timer.elapsed_time() > 5000000000L) {
1263
0
        LOG(INFO) << "segment flush consumes a lot time_ns " << timer.elapsed_time()
1264
0
                  << ", segmemt_size " << *segment_file_size;
1265
0
    }
1266
137
    return Status::OK();
1267
137
}
1268
1269
137
void VerticalSegmentWriter::clear() {
1270
1.77k
    for (auto& column_writer : _column_writers) {
1271
1.77k
        column_writer.reset();
1272
1.77k
    }
1273
137
    _column_writers.clear();
1274
137
    _olap_data_convertor.reset();
1275
137
}
1276
1277
// write ordinal index after data has been written
1278
137
Status VerticalSegmentWriter::_write_ordinal_index() {
1279
1.77k
    for (auto& column_writer : _column_writers) {
1280
1.77k
        RETURN_IF_ERROR(column_writer->write_ordinal_index());
1281
1.77k
    }
1282
137
    return Status::OK();
1283
137
}
1284
1285
137
Status VerticalSegmentWriter::_write_zone_map() {
1286
1.77k
    for (auto& column_writer : _column_writers) {
1287
1.77k
        RETURN_IF_ERROR(column_writer->write_zone_map());
1288
1.77k
    }
1289
137
    return Status::OK();
1290
137
}
1291
1292
137
Status VerticalSegmentWriter::_write_inverted_index() {
1293
1.77k
    for (auto& column_writer : _column_writers) {
1294
1.77k
        RETURN_IF_ERROR(column_writer->write_inverted_index());
1295
1.77k
    }
1296
137
    return Status::OK();
1297
137
}
1298
1299
137
Status VerticalSegmentWriter::_write_ann_index() {
1300
1.77k
    for (auto& column_writer : _column_writers) {
1301
1.77k
        RETURN_IF_ERROR(column_writer->write_ann_index());
1302
1.77k
    }
1303
137
    return Status::OK();
1304
137
}
1305
1306
137
Status VerticalSegmentWriter::_write_bloom_filter_index() {
1307
1.77k
    for (auto& column_writer : _column_writers) {
1308
1.77k
        RETURN_IF_ERROR(column_writer->write_bloom_filter_index());
1309
1.77k
    }
1310
137
    return Status::OK();
1311
137
}
1312
1313
100
Status VerticalSegmentWriter::_write_short_key_index() {
1314
100
    std::vector<Slice> body;
1315
100
    PageFooterPB footer;
1316
100
    RETURN_IF_ERROR(_short_key_index_builder->finalize(_row_count, &body, &footer));
1317
100
    PagePointer pp;
1318
    // short key index page is not compressed right now
1319
100
    RETURN_IF_ERROR(PageIO::write_page(_file_writer, body, footer, &pp));
1320
100
    pp.to_proto(_footer.mutable_short_key_index_page());
1321
100
    return Status::OK();
1322
100
}
1323
1324
46
Status VerticalSegmentWriter::_write_primary_key_index() {
1325
46
    CHECK_EQ(_primary_key_index_builder->num_rows(), _row_count);
1326
46
    return _primary_key_index_builder->finalize(_footer.mutable_primary_key_index_meta());
1327
46
}
1328
1329
137
Status VerticalSegmentWriter::_write_footer() {
1330
137
    _footer.set_num_rows(_row_count);
1331
1332
    // Decide whether to externalize ColumnMetaPB by tablet default, and stamp footer version
1333
1334
137
    if (_tablet_schema->storage_format() == TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V3) {
1335
32
        _footer.set_version(SEGMENT_FOOTER_VERSION_V3_EXT_COL_META);
1336
32
        VLOG_DEBUG << "use external column meta";
1337
        // External ColumnMetaPB writing (optional)
1338
32
        RETURN_IF_ERROR(ExternalColMetaUtil::write_external_column_meta(
1339
32
                _file_writer, &_footer, _opts.compression_type,
1340
32
                [this](const std::vector<Slice>& slices) { return _write_raw_data(slices); }));
1341
32
    }
1342
1343
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
1344
137
    VLOG_DEBUG << "footer " << _footer.DebugString();
1345
137
    std::string footer_buf;
1346
137
    if (!_footer.SerializeToString(&footer_buf)) {
1347
0
        return Status::InternalError("failed to serialize segment footer");
1348
0
    }
1349
1350
137
    faststring fixed_buf;
1351
    // footer's size
1352
137
    put_fixed32_le(&fixed_buf, cast_set<uint32_t>(footer_buf.size()));
1353
    // footer's checksum
1354
137
    uint32_t checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
1355
137
    put_fixed32_le(&fixed_buf, checksum);
1356
    // Append magic number. we don't write magic number in the header because
1357
    // that will need an extra seek when reading
1358
137
    fixed_buf.append(k_segment_magic, k_segment_magic_length);
1359
1360
137
    std::vector<Slice> slices {footer_buf, fixed_buf};
1361
137
    return _write_raw_data(slices);
1362
137
}
1363
1364
761
Status VerticalSegmentWriter::_write_raw_data(const std::vector<Slice>& slices) {
1365
761
    RETURN_IF_ERROR(_file_writer->appendv(&slices[0], slices.size()));
1366
761
    return Status::OK();
1367
761
}
1368
1369
137
Slice VerticalSegmentWriter::min_encoded_key() {
1370
137
    return (_primary_key_index_builder == nullptr) ? Slice(_min_key.data(), _min_key.size())
1371
137
                                                   : _primary_key_index_builder->min_key();
1372
137
}
1373
137
Slice VerticalSegmentWriter::max_encoded_key() {
1374
137
    return (_primary_key_index_builder == nullptr) ? Slice(_max_key.data(), _max_key.size())
1375
137
                                                   : _primary_key_index_builder->max_key();
1376
137
}
1377
1378
0
void VerticalSegmentWriter::_set_min_max_key(const Slice& key) {
1379
0
    if (UNLIKELY(_is_first_row)) {
1380
0
        _min_key.append(key.get_data(), key.get_size());
1381
0
        _is_first_row = false;
1382
0
    }
1383
0
    if (key.compare(_max_key) > 0) {
1384
0
        _max_key.clear();
1385
0
        _max_key.append(key.get_data(), key.get_size());
1386
0
    }
1387
0
}
1388
1389
100
void VerticalSegmentWriter::_set_min_key(const Slice& key) {
1390
100
    if (UNLIKELY(_is_first_row)) {
1391
100
        _min_key.append(key.get_data(), key.get_size());
1392
100
        _is_first_row = false;
1393
100
    }
1394
100
}
1395
1396
100
void VerticalSegmentWriter::_set_max_key(const Slice& key) {
1397
100
    _max_key.clear();
1398
100
    _max_key.append(key.get_data(), key.get_size());
1399
100
}
1400
1401
} // namespace doris::segment_v2