Coverage Report

Created: 2026-05-22 10:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/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/segment_writer.h"
19
20
#include <assert.h>
21
#include <gen_cpp/segment_v2.pb.h>
22
#include <parallel_hashmap/phmap.h>
23
24
#include <algorithm>
25
26
// IWYU pragma: no_include <opentelemetry/common/threadlocal.h>
27
#include <crc32c/crc32c.h>
28
29
#include "cloud/config.h"
30
#include "common/cast_set.h"
31
#include "common/compiler_util.h" // IWYU pragma: keep
32
#include "common/config.h"
33
#include "common/logging.h" // LOG
34
#include "common/status.h"
35
#include "core/block/block.h"
36
#include "core/block/column_with_type_and_name.h"
37
#include "core/column/column_nullable.h"
38
#include "core/data_type/primitive_type.h"
39
#include "core/field.h"
40
#include "core/types.h"
41
#include "core/value/vdatetime_value.h"
42
#include "exec/common/variant_util.h"
43
#include "io/cache/block_file_cache.h"
44
#include "io/cache/block_file_cache_factory.h"
45
#include "io/fs/file_system.h"
46
#include "io/fs/file_writer.h"
47
#include "io/fs/local_file_system.h"
48
#include "runtime/exec_env.h"
49
#include "runtime/memory/mem_tracker.h"
50
#include "service/point_query_executor.h"
51
#include "storage/data_dir.h"
52
#include "storage/index/index_file_writer.h"
53
#include "storage/index/index_writer.h"
54
#include "storage/index/inverted/inverted_index_fs_directory.h"
55
#include "storage/index/primary_key_index.h"
56
#include "storage/index/short_key_index.h"
57
#include "storage/iterator/olap_data_convertor.h"
58
#include "storage/key_coder.h"
59
#include "storage/olap_common.h"
60
#include "storage/olap_define.h"
61
#include "storage/partial_update_info.h"
62
#include "storage/rowset/rowset_writer_context.h" // RowsetWriterContext
63
#include "storage/rowset/segment_creator.h"
64
#include "storage/segment/column_writer.h" // ColumnWriter
65
#include "storage/segment/external_col_meta_util.h"
66
#include "storage/segment/historical_row_retriever.h"
67
#include "storage/segment/page_io.h"
68
#include "storage/segment/page_pointer.h"
69
#include "storage/segment/segment_loader.h"
70
#include "storage/segment/variant/variant_ext_meta_writer.h"
71
#include "storage/segment/variant_stats_calculator.h"
72
#include "storage/storage_engine.h"
73
#include "storage/tablet/tablet_schema.h"
74
#include "storage/utils.h"
75
#include "util/coding.h"
76
#include "util/faststring.h"
77
#include "util/jsonb/serialize.h"
78
#include "util/simd/bits.h"
79
namespace doris {
80
namespace segment_v2 {
81
82
using namespace ErrorCode;
83
using namespace KeyConsts;
84
85
const char* k_segment_magic = "D0R1";
86
const uint32_t k_segment_magic_length = 4;
87
88
13.6k
inline std::string segment_mem_tracker_name(uint32_t segment_id) {
89
13.6k
    return "SegmentWriter:Segment-" + std::to_string(segment_id);
90
13.6k
}
91
92
SegmentWriter::SegmentWriter(io::FileWriter* file_writer, uint32_t segment_id,
93
                             TabletSchemaSPtr tablet_schema, BaseTabletSPtr tablet,
94
                             DataDir* data_dir, const SegmentWriterOptions& opts,
95
                             IndexFileWriter* index_file_writer)
96
13.6k
        : _segment_id(segment_id),
97
13.6k
          _tablet_schema(std::move(tablet_schema)),
98
13.6k
          _tablet(std::move(tablet)),
99
13.6k
          _data_dir(data_dir),
100
13.6k
          _opts(opts),
101
13.6k
          _file_writer(file_writer),
102
13.6k
          _index_file_writer(index_file_writer),
103
13.6k
          _mem_tracker(std::make_unique<MemTracker>(segment_mem_tracker_name(segment_id))),
104
13.6k
          _mow_context(std::move(opts.mow_ctx)) {
105
13.6k
    CHECK_NOTNULL(file_writer);
106
13.6k
    _num_sort_key_columns = _tablet_schema->num_key_columns();
107
13.6k
    _num_short_key_columns = _tablet_schema->num_short_key_columns();
108
13.6k
    if (!_is_mow_with_cluster_key()) {
109
13.5k
        DCHECK(_num_sort_key_columns >= _num_short_key_columns)
110
0
                << ", table_id=" << _tablet_schema->table_id()
111
0
                << ", num_key_columns=" << _num_sort_key_columns
112
0
                << ", num_short_key_columns=" << _num_short_key_columns
113
0
                << ", cluster_key_columns=" << _tablet_schema->cluster_key_uids().size();
114
13.5k
    }
115
48.7k
    for (size_t cid = 0; cid < _num_sort_key_columns; ++cid) {
116
35.0k
        const auto& column = _tablet_schema->column(cid);
117
35.0k
        _key_coders.push_back(get_key_coder(column.type()));
118
35.0k
        _key_index_size.push_back(cast_set<uint16_t>(column.index_length()));
119
35.0k
    }
120
13.6k
    if (_is_mow()) {
121
        // encode the sequence id into the primary key index
122
4.64k
        if (_tablet_schema->has_sequence_col()) {
123
85
            const auto& column = _tablet_schema->column(_tablet_schema->sequence_col_idx());
124
85
            _seq_coder = get_key_coder(column.type());
125
85
        }
126
        // encode the rowid into the primary key index
127
4.64k
        if (_is_mow_with_cluster_key()) {
128
167
            _rowid_coder = get_key_coder(FieldType::OLAP_FIELD_TYPE_UNSIGNED_INT);
129
            // primary keys
130
167
            _primary_key_coders.swap(_key_coders);
131
            // cluster keys
132
167
            _key_coders.clear();
133
167
            _key_index_size.clear();
134
167
            _num_sort_key_columns = _tablet_schema->cluster_key_uids().size();
135
519
            for (auto cid : _tablet_schema->cluster_key_uids()) {
136
519
                const auto& column = _tablet_schema->column_by_uid(cid);
137
519
                _key_coders.push_back(get_key_coder(column.type()));
138
519
                _key_index_size.push_back(cast_set<uint16_t>(column.index_length()));
139
519
            }
140
167
        }
141
4.64k
    }
142
13.6k
}
143
144
13.6k
SegmentWriter::~SegmentWriter() {
145
13.6k
    _mem_tracker->release(_mem_tracker->consumption());
146
13.6k
}
147
148
void SegmentWriter::init_column_meta(ColumnMetaPB* meta, uint32_t column_id,
149
121k
                                     const TabletColumn& column, TabletSchemaSPtr tablet_schema) {
150
121k
    meta->set_column_id(column_id);
151
121k
    meta->set_type(int(column.type()));
152
121k
    meta->set_length(column.length());
153
121k
    meta->set_encoding(DEFAULT_ENCODING);
154
121k
    meta->set_compression(_opts.compression_type);
155
121k
    meta->set_is_nullable(column.is_nullable());
156
121k
    meta->set_default_value(column.default_value());
157
121k
    meta->set_precision(column.precision());
158
121k
    meta->set_frac(column.frac());
159
121k
    if (column.has_path_info()) {
160
3.63k
        column.path_info_ptr()->to_protobuf(meta->mutable_column_path_info(),
161
3.63k
                                            column.parent_unique_id());
162
3.63k
    }
163
121k
    meta->set_unique_id(column.unique_id());
164
132k
    for (uint32_t i = 0; i < column.get_subtype_count(); ++i) {
165
11.2k
        init_column_meta(meta->add_children_columns(), column_id, column.get_sub_column(i),
166
11.2k
                         tablet_schema);
167
11.2k
    }
168
121k
    meta->set_result_is_nullable(column.get_result_is_nullable());
169
121k
    meta->set_function_name(column.get_aggregation_name());
170
121k
    meta->set_be_exec_version(column.get_be_exec_version());
171
121k
    if (column.is_variant_type()) {
172
1.44k
        meta->set_variant_max_subcolumns_count(column.variant_max_subcolumns_count());
173
1.44k
        meta->set_variant_enable_doc_mode(column.variant_enable_doc_mode());
174
1.44k
    }
175
121k
}
176
177
5.56k
Status SegmentWriter::init() {
178
5.56k
    std::vector<uint32_t> column_ids;
179
5.56k
    auto column_cnt = cast_set<int>(_tablet_schema->num_columns());
180
35.4k
    for (uint32_t i = 0; i < column_cnt; ++i) {
181
29.8k
        column_ids.emplace_back(i);
182
29.8k
    }
183
5.56k
    return init(column_ids, true);
184
5.56k
}
185
186
Status SegmentWriter::_create_column_writer(uint32_t cid, const TabletColumn& column,
187
110k
                                            const TabletSchemaSPtr& schema) {
188
110k
    ColumnWriterOptions opts;
189
110k
    opts.meta = _footer.add_columns();
190
191
110k
    init_column_meta(opts.meta, cid, column, schema);
192
193
    // now we create zone map for key columns in AGG_KEYS or all column in UNIQUE_KEYS or DUP_KEYS
194
    // except for columns whose type don't support zone map.
195
110k
    opts.need_zone_map = column.is_key() || schema->keys_type() != KeysType::AGG_KEYS;
196
110k
    opts.need_bloom_filter = column.is_bf_column();
197
110k
    if (opts.need_bloom_filter) {
198
205
        opts.bf_options.fpp = schema->has_bf_fpp() ? schema->bloom_filter_fpp() : 0.05;
199
205
    }
200
110k
    auto* tablet_index = schema->get_ngram_bf_index(column.unique_id());
201
110k
    if (tablet_index) {
202
182
        opts.need_bloom_filter = true;
203
182
        opts.is_ngram_bf_index = true;
204
        //narrow convert from int32_t to uint8_t and uint16_t which is dangerous
205
182
        auto gram_size = tablet_index->get_gram_size();
206
182
        auto gram_bf_size = tablet_index->get_gram_bf_size();
207
182
        if (gram_size > 256 || gram_size < 1) {
208
0
            return Status::NotSupported("Do not support ngram bloom filter for ngram_size: ",
209
0
                                        gram_size);
210
0
        }
211
182
        if (gram_bf_size > 65535 || gram_bf_size < 64) {
212
0
            return Status::NotSupported("Do not support ngram bloom filter for bf_size: ",
213
0
                                        gram_bf_size);
214
0
        }
215
182
        opts.gram_size = cast_set<uint8_t>(gram_size);
216
182
        opts.gram_bf_size = cast_set<uint16_t>(gram_bf_size);
217
182
    }
218
219
110k
    bool skip_inverted_index = false;
220
110k
    if (_opts.rowset_ctx != nullptr) {
221
        // skip write inverted index for index compaction column
222
107k
        skip_inverted_index =
223
107k
                _opts.rowset_ctx->columns_to_do_index_compaction.count(column.unique_id()) > 0;
224
107k
    }
225
    // skip write inverted index on load if skip_write_index_on_load is true
226
110k
    if (_opts.write_type == DataWriteType::TYPE_DIRECT && schema->skip_write_index_on_load()) {
227
0
        skip_inverted_index = true;
228
0
    }
229
    // indexes for this column
230
110k
    if (!skip_inverted_index) {
231
109k
        auto inverted_indexs = schema->inverted_indexs(column);
232
109k
        if (!inverted_indexs.empty()) {
233
4.16k
            opts.inverted_indexes = inverted_indexs;
234
4.16k
            opts.need_inverted_index = true;
235
4.16k
            DCHECK(_index_file_writer != nullptr);
236
4.16k
        }
237
109k
    }
238
    // indexes for this column
239
110k
    if (const auto& index = schema->ann_index(column); index != nullptr) {
240
1
        opts.ann_index = index;
241
1
        opts.need_ann_index = true;
242
1
        DCHECK(_index_file_writer != nullptr);
243
1
    }
244
245
110k
    opts.index_file_writer = _index_file_writer;
246
247
110k
#define DISABLE_INDEX_IF_FIELD_TYPE(TYPE)                     \
248
991k
    if (column.type() == FieldType::OLAP_FIELD_TYPE_##TYPE) { \
249
6.96k
        opts.need_zone_map = false;                           \
250
6.96k
        opts.need_bloom_filter = false;                       \
251
6.96k
    }
252
253
110k
    DISABLE_INDEX_IF_FIELD_TYPE(STRUCT)
254
110k
    DISABLE_INDEX_IF_FIELD_TYPE(ARRAY)
255
110k
    DISABLE_INDEX_IF_FIELD_TYPE(JSONB)
256
110k
    DISABLE_INDEX_IF_FIELD_TYPE(AGG_STATE)
257
110k
    DISABLE_INDEX_IF_FIELD_TYPE(MAP)
258
110k
    DISABLE_INDEX_IF_FIELD_TYPE(BITMAP)
259
110k
    DISABLE_INDEX_IF_FIELD_TYPE(HLL)
260
110k
    DISABLE_INDEX_IF_FIELD_TYPE(QUANTILE_STATE)
261
110k
    DISABLE_INDEX_IF_FIELD_TYPE(VARIANT)
262
263
110k
#undef DISABLE_INDEX_IF_FIELD_TYPE
264
265
110k
    int64_t storage_page_size = _tablet_schema->storage_page_size();
266
    // storage_page_size must be between 4KB and 10MB.
267
110k
    if (storage_page_size >= 4096 && storage_page_size <= 10485760) {
268
110k
        opts.data_page_size = storage_page_size;
269
110k
    }
270
110k
    opts.dict_page_size = _tablet_schema->storage_dict_page_size();
271
110k
    DBUG_EXECUTE_IF("VerticalSegmentWriter._create_column_writer.storage_page_size", {
272
110k
        auto table_id = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
273
110k
                "VerticalSegmentWriter._create_column_writer.storage_page_size", "table_id",
274
110k
                INT_MIN);
275
110k
        auto target_data_page_size = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
276
110k
                "VerticalSegmentWriter._create_column_writer.storage_page_size",
277
110k
                "storage_page_size", INT_MIN);
278
110k
        if (table_id == INT_MIN || target_data_page_size == INT_MIN) {
279
110k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
280
110k
                    "Debug point parameters missing: either 'table_id' or 'storage_page_size' not "
281
110k
                    "set.");
282
110k
        }
283
110k
        if (table_id == _tablet_schema->table_id() &&
284
110k
            opts.data_page_size != target_data_page_size) {
285
110k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
286
110k
                    "Mismatch in 'storage_page_size': expected size does not match the current "
287
110k
                    "data page size. "
288
110k
                    "Expected: " +
289
110k
                    std::to_string(target_data_page_size) +
290
110k
                    ", Actual: " + std::to_string(opts.data_page_size) + ".");
291
110k
        }
292
110k
    })
293
110k
    if (column.is_row_store_column()) {
294
        // smaller page size for row store column
295
137
        auto page_size = _tablet_schema->row_store_page_size();
296
137
        opts.data_page_size =
297
137
                (page_size > 0) ? page_size : segment_v2::ROW_STORE_PAGE_SIZE_DEFAULT_VALUE;
298
        // Row store data is already serialized as a single blob. Keep it on plain pages
299
        // to avoid introducing dictionary pages for the hidden row store column.
300
137
        opts.meta->set_encoding(_tablet_schema->binary_plain_encoding_default_impl() ==
301
137
                                                BinaryPlainEncodingTypePB::BINARY_PLAIN_ENCODING_V2
302
137
                                        ? PLAIN_ENCODING_V2
303
137
                                        : PLAIN_ENCODING);
304
137
    }
305
306
110k
    opts.rowset_ctx = _opts.rowset_ctx;
307
110k
    opts.file_writer = _file_writer;
308
110k
    opts.compression_type = _opts.compression_type;
309
110k
    opts.footer = &_footer;
310
110k
    if (_opts.rowset_ctx != nullptr) {
311
107k
        opts.input_rs_readers = _opts.rowset_ctx->input_rs_readers;
312
107k
    }
313
110k
    opts.encoding_preference = {.integer_type_default_use_plain_encoding =
314
110k
                                        _tablet_schema->integer_type_default_use_plain_encoding(),
315
110k
                                .binary_plain_encoding_default_impl =
316
110k
                                        _tablet_schema->binary_plain_encoding_default_impl()};
317
318
110k
    std::unique_ptr<ColumnWriter> writer;
319
110k
    RETURN_IF_ERROR(ColumnWriter::create(opts, &column, _file_writer, &writer));
320
110k
    RETURN_IF_ERROR(writer->init());
321
110k
    _column_writers.push_back(std::move(writer));
322
323
110k
    _olap_data_convertor->add_column_data_convertor(column);
324
110k
    return Status::OK();
325
110k
}
326
327
26.6k
Status SegmentWriter::init(const std::vector<uint32_t>& col_ids, bool has_key) {
328
26.6k
    DCHECK(_column_writers.empty());
329
26.6k
    DCHECK(_column_ids.empty());
330
26.6k
    _has_key = has_key;
331
26.6k
    _column_writers.reserve(_tablet_schema->columns().size());
332
26.6k
    _column_ids.insert(_column_ids.end(), col_ids.begin(), col_ids.end());
333
26.6k
    _olap_data_convertor = std::make_unique<OlapBlockDataConvertor>();
334
26.6k
    if (_opts.compression_type == UNKNOWN_COMPRESSION) {
335
13.6k
        _opts.compression_type = _tablet_schema->compression_type();
336
13.6k
    }
337
338
    // Vertical compaction calls init() multiple times against the same writer; the footer accumulates entries
339
    // across calls, so this init()'s slice of footer columns starts at the current size.
340
26.6k
    const int variant_stats_footer_offset = _footer.columns_size();
341
26.6k
    RETURN_IF_ERROR(_create_writers(_tablet_schema, col_ids));
342
343
    // Initialize variant statistics calculator
344
26.6k
    _variant_stats_calculator = std::make_unique<VariantStatsCaculator>(
345
26.6k
            &_footer, _tablet_schema, col_ids, variant_stats_footer_offset);
346
347
    // we don't need the short key index for unique key merge on write table.
348
26.6k
    if (_has_key) {
349
13.6k
        if (_is_mow()) {
350
4.64k
            size_t seq_col_length = 0;
351
4.64k
            if (_tablet_schema->has_sequence_col()) {
352
85
                seq_col_length =
353
85
                        _tablet_schema->column(_tablet_schema->sequence_col_idx()).length() + 1;
354
85
            }
355
4.64k
            size_t rowid_length = 0;
356
4.64k
            if (_is_mow_with_cluster_key()) {
357
167
                rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
358
167
                _short_key_index_builder.reset(
359
167
                        new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
360
167
            }
361
4.64k
            _primary_key_index_builder.reset(
362
4.64k
                    new PrimaryKeyIndexBuilder(_file_writer, seq_col_length, rowid_length));
363
4.64k
            RETURN_IF_ERROR(_primary_key_index_builder->init());
364
9.02k
        } else {
365
9.02k
            _short_key_index_builder.reset(
366
9.02k
                    new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
367
9.02k
        }
368
13.6k
    }
369
26.6k
    return Status::OK();
370
26.6k
}
371
372
Status SegmentWriter::_create_writers(const TabletSchemaSPtr& tablet_schema,
373
26.6k
                                      const std::vector<uint32_t>& col_ids) {
374
26.6k
    _olap_data_convertor->reserve(col_ids.size());
375
110k
    for (auto& cid : col_ids) {
376
110k
        RETURN_IF_ERROR(_create_column_writer(cid, tablet_schema->column(cid), tablet_schema));
377
110k
    }
378
26.6k
    return Status::OK();
379
26.6k
}
380
381
2.71M
void SegmentWriter::_maybe_invalid_row_cache(const std::string& key) {
382
    // Just invalid row cache for simplicity, since the rowset is not visible at present.
383
    // If we update/insert cache, if load failed rowset will not be visible but cached data
384
    // will be visible, and lead to inconsistency.
385
2.71M
    if (!config::disable_storage_row_cache && _tablet_schema->has_row_store_for_all_columns() &&
386
2.71M
        _opts.write_type == DataWriteType::TYPE_DIRECT) {
387
        // invalidate cache
388
0
        RowCache::instance()->erase({_opts.rowset_ctx->tablet_id, key});
389
0
    }
390
2.71M
}
391
392
5.15k
void SegmentWriter::_serialize_block_to_row_column(const Block& block) {
393
5.15k
    if (block.rows() == 0) {
394
0
        return;
395
0
    }
396
5.15k
    MonotonicStopWatch watch;
397
5.15k
    watch.start();
398
5.15k
    int row_column_id = 0;
399
36.8k
    for (int i = 0; i < _tablet_schema->num_columns(); ++i) {
400
31.9k
        if (_tablet_schema->column(i).is_row_store_column()) {
401
272
            auto* row_store_column = static_cast<ColumnString*>(
402
272
                    block.get_by_position(i).column->assume_mutable_ref().assume_mutable().get());
403
272
            row_store_column->clear();
404
272
            DataTypeSerDeSPtrs serdes = create_data_type_serdes(block.get_data_types());
405
272
            JsonbSerializeUtil::block_to_jsonb(*_tablet_schema, block, *row_store_column,
406
272
                                               cast_set<int>(_tablet_schema->num_columns()), serdes,
407
272
                                               {_tablet_schema->row_columns_uids().begin(),
408
272
                                                _tablet_schema->row_columns_uids().end()});
409
272
            break;
410
272
        }
411
31.9k
    }
412
413
18.4E
    VLOG_DEBUG << "serialize , num_rows:" << block.rows() << ", row_column_id:" << row_column_id
414
18.4E
               << ", total_byte_size:" << block.allocated_bytes() << ", serialize_cost(us)"
415
18.4E
               << watch.elapsed_time() / 1000;
416
5.15k
}
417
418
Status SegmentWriter::probe_key_for_mow(
419
        std::string key, std::size_t segment_pos, bool have_input_seq_column, bool have_delete_sign,
420
        const std::vector<RowsetSharedPtr>& specified_rowsets,
421
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
422
        bool& has_default_or_nullable, std::vector<bool>& use_default_or_null_flag,
423
        const std::function<void(const RowLocation& loc)>& found_cb,
424
0
        const std::function<Status()>& not_found_cb, PartialUpdateStats& stats) {
425
0
    RowLocation loc;
426
    // save rowset shared ptr so this rowset wouldn't delete
427
0
    RowsetSharedPtr rowset;
428
0
    auto st = _tablet->lookup_row_key(
429
0
            key, _tablet_schema.get(), have_input_seq_column, specified_rowsets, &loc,
430
0
            cast_set<uint32_t>(_mow_context->max_version), segment_caches, &rowset);
431
0
    if (st.is<KEY_NOT_FOUND>()) {
432
0
        if (!have_delete_sign) {
433
0
            RETURN_IF_ERROR(not_found_cb());
434
0
        }
435
0
        ++stats.num_rows_new_added;
436
0
        has_default_or_nullable = true;
437
0
        use_default_or_null_flag.emplace_back(true);
438
0
        return Status::OK();
439
0
    }
440
0
    if (!st.ok() && !st.is<KEY_ALREADY_EXISTS>()) {
441
0
        LOG(WARNING) << "failed to lookup row key, error: " << st;
442
0
        return st;
443
0
    }
444
445
    // 1. if the delete sign is marked, it means that the value columns of the row will not
446
    //    be read. So we don't need to read the missing values from the previous rows.
447
    // 2. the one exception is when there are sequence columns in the table, we need to read
448
    //    the sequence columns, otherwise it may cause the merge-on-read based compaction
449
    //    policy to produce incorrect results
450
    // TODO(bobhan1): only read seq col rather than all columns in this situation for
451
    // partial update and flexible partial update
452
453
    // TODO(bobhan1): handle sequence column here
454
0
    if (st.is<KEY_ALREADY_EXISTS>() || (have_delete_sign && !_tablet_schema->has_sequence_col())) {
455
0
        has_default_or_nullable = true;
456
0
        use_default_or_null_flag.emplace_back(true);
457
0
    } else {
458
        // partial update should not contain invisible columns
459
0
        use_default_or_null_flag.emplace_back(false);
460
0
        _rsid_to_rowset.emplace(rowset->rowset_id(), rowset);
461
0
        found_cb(loc);
462
0
    }
463
464
0
    if (st.is<KEY_ALREADY_EXISTS>()) {
465
        // although we need to mark delete current row, we still need to read missing columns
466
        // for this row, we need to ensure that each column is aligned
467
0
        _mow_context->delete_bitmap->add(
468
0
                {_opts.rowset_ctx->rowset_id, _segment_id, DeleteBitmap::TEMP_VERSION_COMMON},
469
0
                cast_set<uint32_t>(segment_pos));
470
0
        ++stats.num_rows_deleted;
471
0
    } else {
472
0
        _mow_context->delete_bitmap->add(
473
0
                {loc.rowset_id, loc.segment_id, DeleteBitmap::TEMP_VERSION_COMMON}, loc.row_id);
474
0
        ++stats.num_rows_updated;
475
0
    }
476
0
    return Status::OK();
477
0
}
478
479
0
Status SegmentWriter::partial_update_preconditions_check(size_t row_pos) {
480
0
    if (!_is_mow()) {
481
0
        auto msg = fmt::format(
482
0
                "Can only do partial update on merge-on-write unique table, but found: "
483
0
                "keys_type={}, _opts.enable_unique_key_merge_on_write={}, tablet_id={}",
484
0
                _tablet_schema->keys_type(), _opts.enable_unique_key_merge_on_write,
485
0
                _tablet->tablet_id());
486
0
        DCHECK(false) << msg;
487
0
        return Status::InternalError<false>(msg);
488
0
    }
489
0
    if (_opts.rowset_ctx->partial_update_info == nullptr) {
490
0
        auto msg =
491
0
                fmt::format("partial_update_info should not be nullptr, please check, tablet_id={}",
492
0
                            _tablet->tablet_id());
493
0
        DCHECK(false) << msg;
494
0
        return Status::InternalError<false>(msg);
495
0
    }
496
0
    if (!_opts.rowset_ctx->partial_update_info->is_fixed_partial_update()) {
497
0
        auto msg = fmt::format(
498
0
                "in fixed partial update code, but update_mode={}, please check, tablet_id={}",
499
0
                _opts.rowset_ctx->partial_update_info->update_mode(), _tablet->tablet_id());
500
0
        DCHECK(false) << msg;
501
0
        return Status::InternalError<false>(msg);
502
0
    }
503
0
    if (row_pos != 0) {
504
0
        auto msg = fmt::format("row_pos should be 0, but found {}, tablet_id={}", row_pos,
505
0
                               _tablet->tablet_id());
506
0
        DCHECK(false) << msg;
507
0
        return Status::InternalError<false>(msg);
508
0
    }
509
0
    return Status::OK();
510
0
}
511
512
// for partial update, we should do following steps to fill content of block:
513
// 1. set block data to data convertor, and get all key_column's converted slice
514
// 2. get pk of input block, and read missing columns
515
//       2.1 first find key location{rowset_id, segment_id, row_id}
516
//       2.2 build read plan to read by batch
517
//       2.3 fill block
518
// 3. set columns to data convertor and then write all columns
519
Status SegmentWriter::append_block_with_partial_content(const Block* block, size_t row_pos,
520
0
                                                        size_t num_rows) {
521
0
    if (block->columns() < _tablet_schema->num_key_columns() ||
522
0
        block->columns() >= _tablet_schema->num_columns()) {
523
0
        return Status::InvalidArgument(
524
0
                fmt::format("illegal partial update block columns: {}, num key columns: {}, total "
525
0
                            "schema columns: {}",
526
0
                            block->columns(), _tablet_schema->num_key_columns(),
527
0
                            _tablet_schema->num_columns()));
528
0
    }
529
0
    RETURN_IF_ERROR(partial_update_preconditions_check(row_pos));
530
531
    // find missing column cids
532
0
    const auto& missing_cids = _opts.rowset_ctx->partial_update_info->missing_cids;
533
0
    const auto& including_cids = _opts.rowset_ctx->partial_update_info->update_cids;
534
535
    // create full block and fill with input columns
536
0
    auto full_block = _tablet_schema->create_block();
537
0
    size_t input_id = 0;
538
0
    for (auto i : including_cids) {
539
0
        full_block.replace_by_position(i, block->get_by_position(input_id++).column);
540
0
    }
541
542
0
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
543
0
        _tablet_schema->num_variant_columns() > 0) {
544
0
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
545
0
                full_block, *_tablet_schema, including_cids));
546
0
    }
547
0
    RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
548
0
            &full_block, row_pos, num_rows, including_cids));
549
550
0
    bool have_input_seq_column = false;
551
    // write including columns
552
0
    std::vector<IOlapColumnDataAccessor*> key_columns;
553
0
    IOlapColumnDataAccessor* seq_column = nullptr;
554
0
    size_t segment_start_pos = 0;
555
0
    for (auto cid : including_cids) {
556
        // here we get segment column row num before append data.
557
0
        segment_start_pos = _column_writers[cid]->get_next_rowid();
558
        // olap data convertor alway start from id = 0
559
0
        auto converted_result = _olap_data_convertor->convert_column_data(cid);
560
0
        if (!converted_result.first.ok()) {
561
0
            return converted_result.first;
562
0
        }
563
0
        if (cid < _num_sort_key_columns) {
564
0
            key_columns.push_back(converted_result.second);
565
0
        } else if (_tablet_schema->has_sequence_col() &&
566
0
                   cid == _tablet_schema->sequence_col_idx()) {
567
0
            seq_column = converted_result.second;
568
0
            have_input_seq_column = true;
569
0
        }
570
0
        RETURN_IF_ERROR(_column_writers[cid]->append(converted_result.second->get_nullmap(),
571
0
                                                     converted_result.second->get_data(),
572
0
                                                     num_rows));
573
0
    }
574
575
0
    bool has_default_or_nullable = false;
576
0
    std::vector<bool> use_default_or_null_flag;
577
0
    use_default_or_null_flag.reserve(num_rows);
578
0
    const auto* delete_signs =
579
0
            BaseTablet::get_delete_sign_column_data(full_block, row_pos + num_rows);
580
581
0
    const std::vector<RowsetSharedPtr>& specified_rowsets = _mow_context->rowset_ptrs;
582
0
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
583
584
0
    FixedReadPlan read_plan;
585
586
    // locate rows in base data
587
0
    PartialUpdateStats stats;
588
589
0
    for (size_t block_pos = row_pos; block_pos < row_pos + num_rows; block_pos++) {
590
        // block   segment
591
        //   2   ->   0
592
        //   3   ->   1
593
        //   4   ->   2
594
        //   5   ->   3
595
        // here row_pos = 2, num_rows = 4.
596
0
        size_t delta_pos = block_pos - row_pos;
597
0
        size_t segment_pos = segment_start_pos + delta_pos;
598
0
        std::string key = _full_encode_keys(key_columns, delta_pos);
599
0
        _maybe_invalid_row_cache(key);
600
0
        if (have_input_seq_column) {
601
0
            _encode_seq_column(seq_column, delta_pos, &key);
602
0
        }
603
        // If the table have sequence column, and the include-cids don't contain the sequence
604
        // column, we need to update the primary key index builder at the end of this method.
605
        // At that time, we have a valid sequence column to encode the key with seq col.
606
0
        if (!_tablet_schema->has_sequence_col() || have_input_seq_column) {
607
0
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
608
0
        }
609
610
        // mark key with delete sign as deleted.
611
0
        bool have_delete_sign = (delete_signs != nullptr && delete_signs[block_pos] != 0);
612
613
0
        auto not_found_cb = [&]() {
614
0
            return _opts.rowset_ctx->partial_update_info->handle_new_key(
615
0
                    *_tablet_schema, [&]() -> std::string {
616
0
                        return block->dump_one_line(block_pos,
617
0
                                                    cast_set<int>(_num_sort_key_columns));
618
0
                    });
619
0
        };
620
0
        auto update_read_plan = [&](const RowLocation& loc) {
621
0
            read_plan.prepare_to_read(loc, segment_pos);
622
0
        };
623
0
        RETURN_IF_ERROR(probe_key_for_mow(std::move(key), segment_pos, have_input_seq_column,
624
0
                                          have_delete_sign, specified_rowsets, segment_caches,
625
0
                                          has_default_or_nullable, use_default_or_null_flag,
626
0
                                          update_read_plan, not_found_cb, stats));
627
0
    }
628
0
    CHECK_EQ(use_default_or_null_flag.size(), num_rows);
629
630
0
    if (config::enable_merge_on_write_correctness_check) {
631
0
        _tablet->add_sentinel_mark_to_delete_bitmap(_mow_context->delete_bitmap.get(),
632
0
                                                    *_mow_context->rowset_ids);
633
0
    }
634
635
    // read to fill full block
636
0
    RETURN_IF_ERROR(read_plan.fill_missing_columns(
637
0
            _opts.rowset_ctx->make_historical_row_retriever_context(), _rsid_to_rowset,
638
0
            *_tablet_schema, full_block, use_default_or_null_flag, has_default_or_nullable,
639
0
            cast_set<uint32_t>(segment_start_pos), block));
640
641
0
    if (_tablet_schema->num_variant_columns() > 0) {
642
0
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
643
0
                full_block, *_tablet_schema, missing_cids));
644
0
    }
645
646
    // convert block to row store format
647
0
    _serialize_block_to_row_column(full_block);
648
649
    // convert missing columns and send to column writer
650
0
    RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
651
0
            &full_block, row_pos, num_rows, missing_cids));
652
0
    for (auto cid : missing_cids) {
653
0
        auto converted_result = _olap_data_convertor->convert_column_data(cid);
654
0
        if (!converted_result.first.ok()) {
655
0
            return converted_result.first;
656
0
        }
657
0
        if (_tablet_schema->has_sequence_col() && !have_input_seq_column &&
658
0
            cid == _tablet_schema->sequence_col_idx()) {
659
0
            DCHECK_EQ(seq_column, nullptr);
660
0
            seq_column = converted_result.second;
661
0
        }
662
0
        RETURN_IF_ERROR(_column_writers[cid]->append(converted_result.second->get_nullmap(),
663
0
                                                     converted_result.second->get_data(),
664
0
                                                     num_rows));
665
0
    }
666
0
    _num_rows_updated += stats.num_rows_updated;
667
0
    _num_rows_deleted += stats.num_rows_deleted;
668
0
    _num_rows_new_added += stats.num_rows_new_added;
669
0
    _num_rows_filtered += stats.num_rows_filtered;
670
0
    if (_tablet_schema->has_sequence_col() && !have_input_seq_column) {
671
0
        DCHECK_NE(seq_column, nullptr);
672
0
        if (_num_rows_written != row_pos ||
673
0
            _primary_key_index_builder->num_rows() != _num_rows_written) {
674
0
            return Status::InternalError(
675
0
                    "Correctness check failed, _num_rows_written: {}, row_pos: {}, primary key "
676
0
                    "index builder num rows: {}",
677
0
                    _num_rows_written, row_pos, _primary_key_index_builder->num_rows());
678
0
        }
679
0
        RETURN_IF_ERROR(
680
0
                _generate_primary_key_index(_key_coders, key_columns, seq_column, num_rows, false));
681
0
    }
682
683
0
    _num_rows_written += num_rows;
684
0
    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
0
    _olap_data_convertor->clear_source_content();
688
689
0
    return Status::OK();
690
0
}
691
692
36.4k
Status SegmentWriter::append_block(const Block* block, size_t row_pos, size_t num_rows) {
693
36.4k
    if (_opts.rowset_ctx->partial_update_info &&
694
36.4k
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
695
36.4k
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
696
36.4k
        !_opts.rowset_ctx->is_transient_rowset_writer) {
697
0
        if (_opts.rowset_ctx->partial_update_info->is_fixed_partial_update()) {
698
0
            RETURN_IF_ERROR(append_block_with_partial_content(block, row_pos, num_rows));
699
0
        } else {
700
0
            return Status::NotSupported<false>(
701
0
                    "SegmentWriter doesn't support flexible partial update, please set "
702
0
                    "enable_vertical_segment_writer=true in be.conf on all BEs to use "
703
0
                    "VerticalSegmentWriter.");
704
0
        }
705
0
        return Status::OK();
706
0
    }
707
36.4k
    if (block->columns() < _column_writers.size()) {
708
0
        return Status::InternalError(
709
0
                "block->columns() < _column_writers.size(), block->columns()=" +
710
0
                std::to_string(block->columns()) +
711
0
                ", _column_writers.size()=" + std::to_string(_column_writers.size()) +
712
0
                ", _tablet_schema->dump_structure()=" + _tablet_schema->dump_structure());
713
0
    }
714
18.4E
    CHECK(block->columns() >= _column_writers.size())
715
18.4E
            << ", block->columns()=" << block->columns()
716
18.4E
            << ", _column_writers.size()=" << _column_writers.size()
717
18.4E
            << ", _tablet_schema->dump_structure()=" << _tablet_schema->dump_structure();
718
    // Row column should be filled here when it's a directly write from memtable
719
    // or it's schema change write(since column data type maybe changed, so we should reubild)
720
36.4k
    if (_opts.write_type == DataWriteType::TYPE_DIRECT ||
721
36.4k
        _opts.write_type == DataWriteType::TYPE_SCHEMA_CHANGE) {
722
5.15k
        _serialize_block_to_row_column(*block);
723
5.15k
    }
724
725
36.4k
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
726
36.4k
        _tablet_schema->num_variant_columns() > 0) {
727
217
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
728
217
                const_cast<Block&>(*block), *_tablet_schema, _column_ids));
729
217
    }
730
731
36.4k
    _olap_data_convertor->set_source_content(block, row_pos, num_rows);
732
733
    // convert column data from engine format to storage layer format
734
36.4k
    std::vector<IOlapColumnDataAccessor*> key_columns;
735
36.4k
    IOlapColumnDataAccessor* seq_column = nullptr;
736
186k
    for (size_t id = 0; id < _column_writers.size(); ++id) {
737
        // olap data convertor alway start from id = 0
738
150k
        auto converted_result = _olap_data_convertor->convert_column_data(id);
739
150k
        if (!converted_result.first.ok()) {
740
0
            return converted_result.first;
741
0
        }
742
150k
        auto cid = _column_ids[id];
743
150k
        if (_has_key && cid < _tablet_schema->num_key_columns()) {
744
42.9k
            key_columns.push_back(converted_result.second);
745
107k
        } else if (_has_key && _tablet_schema->has_sequence_col() &&
746
107k
                   cid == _tablet_schema->sequence_col_idx()) {
747
149
            seq_column = converted_result.second;
748
149
        }
749
150k
        RETURN_IF_ERROR(_column_writers[id]->append(converted_result.second->get_nullmap(),
750
150k
                                                    converted_result.second->get_data(), num_rows));
751
150k
    }
752
36.4k
    if (_opts.write_type == DataWriteType::TYPE_COMPACTION) {
753
29.5k
        RETURN_IF_ERROR(
754
29.5k
                _variant_stats_calculator->calculate_variant_stats(block, row_pos, num_rows));
755
29.5k
    }
756
757
36.4k
    RETURN_IF_ERROR(build_key_index(key_columns, seq_column, num_rows));
758
759
36.4k
    _num_rows_written += num_rows;
760
36.4k
    _olap_data_convertor->clear_source_content();
761
36.4k
    return Status::OK();
762
36.4k
}
763
764
Status SegmentWriter::build_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
765
36.4k
                                      IOlapColumnDataAccessor* seq_column, size_t num_rows) {
766
36.4k
    if (!_has_key) {
767
19.3k
        return Status::OK();
768
19.3k
    }
769
770
    // find all row pos for short key indexes
771
17.1k
    std::vector<size_t> short_key_pos;
772
17.1k
    if (UNLIKELY(_short_key_row_pos == 0 && _num_rows_written == 0)) {
773
13.6k
        short_key_pos.push_back(0);
774
13.6k
    }
775
38.5k
    while (_short_key_row_pos + _opts.num_rows_per_block < _num_rows_written + num_rows) {
776
21.4k
        _short_key_row_pos += _opts.num_rows_per_block;
777
21.4k
        short_key_pos.push_back(_short_key_row_pos - _num_rows_written);
778
21.4k
    }
779
780
17.1k
    if (_is_mow_with_cluster_key()) {
781
        // For CLUSTER BY tables:
782
        // 1) generate primary key index (unique keys)
783
259
        RETURN_IF_ERROR(_generate_primary_key_index(_primary_key_coders, key_columns, seq_column,
784
259
                                                    num_rows, true));
785
        // 2) generate short key index (cluster keys)
786
259
        key_columns.clear();
787
1.53k
        for (const auto& cid : _tablet_schema->cluster_key_uids()) {
788
1.53k
            auto cluster_key_index = _tablet_schema->field_index(cid);
789
1.53k
            if (cluster_key_index == -1) {
790
0
                return Status::InternalError("could not find cluster key column with unique_id=" +
791
0
                                             std::to_string(cid) + " in tablet schema");
792
0
            }
793
1.53k
            bool found = false;
794
13.3k
            for (auto i = 0; i < _column_ids.size(); ++i) {
795
13.3k
                if (_column_ids[i] == cluster_key_index) {
796
1.53k
                    auto converted_result = _olap_data_convertor->convert_column_data(i);
797
1.53k
                    if (!converted_result.first.ok()) {
798
0
                        return converted_result.first;
799
0
                    }
800
1.53k
                    key_columns.push_back(converted_result.second);
801
1.53k
                    found = true;
802
1.53k
                    break;
803
1.53k
                }
804
13.3k
            }
805
1.53k
            if (!found) {
806
0
                return Status::InternalError(
807
0
                        "could not found cluster key column with unique_id=" + std::to_string(cid) +
808
0
                        ", tablet schema index=" + std::to_string(cluster_key_index));
809
0
            }
810
1.53k
        }
811
259
        return _generate_short_key_index(key_columns, num_rows, short_key_pos);
812
259
    }
813
16.8k
    if (_is_mow()) {
814
4.85k
        return _generate_primary_key_index(_key_coders, key_columns, seq_column, num_rows, false);
815
4.85k
    }
816
11.9k
    return _generate_short_key_index(key_columns, num_rows, short_key_pos);
817
16.8k
}
818
819
7.23k
int64_t SegmentWriter::max_row_to_add(size_t row_avg_size_in_bytes) {
820
7.23k
    auto segment_size = estimate_segment_size();
821
7.23k
    if (segment_size >= MAX_SEGMENT_SIZE || _num_rows_written >= _opts.max_rows_per_segment)
822
354
            [[unlikely]] {
823
354
        return 0;
824
354
    }
825
6.87k
    int64_t size_rows = ((int64_t)MAX_SEGMENT_SIZE - (int64_t)segment_size) / row_avg_size_in_bytes;
826
6.87k
    int64_t count_rows = (int64_t)_opts.max_rows_per_segment - _num_rows_written;
827
828
6.87k
    return std::min(size_rows, count_rows);
829
7.23k
}
830
831
std::string SegmentWriter::_full_encode_keys(
832
2.32M
        const std::vector<IOlapColumnDataAccessor*>& key_columns, size_t pos, bool null_first) {
833
2.32M
    assert(_key_index_size.size() == _num_sort_key_columns);
834
2.32M
    assert(key_columns.size() == _num_sort_key_columns &&
835
2.32M
           _key_coders.size() == _num_sort_key_columns);
836
2.32M
    return _full_encode_keys(_key_coders, key_columns, pos, null_first);
837
2.32M
}
838
839
std::string SegmentWriter::_full_encode_keys(
840
        const std::vector<const KeyCoder*>& key_coders,
841
2.74M
        const std::vector<IOlapColumnDataAccessor*>& key_columns, size_t pos, bool null_first) {
842
2.74M
    assert(key_columns.size() == key_coders.size());
843
844
2.74M
    std::string encoded_keys;
845
2.74M
    size_t cid = 0;
846
9.09M
    for (const auto& column : key_columns) {
847
9.09M
        auto field = column->get_data_at(pos);
848
9.09M
        if (UNLIKELY(!field)) {
849
394k
            if (null_first) {
850
394k
                encoded_keys.push_back(KEY_NULL_FIRST_MARKER);
851
18.4E
            } else {
852
18.4E
                encoded_keys.push_back(KEY_NORMAL_MARKER);
853
18.4E
            }
854
394k
            ++cid;
855
394k
            continue;
856
394k
        }
857
8.70M
        encoded_keys.push_back(KEY_NORMAL_MARKER);
858
8.70M
        DCHECK(key_coders[cid] != nullptr);
859
8.70M
        key_coders[cid]->full_encode_ascending(field, &encoded_keys);
860
8.70M
        ++cid;
861
8.70M
    }
862
2.74M
    return encoded_keys;
863
2.74M
}
864
865
void SegmentWriter::_encode_seq_column(const IOlapColumnDataAccessor* seq_column, size_t pos,
866
183
                                       std::string* encoded_keys) {
867
183
    auto field = seq_column->get_data_at(pos);
868
    // To facilitate the use of the primary key index, encode the seq column
869
    // to the minimum value of the corresponding length when the seq column
870
    // is null
871
183
    if (UNLIKELY(!field)) {
872
1
        encoded_keys->push_back(KEY_NULL_FIRST_MARKER);
873
1
        size_t seq_col_length = _tablet_schema->column(_tablet_schema->sequence_col_idx()).length();
874
1
        encoded_keys->append(seq_col_length, KEY_MINIMAL_MARKER);
875
1
        return;
876
1
    }
877
182
    encoded_keys->push_back(KEY_NORMAL_MARKER);
878
182
    _seq_coder->full_encode_ascending(field, encoded_keys);
879
182
}
880
881
422k
void SegmentWriter::_encode_rowid(const uint32_t rowid, std::string* encoded_keys) {
882
422k
    encoded_keys->push_back(KEY_NORMAL_MARKER);
883
422k
    _rowid_coder->full_encode_ascending(&rowid, encoded_keys);
884
422k
}
885
886
std::string SegmentWriter::_encode_keys(const std::vector<IOlapColumnDataAccessor*>& key_columns,
887
28.8k
                                        size_t pos) {
888
28.8k
    assert(key_columns.size() == _num_short_key_columns);
889
890
28.8k
    std::string encoded_keys;
891
28.8k
    size_t cid = 0;
892
39.5k
    for (const auto& column : key_columns) {
893
39.5k
        auto field = column->get_data_at(pos);
894
39.5k
        if (UNLIKELY(!field)) {
895
605
            encoded_keys.push_back(KEY_NULL_FIRST_MARKER);
896
605
            ++cid;
897
605
            continue;
898
605
        }
899
38.9k
        encoded_keys.push_back(KEY_NORMAL_MARKER);
900
38.9k
        _key_coders[cid]->encode_ascending(field, _key_index_size[cid], &encoded_keys);
901
38.9k
        ++cid;
902
38.9k
    }
903
28.8k
    return encoded_keys;
904
28.8k
}
905
906
// TODO(lingbin): Currently this function does not include the size of various indexes,
907
// We should make this more precise.
908
// NOTE: This function will be called when any row of data is added, so we need to
909
// make this function efficient.
910
7.55k
uint64_t SegmentWriter::estimate_segment_size() {
911
    // footer_size(4) + checksum(4) + segment_magic(4)
912
7.55k
    uint64_t size = 12;
913
41.6k
    for (auto& column_writer : _column_writers) {
914
41.6k
        size += column_writer->estimate_buffer_size();
915
41.6k
    }
916
7.55k
    if (_is_mow_with_cluster_key()) {
917
196
        size += _primary_key_index_builder->size() + _short_key_index_builder->size();
918
7.36k
    } else if (_is_mow()) {
919
381
        size += _primary_key_index_builder->size();
920
6.98k
    } else {
921
6.98k
        size += _short_key_index_builder->size();
922
6.98k
    }
923
924
    // update the mem_tracker of segment size
925
7.55k
    _mem_tracker->consume(size - _mem_tracker->consumption());
926
7.55k
    return size;
927
7.55k
}
928
929
26.6k
Status SegmentWriter::finalize_columns_data() {
930
26.6k
    if (_has_key) {
931
13.6k
        _row_count = _num_rows_written;
932
13.6k
    } else {
933
18.4E
        DCHECK(_row_count == _num_rows_written)
934
18.4E
                << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
935
13.0k
        if (_row_count != _num_rows_written) {
936
0
            std::stringstream ss;
937
0
            ss << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
938
0
            LOG(WARNING) << ss.str();
939
0
            return Status::InternalError(ss.str());
940
0
        }
941
13.0k
    }
942
26.6k
    _num_rows_written = 0;
943
944
110k
    for (auto& column_writer : _column_writers) {
945
110k
        RETURN_IF_ERROR(column_writer->finish());
946
110k
    }
947
26.6k
    RETURN_IF_ERROR(_write_data());
948
949
26.6k
    return Status::OK();
950
26.6k
}
951
952
26.6k
Status SegmentWriter::finalize_columns_index(uint64_t* index_size) {
953
26.6k
    uint64_t index_start = _file_writer->bytes_appended();
954
26.6k
    RETURN_IF_ERROR(_write_ordinal_index());
955
26.6k
    RETURN_IF_ERROR(_write_zone_map());
956
26.6k
    RETURN_IF_ERROR(_write_inverted_index());
957
26.6k
    RETURN_IF_ERROR(_write_ann_index());
958
26.6k
    RETURN_IF_ERROR(_write_bloom_filter_index());
959
960
26.6k
    *index_size = _file_writer->bytes_appended() - index_start;
961
26.6k
    if (_has_key) {
962
13.6k
        if (_is_mow_with_cluster_key()) {
963
            // 1. sort primary keys
964
167
            std::sort(_primary_keys.begin(), _primary_keys.end());
965
            // 2. write primary keys index
966
167
            std::string last_key;
967
423k
            for (const auto& key : _primary_keys) {
968
423k
                DCHECK(key.compare(last_key) > 0)
969
0
                        << "found duplicate key or key is not sorted! current key: " << key
970
0
                        << ", last key: " << last_key;
971
423k
                RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
972
423k
                last_key = key;
973
423k
            }
974
975
167
            RETURN_IF_ERROR(_write_short_key_index());
976
167
            *index_size = _file_writer->bytes_appended() - index_start;
977
167
            RETURN_IF_ERROR(_write_primary_key_index());
978
167
            *index_size += _primary_key_index_builder->disk_size();
979
13.5k
        } else if (_is_mow()) {
980
4.47k
            RETURN_IF_ERROR(_write_primary_key_index());
981
            // IndexedColumnWriter write data pages mixed with segment data, we should use
982
            // the stat from primary key index builder.
983
4.47k
            *index_size += _primary_key_index_builder->disk_size();
984
9.02k
        } else {
985
9.02k
            RETURN_IF_ERROR(_write_short_key_index());
986
9.02k
            *index_size = _file_writer->bytes_appended() - index_start;
987
9.02k
        }
988
13.6k
    }
989
    // reset all column writers and data_conveter
990
26.6k
    clear();
991
992
26.6k
    return Status::OK();
993
26.6k
}
994
995
13.6k
Status SegmentWriter::finalize_footer(uint64_t* segment_file_size) {
996
13.6k
    RETURN_IF_ERROR(_write_footer());
997
    // finish
998
13.6k
    RETURN_IF_ERROR(_file_writer->close(true));
999
13.6k
    *segment_file_size = _file_writer->bytes_appended();
1000
13.6k
    if (*segment_file_size == 0) {
1001
0
        return Status::Corruption("Bad segment, file size = 0");
1002
0
    }
1003
13.6k
    return Status::OK();
1004
13.6k
}
1005
1006
5.56k
Status SegmentWriter::finalize(uint64_t* segment_file_size, uint64_t* index_size) {
1007
5.56k
    MonotonicStopWatch timer;
1008
5.56k
    timer.start();
1009
    // check disk capacity
1010
5.56k
    if (_data_dir != nullptr && _data_dir->reach_capacity_limit((int64_t)estimate_segment_size())) {
1011
0
        return Status::Error<DISK_REACH_CAPACITY_LIMIT>("disk {} exceed capacity limit, path: {}",
1012
0
                                                        _data_dir->path_hash(), _data_dir->path());
1013
0
    }
1014
    // write data
1015
5.56k
    RETURN_IF_ERROR(finalize_columns_data());
1016
    // Get the index start before finalize_footer since this function would write new data.
1017
5.56k
    uint64_t index_start = _file_writer->bytes_appended();
1018
    // write index
1019
5.56k
    RETURN_IF_ERROR(finalize_columns_index(index_size));
1020
    // write footer
1021
5.56k
    RETURN_IF_ERROR(finalize_footer(segment_file_size));
1022
1023
5.56k
    if (timer.elapsed_time() > 5000000000l) {
1024
8
        LOG(INFO) << "segment flush consumes a lot time_ns " << timer.elapsed_time()
1025
8
                  << ", segmemt_size " << *segment_file_size;
1026
8
    }
1027
    // When the cache type is not ttl(expiration time == 0), the data should be split into normal cache queue
1028
    // and index cache queue
1029
5.56k
    if (auto* cache_builder = _file_writer->cache_builder(); cache_builder != nullptr &&
1030
5.56k
                                                             cache_builder->_expiration_time == 0 &&
1031
5.56k
                                                             config::is_cloud_mode()) {
1032
33
        auto size = *index_size + *segment_file_size;
1033
33
        auto holder = cache_builder->allocate_cache_holder(index_start, size, _tablet->tablet_id());
1034
33
        for (auto& segment : holder->file_blocks) {
1035
33
            static_cast<void>(segment->change_cache_type(io::FileCacheType::INDEX));
1036
33
        }
1037
33
    }
1038
5.56k
    return Status::OK();
1039
5.56k
}
1040
1041
26.7k
void SegmentWriter::clear() {
1042
110k
    for (auto& column_writer : _column_writers) {
1043
110k
        column_writer.reset();
1044
110k
    }
1045
26.7k
    _column_writers.clear();
1046
26.7k
    _column_ids.clear();
1047
26.7k
    _olap_data_convertor.reset();
1048
26.7k
}
1049
1050
// write column data to file one by one
1051
26.6k
Status SegmentWriter::_write_data() {
1052
110k
    for (auto& column_writer : _column_writers) {
1053
110k
        RETURN_IF_ERROR(column_writer->write_data());
1054
1055
110k
        auto* column_meta = column_writer->get_column_meta();
1056
110k
        DCHECK(column_meta != nullptr);
1057
110k
        column_meta->set_compressed_data_bytes(
1058
110k
                (column_meta->has_compressed_data_bytes() ? column_meta->compressed_data_bytes()
1059
110k
                                                          : 0) +
1060
110k
                column_writer->get_total_compressed_data_pages_bytes());
1061
110k
        column_meta->set_uncompressed_data_bytes(
1062
110k
                (column_meta->has_uncompressed_data_bytes() ? column_meta->uncompressed_data_bytes()
1063
110k
                                                            : 0) +
1064
110k
                column_writer->get_total_uncompressed_data_pages_bytes());
1065
110k
        column_meta->set_raw_data_bytes(
1066
110k
                (column_meta->has_raw_data_bytes() ? column_meta->raw_data_bytes() : 0) +
1067
110k
                column_writer->get_raw_data_bytes());
1068
110k
    }
1069
26.6k
    return Status::OK();
1070
26.6k
}
1071
1072
// write ordinal index after data has been written
1073
26.6k
Status SegmentWriter::_write_ordinal_index() {
1074
110k
    for (auto& column_writer : _column_writers) {
1075
110k
        RETURN_IF_ERROR(column_writer->write_ordinal_index());
1076
110k
    }
1077
26.6k
    return Status::OK();
1078
26.6k
}
1079
1080
26.6k
Status SegmentWriter::_write_zone_map() {
1081
110k
    for (auto& column_writer : _column_writers) {
1082
110k
        RETURN_IF_ERROR(column_writer->write_zone_map());
1083
110k
    }
1084
26.6k
    return Status::OK();
1085
26.6k
}
1086
1087
26.6k
Status SegmentWriter::_write_inverted_index() {
1088
110k
    for (auto& column_writer : _column_writers) {
1089
110k
        RETURN_IF_ERROR(column_writer->write_inverted_index());
1090
110k
    }
1091
26.6k
    return Status::OK();
1092
26.6k
}
1093
1094
26.6k
Status SegmentWriter::_write_ann_index() {
1095
110k
    for (auto& column_writer : _column_writers) {
1096
110k
        RETURN_IF_ERROR(column_writer->write_ann_index());
1097
110k
    }
1098
26.6k
    return Status::OK();
1099
26.6k
}
1100
1101
26.6k
Status SegmentWriter::_write_bloom_filter_index() {
1102
110k
    for (auto& column_writer : _column_writers) {
1103
110k
        RETURN_IF_ERROR(column_writer->write_bloom_filter_index());
1104
110k
    }
1105
26.6k
    return Status::OK();
1106
26.6k
}
1107
1108
9.19k
Status SegmentWriter::_write_short_key_index() {
1109
9.19k
    std::vector<Slice> body;
1110
9.19k
    PageFooterPB footer;
1111
9.19k
    RETURN_IF_ERROR(_short_key_index_builder->finalize(_row_count, &body, &footer));
1112
9.19k
    PagePointer pp;
1113
    // short key index page is not compressed right now
1114
9.19k
    RETURN_IF_ERROR(PageIO::write_page(_file_writer, body, footer, &pp));
1115
9.19k
    pp.to_proto(_footer.mutable_short_key_index_page());
1116
9.19k
    return Status::OK();
1117
9.19k
}
1118
1119
4.64k
Status SegmentWriter::_write_primary_key_index() {
1120
4.64k
    CHECK_EQ(_primary_key_index_builder->num_rows(), _row_count);
1121
4.64k
    return _primary_key_index_builder->finalize(_footer.mutable_primary_key_index_meta());
1122
4.64k
}
1123
1124
13.6k
Status SegmentWriter::_write_footer() {
1125
13.6k
    _footer.set_num_rows(_row_count);
1126
    // Decide whether to externalize ColumnMetaPB by tablet default, and stamp footer version
1127
13.6k
    if (_tablet_schema->is_external_segment_column_meta_used()) {
1128
5.39k
        _footer.set_version(SEGMENT_FOOTER_VERSION_V3_EXT_COL_META);
1129
5.39k
        VLOG_DEBUG << "use external column meta";
1130
        // External ColumnMetaPB writing (optional)
1131
5.39k
        RETURN_IF_ERROR(ExternalColMetaUtil::write_external_column_meta(
1132
5.39k
                _file_writer, &_footer, _opts.compression_type,
1133
5.39k
                [this](const std::vector<Slice>& slices) { return _write_raw_data(slices); }));
1134
5.39k
    }
1135
1136
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
1137
13.6k
    std::string footer_buf;
1138
13.6k
    VLOG_DEBUG << "footer " << _footer.DebugString();
1139
13.6k
    if (!_footer.SerializeToString(&footer_buf)) {
1140
0
        return Status::InternalError("failed to serialize segment footer");
1141
0
    }
1142
1143
13.6k
    faststring fixed_buf;
1144
    // footer's size
1145
13.6k
    put_fixed32_le(&fixed_buf, cast_set<uint32_t>(footer_buf.size()));
1146
    // footer's checksum
1147
13.6k
    uint32_t checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
1148
13.6k
    put_fixed32_le(&fixed_buf, checksum);
1149
    // Append magic number. we don't write magic number in the header because
1150
    // that will need an extra seek when reading
1151
13.6k
    fixed_buf.append(k_segment_magic, k_segment_magic_length);
1152
1153
13.6k
    std::vector<Slice> slices {footer_buf, fixed_buf};
1154
13.6k
    return _write_raw_data(slices);
1155
13.6k
}
1156
1157
72.3k
Status SegmentWriter::_write_raw_data(const std::vector<Slice>& slices) {
1158
72.3k
    RETURN_IF_ERROR(_file_writer->appendv(&slices[0], slices.size()));
1159
72.3k
    return Status::OK();
1160
72.3k
}
1161
1162
13.6k
Slice SegmentWriter::min_encoded_key() {
1163
13.6k
    return (_primary_key_index_builder == nullptr) ? Slice(_min_key.data(), _min_key.size())
1164
13.6k
                                                   : _primary_key_index_builder->min_key();
1165
13.6k
}
1166
13.6k
Slice SegmentWriter::max_encoded_key() {
1167
13.6k
    return (_primary_key_index_builder == nullptr) ? Slice(_max_key.data(), _max_key.size())
1168
13.6k
                                                   : _primary_key_index_builder->max_key();
1169
13.6k
}
1170
1171
211
void SegmentWriter::set_min_max_key(const Slice& key) {
1172
211
    if (UNLIKELY(_is_first_row)) {
1173
6
        _min_key.append(key.get_data(), key.get_size());
1174
6
        _is_first_row = false;
1175
6
    }
1176
211
    if (key.compare(_max_key) > 0) {
1177
211
        _max_key.clear();
1178
211
        _max_key.append(key.get_data(), key.get_size());
1179
211
    }
1180
211
}
1181
1182
12.2k
void SegmentWriter::set_min_key(const Slice& key) {
1183
12.2k
    if (UNLIKELY(_is_first_row)) {
1184
9.18k
        _min_key.append(key.get_data(), key.get_size());
1185
9.18k
        _is_first_row = false;
1186
9.18k
    }
1187
12.2k
}
1188
1189
12.2k
void SegmentWriter::set_max_key(const Slice& key) {
1190
12.2k
    _max_key.clear();
1191
12.2k
    _max_key.append(key.get_data(), key.get_size());
1192
12.2k
}
1193
1194
0
void SegmentWriter::set_mow_context(std::shared_ptr<MowContext> mow_context) {
1195
0
    _mow_context = mow_context;
1196
0
}
1197
1198
Status SegmentWriter::_generate_primary_key_index(
1199
        const std::vector<const KeyCoder*>& primary_key_coders,
1200
        const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
1201
5.10k
        IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort) {
1202
5.10k
    if (!need_sort) { // mow table without cluster key
1203
4.85k
        std::string last_key;
1204
2.30M
        for (size_t pos = 0; pos < num_rows; pos++) {
1205
            // use _key_coders
1206
2.30M
            std::string key = _full_encode_keys(primary_key_columns, pos);
1207
2.30M
            _maybe_invalid_row_cache(key);
1208
2.30M
            if (_tablet_schema->has_sequence_col()) {
1209
162
                _encode_seq_column(seq_column, pos, &key);
1210
162
            }
1211
2.30M
            DCHECK(key.compare(last_key) > 0)
1212
1.22k
                    << "found duplicate key or key is not sorted! current key: " << key
1213
1.22k
                    << ", last key: " << last_key;
1214
2.30M
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1215
2.30M
            last_key = std::move(key);
1216
2.30M
        }
1217
4.85k
    } else { // mow table with cluster key
1218
        // generate primary keys in memory
1219
423k
        for (uint32_t pos = 0; pos < num_rows; pos++) {
1220
422k
            std::string key = _full_encode_keys(primary_key_coders, primary_key_columns, pos);
1221
422k
            _maybe_invalid_row_cache(key);
1222
422k
            if (_tablet_schema->has_sequence_col()) {
1223
21
                _encode_seq_column(seq_column, pos, &key);
1224
21
            }
1225
422k
            _encode_rowid(pos + _num_rows_written, &key);
1226
422k
            _primary_keys_size += key.size();
1227
422k
            _primary_keys.emplace_back(std::move(key));
1228
422k
        }
1229
259
    }
1230
5.10k
    return Status::OK();
1231
5.10k
}
1232
1233
Status SegmentWriter::_generate_short_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
1234
                                                size_t num_rows,
1235
12.2k
                                                const std::vector<size_t>& short_key_pos) {
1236
    // use _key_coders
1237
12.2k
    set_min_key(_full_encode_keys(key_columns, 0));
1238
12.2k
    set_max_key(_full_encode_keys(key_columns, num_rows - 1));
1239
18.4E
    DCHECK(Slice(_max_key.data(), _max_key.size())
1240
18.4E
                   .compare(Slice(_min_key.data(), _min_key.size())) >= 0)
1241
18.4E
            << "key is not sorted! min key: " << _min_key << ", max key: " << _max_key;
1242
1243
12.2k
    key_columns.resize(_num_short_key_columns);
1244
12.2k
    std::string last_key;
1245
28.8k
    for (const auto pos : short_key_pos) {
1246
28.8k
        std::string key = _encode_keys(key_columns, pos);
1247
28.8k
        DCHECK(key.compare(last_key) >= 0)
1248
0
                << "key is not sorted! current key: " << key << ", last key: " << last_key;
1249
28.8k
        RETURN_IF_ERROR(_short_key_index_builder->add_item(key));
1250
28.8k
        last_key = std::move(key);
1251
28.8k
    }
1252
12.2k
    return Status::OK();
1253
12.2k
}
1254
1255
384k
inline bool SegmentWriter::_is_mow() {
1256
384k
    return _tablet_schema->keys_type() == UNIQUE_KEYS && _opts.enable_unique_key_merge_on_write;
1257
384k
}
1258
1259
190k
inline bool SegmentWriter::_is_mow_with_cluster_key() {
1260
190k
    return _is_mow() && !_tablet_schema->cluster_key_uids().empty();
1261
190k
}
1262
1263
} // namespace segment_v2
1264
} // namespace doris