Coverage Report

Created: 2026-07-22 14:18

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