Coverage Report

Created: 2026-08-14 19:23

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