Coverage Report

Created: 2026-07-13 09:31

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