Coverage Report

Created: 2026-08-13 23:35

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 "storage/data_dir.h"
51
#include "storage/index/index_file_writer.h"
52
#include "storage/index/index_writer.h"
53
#include "storage/index/inverted/inverted_index_fs_directory.h"
54
#include "storage/index/primary_key_index.h"
55
#include "storage/index/short_key_index.h"
56
#include "storage/iterator/olap_data_convertor.h"
57
#include "storage/key_coder.h"
58
#include "storage/mow/historical_row_fetcher.h"
59
#include "storage/mow/key_probe.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
86
const char* k_segment_magic = "D0R1";
87
const uint32_t k_segment_magic_length = 4;
88
89
3.44k
inline std::string segment_mem_tracker_name(uint32_t segment_id) {
90
3.44k
    return "SegmentWriter:Segment-" + std::to_string(segment_id);
91
3.44k
}
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
3.44k
        : _segment_id(segment_id),
98
3.44k
          _tablet_schema(std::move(tablet_schema)),
99
3.44k
          _tablet(std::move(tablet)),
100
3.44k
          _data_dir(data_dir),
101
3.44k
          _opts(opts),
102
3.44k
          _file_writer(file_writer),
103
3.44k
          _index_file_writer(index_file_writer),
104
3.44k
          _mem_tracker(std::make_unique<MemTracker>(segment_mem_tracker_name(segment_id))),
105
3.44k
          _key_encoder(*_tablet_schema, _is_mow()),
106
3.44k
          _mow_context(std::move(opts.mow_ctx)) {
107
3.44k
    CHECK_NOTNULL(file_writer);
108
3.44k
    _num_short_key_columns = _tablet_schema->num_short_key_columns();
109
3.44k
}
110
111
3.44k
SegmentWriter::~SegmentWriter() {
112
3.44k
    _mem_tracker->release(_mem_tracker->consumption());
113
3.44k
}
114
115
void SegmentWriter::init_column_meta(ColumnMetaPB* meta, uint32_t column_id,
116
15.7k
                                     const TabletColumn& column, const ColumnWriterOptions& opts) {
117
15.7k
    meta->set_column_id(column_id);
118
15.7k
    meta->set_type(int(column.type()));
119
15.7k
    meta->set_length(column.length());
120
15.7k
    meta->set_encoding(EncodingInfo::resolve_default_encoding(opts.storage_format, column));
121
15.7k
    meta->set_compression(_opts.compression_type);
122
15.7k
    meta->set_is_nullable(column.is_nullable());
123
15.7k
    meta->set_default_value(column.default_value());
124
15.7k
    meta->set_precision(column.precision());
125
15.7k
    meta->set_frac(column.frac());
126
15.7k
    if (column.has_path_info()) {
127
525
        column.path_info_ptr()->to_protobuf(meta->mutable_column_path_info(),
128
525
                                            column.parent_unique_id());
129
525
    }
130
15.7k
    meta->set_unique_id(column.unique_id());
131
16.2k
    for (uint32_t i = 0; i < column.get_subtype_count(); ++i) {
132
422
        init_column_meta(meta->add_children_columns(), column_id, column.get_sub_column(i), opts);
133
422
    }
134
15.7k
    meta->set_result_is_nullable(column.get_result_is_nullable());
135
15.7k
    meta->set_function_name(column.get_aggregation_name());
136
15.7k
    meta->set_be_exec_version(column.get_be_exec_version());
137
15.7k
    if (column.is_variant_type()) {
138
459
        meta->set_variant_max_subcolumns_count(column.variant_max_subcolumns_count());
139
459
        meta->set_variant_enable_doc_mode(column.variant_enable_doc_mode());
140
459
    }
141
15.7k
}
142
143
2.22k
Status SegmentWriter::init() {
144
2.22k
    std::vector<uint32_t> column_ids;
145
2.22k
    auto column_cnt = cast_set<int>(_tablet_schema->num_columns());
146
14.0k
    for (uint32_t i = 0; i < column_cnt; ++i) {
147
11.8k
        column_ids.emplace_back(i);
148
11.8k
    }
149
2.22k
    return init(column_ids, true);
150
2.22k
}
151
152
Status SegmentWriter::_create_column_writer(uint32_t cid, const TabletColumn& column,
153
15.3k
                                            const TabletSchemaSPtr& schema) {
154
15.3k
    ColumnWriterOptions opts;
155
15.3k
    opts.meta = _footer.add_columns();
156
15.3k
    opts.storage_format = schema->storage_format();
157
158
15.3k
    init_column_meta(opts.meta, cid, column, opts);
159
160
    // now we create zone map for key columns in AGG_KEYS or all column in UNIQUE_KEYS or DUP_KEYS
161
    // except for columns whose type don't support zone map.
162
15.3k
    opts.need_zone_map = column.is_key() || schema->keys_type() != KeysType::AGG_KEYS;
163
15.3k
    opts.need_bloom_filter = column.is_bf_column();
164
15.3k
    if (opts.need_bloom_filter) {
165
106
        opts.bf_options.fpp = schema->has_bf_fpp() ? schema->bloom_filter_fpp() : 0.05;
166
106
    }
167
15.3k
    auto* tablet_index = schema->get_ngram_bf_index(column.unique_id());
168
15.3k
    if (tablet_index) {
169
8
        opts.need_bloom_filter = true;
170
8
        opts.is_ngram_bf_index = true;
171
        //narrow convert from int32_t to uint8_t and uint16_t which is dangerous
172
8
        auto gram_size = tablet_index->get_gram_size();
173
8
        auto gram_bf_size = tablet_index->get_gram_bf_size();
174
8
        if (gram_size > 256 || gram_size < 1) {
175
0
            return Status::NotSupported("Do not support ngram bloom filter for ngram_size: ",
176
0
                                        gram_size);
177
0
        }
178
8
        if (gram_bf_size > 65535 || gram_bf_size < 64) {
179
0
            return Status::NotSupported("Do not support ngram bloom filter for bf_size: ",
180
0
                                        gram_bf_size);
181
0
        }
182
8
        opts.gram_size = cast_set<uint8_t>(gram_size);
183
8
        opts.gram_bf_size = cast_set<uint16_t>(gram_bf_size);
184
8
    }
185
186
15.3k
    bool skip_inverted_index = false;
187
15.3k
    if (_opts.rowset_ctx != nullptr) {
188
        // skip write inverted index for index compaction column
189
13.1k
        skip_inverted_index =
190
13.1k
                _opts.rowset_ctx->columns_to_do_index_compaction.count(column.unique_id()) > 0;
191
13.1k
    }
192
    // skip write inverted index on load if skip_write_index_on_load is true
193
15.3k
    if (_opts.write_type == DataWriteType::TYPE_DIRECT && schema->skip_write_index_on_load()) {
194
0
        skip_inverted_index = true;
195
0
    }
196
    // indexes for this column
197
15.3k
    if (!skip_inverted_index) {
198
14.9k
        auto inverted_indexs = schema->inverted_indexs(column);
199
14.9k
        if (!inverted_indexs.empty()) {
200
2.22k
            opts.inverted_indexes = inverted_indexs;
201
2.22k
            opts.need_inverted_index = true;
202
2.22k
            DCHECK(_index_file_writer != nullptr);
203
2.22k
        }
204
14.9k
    }
205
    // indexes for this column
206
15.3k
    if (const auto& index = schema->ann_index(column); index != nullptr) {
207
9
        opts.ann_index = index;
208
9
        opts.need_ann_index = true;
209
9
        DCHECK(_index_file_writer != nullptr);
210
9
    }
211
212
15.3k
    opts.index_file_writer = _index_file_writer;
213
214
15.3k
#define DISABLE_INDEX_IF_FIELD_TYPE(TYPE)                     \
215
138k
    if (column.type() == FieldType::OLAP_FIELD_TYPE_##TYPE) { \
216
704
        opts.need_zone_map = false;                           \
217
704
        opts.need_bloom_filter = false;                       \
218
704
    }
219
220
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(STRUCT)
221
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(ARRAY)
222
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(JSONB)
223
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(AGG_STATE)
224
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(MAP)
225
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(BITMAP)
226
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(HLL)
227
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(QUANTILE_STATE)
228
15.3k
    DISABLE_INDEX_IF_FIELD_TYPE(VARIANT)
229
230
15.3k
#undef DISABLE_INDEX_IF_FIELD_TYPE
231
232
15.3k
    int64_t storage_page_size = _tablet_schema->storage_page_size();
233
    // storage_page_size must be between 4KB and 10MB.
234
15.3k
    if (storage_page_size >= 4096 && storage_page_size <= 10485760) {
235
15.3k
        opts.data_page_size = storage_page_size;
236
15.3k
    }
237
15.3k
    opts.dict_page_size = _tablet_schema->storage_dict_page_size();
238
15.3k
    DBUG_EXECUTE_IF("VerticalSegmentWriter._create_column_writer.storage_page_size", {
239
15.3k
        auto table_id = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
240
15.3k
                "VerticalSegmentWriter._create_column_writer.storage_page_size", "table_id",
241
15.3k
                INT_MIN);
242
15.3k
        auto target_data_page_size = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
243
15.3k
                "VerticalSegmentWriter._create_column_writer.storage_page_size",
244
15.3k
                "storage_page_size", INT_MIN);
245
15.3k
        if (table_id == INT_MIN || target_data_page_size == INT_MIN) {
246
15.3k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
247
15.3k
                    "Debug point parameters missing: either 'table_id' or 'storage_page_size' not "
248
15.3k
                    "set.");
249
15.3k
        }
250
15.3k
        if (table_id == _tablet_schema->table_id() &&
251
15.3k
            opts.data_page_size != target_data_page_size) {
252
15.3k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
253
15.3k
                    "Mismatch in 'storage_page_size': expected size does not match the current "
254
15.3k
                    "data page size. "
255
15.3k
                    "Expected: " +
256
15.3k
                    std::to_string(target_data_page_size) +
257
15.3k
                    ", Actual: " + std::to_string(opts.data_page_size) + ".");
258
15.3k
        }
259
15.3k
    })
260
15.3k
    if (column.is_row_store_column()) {
261
        // smaller page size for row store column; encoding is already set to PLAIN /
262
        // PLAIN_V2 by init_column_meta via resolve_default_encoding().
263
47
        auto page_size = _tablet_schema->row_store_page_size();
264
47
        opts.data_page_size =
265
47
                (page_size > 0) ? page_size : segment_v2::ROW_STORE_PAGE_SIZE_DEFAULT_VALUE;
266
47
    }
267
268
15.3k
    opts.rowset_ctx = _opts.rowset_ctx;
269
15.3k
    opts.file_writer = _file_writer;
270
15.3k
    opts.compression_type = _opts.compression_type;
271
15.3k
    opts.footer = &_footer;
272
15.3k
    if (_opts.rowset_ctx != nullptr) {
273
13.1k
        opts.input_rs_readers = _opts.rowset_ctx->input_rs_readers;
274
13.1k
    }
275
276
15.3k
    std::unique_ptr<ColumnWriter> writer;
277
15.3k
    RETURN_IF_ERROR(ColumnWriter::create(opts, &column, _file_writer, &writer));
278
15.3k
    RETURN_IF_ERROR(writer->init());
279
15.3k
    _column_writers.push_back(std::move(writer));
280
281
15.3k
    _olap_data_convertor->add_column_data_convertor(column);
282
15.3k
    return Status::OK();
283
15.3k
}
284
285
4.40k
Status SegmentWriter::init(const std::vector<uint32_t>& col_ids, bool has_key) {
286
4.40k
    DCHECK(_column_writers.empty());
287
4.40k
    DCHECK(_column_ids.empty());
288
4.40k
    _has_key = has_key;
289
4.40k
    _column_writers.reserve(_tablet_schema->columns().size());
290
4.40k
    _column_ids.insert(_column_ids.end(), col_ids.begin(), col_ids.end());
291
4.40k
    _olap_data_convertor = std::make_unique<OlapBlockDataConvertor>();
292
4.40k
    if (_opts.compression_type == UNKNOWN_COMPRESSION) {
293
3.42k
        _opts.compression_type = _tablet_schema->compression_type();
294
3.42k
    }
295
296
    // Vertical compaction calls init() multiple times against the same writer; the footer accumulates entries
297
    // across calls, so this init()'s slice of footer columns starts at the current size.
298
4.40k
    const int variant_stats_footer_offset = _footer.columns_size();
299
4.40k
    RETURN_IF_ERROR(_create_writers(_tablet_schema, col_ids));
300
301
    // Initialize variant statistics calculator
302
4.40k
    _variant_stats_calculator = std::make_unique<VariantStatsCaculator>(
303
4.40k
            &_footer, _tablet_schema, col_ids, variant_stats_footer_offset);
304
305
    // we don't need the short key index for unique key merge on write table.
306
4.40k
    if (_has_key) {
307
3.44k
        if (_is_mow()) {
308
171
            size_t seq_col_length = 0;
309
171
            if (_tablet_schema->has_sequence_col()) {
310
91
                seq_col_length =
311
91
                        _tablet_schema->column(_tablet_schema->sequence_col_idx()).length() + 1;
312
91
            }
313
171
            size_t rowid_length = 0;
314
171
            if (_is_mow_with_cluster_key()) {
315
8
                rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
316
8
                _short_key_index_builder.reset(
317
8
                        new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
318
8
            }
319
171
            _primary_key_index_builder.reset(
320
171
                    new PrimaryKeyIndexBuilder(_file_writer, seq_col_length, rowid_length));
321
171
            RETURN_IF_ERROR(_primary_key_index_builder->init());
322
3.27k
        } else {
323
3.27k
            _short_key_index_builder.reset(
324
3.27k
                    new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
325
3.27k
        }
326
3.44k
    }
327
4.40k
    return Status::OK();
328
4.40k
}
329
330
Status SegmentWriter::_create_writers(const TabletSchemaSPtr& tablet_schema,
331
4.40k
                                      const std::vector<uint32_t>& col_ids) {
332
4.40k
    _olap_data_convertor->reserve(col_ids.size());
333
15.3k
    for (auto& cid : col_ids) {
334
15.3k
        RETURN_IF_ERROR(_create_column_writer(cid, tablet_schema->column(cid), tablet_schema));
335
15.3k
    }
336
4.40k
    return Status::OK();
337
4.40k
}
338
339
12
void SegmentWriter::_serialize_block_to_row_column(Block& block) {
340
12
    if (block.rows() == 0) {
341
0
        return;
342
0
    }
343
12
    MonotonicStopWatch watch;
344
12
    watch.start();
345
12
    int row_column_id = 0;
346
308
    for (int i = 0; i < _tablet_schema->num_columns(); ++i) {
347
300
        if (_tablet_schema->column(i).is_row_store_column()) {
348
4
            auto row_store_column_ptr = block.get_by_position(i).column->clone_empty();
349
4
            auto* row_store_column = static_cast<ColumnString*>(row_store_column_ptr.get());
350
4
            DataTypeSerDeSPtrs serdes = create_data_type_serdes(block.get_data_types());
351
4
            JsonbSerializeUtil::block_to_jsonb(*_tablet_schema, block, *row_store_column,
352
4
                                               cast_set<int>(_tablet_schema->num_columns()), serdes,
353
4
                                               {_tablet_schema->row_columns_uids().begin(),
354
4
                                                _tablet_schema->row_columns_uids().end()});
355
4
            block.replace_by_position(i, std::move(row_store_column_ptr));
356
4
            break;
357
4
        }
358
300
    }
359
360
12
    VLOG_DEBUG << "serialize , num_rows:" << block.rows() << ", row_column_id:" << row_column_id
361
0
               << ", total_byte_size:" << block.allocated_bytes() << ", serialize_cost(us)"
362
0
               << watch.elapsed_time() / 1000;
363
12
}
364
365
Status SegmentWriter::probe_key_for_mow(
366
        const MowKeyProbe& probe, std::string key, std::size_t segment_pos,
367
        bool have_input_seq_column, bool have_delete_sign,
368
        const std::vector<RowsetSharedPtr>& specified_rowsets,
369
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
370
        bool& has_default_or_nullable, std::vector<bool>& use_default_or_null_flag,
371
        const std::function<void(const RowLocation& loc, const RowsetSharedPtr& rowset)>& found_cb,
372
36
        const std::function<Status()>& not_found_cb, PartialUpdateStats& stats) {
373
36
    ProbeOutcome outcome =
374
36
            DORIS_TRY(probe.probe(key, segment_pos, have_input_seq_column, have_delete_sign,
375
36
                                  specified_rowsets, segment_caches, stats));
376
36
    if (outcome.result == KeyProbeResult::NOT_FOUND) {
377
12
        if (!have_delete_sign) {
378
12
            RETURN_IF_ERROR(not_found_cb());
379
12
        }
380
12
        has_default_or_nullable = true;
381
12
        use_default_or_null_flag.emplace_back(true);
382
12
        return Status::OK();
383
12
    }
384
24
    if (outcome.use_default_or_null) {
385
0
        has_default_or_nullable = true;
386
0
        use_default_or_null_flag.emplace_back(true);
387
24
    } else {
388
        // partial update should not contain invisible columns
389
24
        use_default_or_null_flag.emplace_back(false);
390
24
        found_cb(outcome.loc, outcome.rowset);
391
24
    }
392
24
    return Status::OK();
393
36
}
394
395
12
Status SegmentWriter::partial_update_preconditions_check(size_t row_pos) {
396
12
    if (!_is_mow()) {
397
0
        auto msg = fmt::format(
398
0
                "Can only do partial update on merge-on-write unique table, but found: "
399
0
                "keys_type={}, _opts.enable_unique_key_merge_on_write={}, tablet_id={}",
400
0
                _tablet_schema->keys_type(), _opts.enable_unique_key_merge_on_write,
401
0
                _tablet->tablet_id());
402
0
        DCHECK(false) << msg;
403
0
        return Status::InternalError<false>(msg);
404
0
    }
405
12
    if (_opts.rowset_ctx->partial_update_info == nullptr) {
406
0
        auto msg =
407
0
                fmt::format("partial_update_info should not be nullptr, please check, tablet_id={}",
408
0
                            _tablet->tablet_id());
409
0
        DCHECK(false) << msg;
410
0
        return Status::InternalError<false>(msg);
411
0
    }
412
12
    if (!_opts.rowset_ctx->partial_update_info->is_fixed_partial_update()) {
413
0
        auto msg = fmt::format(
414
0
                "in fixed partial update code, but update_mode={}, please check, tablet_id={}",
415
0
                _opts.rowset_ctx->partial_update_info->update_mode(), _tablet->tablet_id());
416
0
        DCHECK(false) << msg;
417
0
        return Status::InternalError<false>(msg);
418
0
    }
419
12
    if (row_pos != 0) {
420
0
        auto msg = fmt::format("row_pos should be 0, but found {}, tablet_id={}", row_pos,
421
0
                               _tablet->tablet_id());
422
0
        DCHECK(false) << msg;
423
0
        return Status::InternalError<false>(msg);
424
0
    }
425
12
    return Status::OK();
426
12
}
427
428
// for partial update, we should do following steps to fill content of block:
429
// 1. set block data to data convertor, and get all key_column's converted slice
430
// 2. get pk of input block, and read missing columns
431
//       2.1 first find key location{rowset_id, segment_id, row_id}
432
//       2.2 build read plan to read by batch
433
//       2.3 fill block
434
// 3. set columns to data convertor and then write all columns
435
Status SegmentWriter::append_block_with_partial_content(const Block* block, size_t row_pos,
436
12
                                                        size_t num_rows) {
437
12
    if (block->columns() < _tablet_schema->num_key_columns() ||
438
12
        block->columns() >= _tablet_schema->num_columns()) {
439
0
        return Status::InvalidArgument(
440
0
                fmt::format("illegal partial update block columns: {}, num key columns: {}, total "
441
0
                            "schema columns: {}",
442
0
                            block->columns(), _tablet_schema->num_key_columns(),
443
0
                            _tablet_schema->num_columns()));
444
0
    }
445
12
    RETURN_IF_ERROR(partial_update_preconditions_check(row_pos));
446
447
    // find missing column cids
448
12
    const auto& missing_cids = _opts.rowset_ctx->partial_update_info->missing_cids;
449
12
    const auto& including_cids = _opts.rowset_ctx->partial_update_info->update_cids;
450
451
    // create full block and fill with input columns
452
12
    auto full_block = _tablet_schema->create_block();
453
12
    size_t input_id = 0;
454
260
    for (auto i : including_cids) {
455
260
        const auto& input_column = block->get_by_position(input_id++);
456
260
        auto& full_column = full_block.get_by_position(i);
457
260
        full_column.column = input_column.column;
458
260
        full_column.type = input_column.type;
459
260
    }
460
461
12
    if (_opts.rowset_ctx->write_type != DataWriteType::TYPE_COMPACTION &&
462
12
        _tablet_schema->num_variant_columns() > 0) {
463
4
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
464
4
                full_block, *_tablet_schema, including_cids));
465
4
    }
466
12
    RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
467
12
            &full_block, row_pos, num_rows, including_cids));
468
469
12
    bool have_input_seq_column = false;
470
    // write including columns
471
12
    std::vector<IOlapColumnDataAccessor*> key_columns;
472
12
    IOlapColumnDataAccessor* seq_column = nullptr;
473
12
    size_t segment_start_pos = 0;
474
260
    for (auto cid : including_cids) {
475
        // here we get segment column row num before append data.
476
260
        segment_start_pos = _column_writers[cid]->get_next_rowid();
477
        // olap data convertor alway start from id = 0
478
260
        auto converted_result = _olap_data_convertor->convert_column_data(cid);
479
260
        if (!converted_result.first.ok()) {
480
0
            return converted_result.first;
481
0
        }
482
260
        if (cid < _key_encoder.num_sort_key_columns()) {
483
240
            key_columns.push_back(converted_result.second);
484
240
        } else if (_tablet_schema->has_sequence_col() &&
485
20
                   cid == _tablet_schema->sequence_col_idx()) {
486
4
            seq_column = converted_result.second;
487
4
            have_input_seq_column = true;
488
4
        }
489
260
        RETURN_IF_ERROR(_column_writers[cid]->append(converted_result.second->get_nullmap(),
490
260
                                                     converted_result.second->get_data(),
491
260
                                                     num_rows));
492
260
    }
493
494
12
    bool has_default_or_nullable = false;
495
12
    std::vector<bool> use_default_or_null_flag;
496
12
    use_default_or_null_flag.reserve(num_rows);
497
12
    const auto* delete_signs =
498
12
            BaseTablet::get_delete_sign_column_data(full_block, row_pos + num_rows);
499
500
12
    const std::vector<RowsetSharedPtr>& specified_rowsets = _mow_context->rowset_ptrs;
501
12
    std::vector<std::unique_ptr<SegmentCacheHandle>> segment_caches(specified_rowsets.size());
502
503
    // the horizontal writer never runs flexible partial update
504
12
    MowKeyProbe probe = MowKeyProbe::for_partial_update(
505
12
            _tablet.get(), _tablet_schema.get(), _tablet_schema->has_sequence_col(), _mow_context,
506
12
            _opts.rowset_ctx->rowset_id, _segment_id, /*flexible=*/false);
507
    // owns the rowset pins and the read plan for the historical read below
508
12
    HistoricalRowFetcher fetcher {_opts.rowset_ctx->make_historical_row_retriever_context()};
509
510
    // locate rows in base data
511
12
    PartialUpdateStats stats;
512
513
48
    for (size_t block_pos = row_pos; block_pos < row_pos + num_rows; block_pos++) {
514
        // block   segment
515
        //   2   ->   0
516
        //   3   ->   1
517
        //   4   ->   2
518
        //   5   ->   3
519
        // here row_pos = 2, num_rows = 4.
520
36
        size_t delta_pos = block_pos - row_pos;
521
36
        size_t segment_pos = segment_start_pos + delta_pos;
522
36
        std::string key = encode_mow_key_invalidate_cache(
523
36
                _key_encoder, key_columns, seq_column, delta_pos, have_input_seq_column,
524
36
                _opts.rowset_ctx->tablet_id, *_tablet_schema, _opts.write_type);
525
        // If the table have sequence column, and the include-cids don't contain the sequence
526
        // column, we need to update the primary key index builder at the end of this method.
527
        // At that time, we have a valid sequence column to encode the key with seq col.
528
36
        if (!_tablet_schema->has_sequence_col() || have_input_seq_column) {
529
24
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
530
24
        }
531
532
        // mark key with delete sign as deleted.
533
36
        bool have_delete_sign = (delete_signs != nullptr && delete_signs[block_pos] != 0);
534
535
36
        auto not_found_cb = [&]() {
536
12
            return _opts.rowset_ctx->partial_update_info->handle_new_key(
537
12
                    *_tablet_schema, [&]() -> std::string {
538
0
                        return block->dump_one_line(
539
0
                                block_pos, cast_set<int>(_key_encoder.num_sort_key_columns()));
540
0
                    });
541
12
        };
542
36
        auto update_read_plan = [&](const RowLocation& loc, const RowsetSharedPtr& rowset) {
543
            // keep the rowset alive until the historical read below is done
544
24
            fetcher.pin_rowset(rowset);
545
24
            fetcher.plan_fixed_read(loc, segment_pos);
546
24
        };
547
36
        RETURN_IF_ERROR(probe_key_for_mow(probe, std::move(key), segment_pos, have_input_seq_column,
548
36
                                          have_delete_sign, specified_rowsets, segment_caches,
549
36
                                          has_default_or_nullable, use_default_or_null_flag,
550
36
                                          update_read_plan, not_found_cb, stats));
551
36
    }
552
12
    CHECK_EQ(use_default_or_null_flag.size(), num_rows);
553
554
12
    if (config::enable_merge_on_write_correctness_check) {
555
12
        _tablet->add_sentinel_mark_to_delete_bitmap(_mow_context->delete_bitmap.get(),
556
12
                                                    *_mow_context->rowset_ids);
557
12
    }
558
559
    // read to fill full block
560
12
    RETURN_IF_ERROR(fetcher.fill_missing_columns(*_tablet_schema, full_block,
561
12
                                                 use_default_or_null_flag, has_default_or_nullable,
562
12
                                                 cast_set<uint32_t>(segment_start_pos), block));
563
564
12
    if (_tablet_schema->num_variant_columns() > 0) {
565
4
        RETURN_IF_ERROR(variant_util::parse_and_materialize_variant_columns(
566
4
                full_block, *_tablet_schema, missing_cids));
567
4
    }
568
569
    // convert block to row store format
570
12
    _serialize_block_to_row_column(full_block);
571
572
    // convert missing columns and send to column writer
573
12
    RETURN_IF_ERROR(_olap_data_convertor->set_source_content_with_specifid_columns(
574
12
            &full_block, row_pos, num_rows, missing_cids));
575
48
    for (auto cid : missing_cids) {
576
48
        auto converted_result = _olap_data_convertor->convert_column_data(cid);
577
48
        if (!converted_result.first.ok()) {
578
0
            return converted_result.first;
579
0
        }
580
48
        if (_tablet_schema->has_sequence_col() && !have_input_seq_column &&
581
48
            cid == _tablet_schema->sequence_col_idx()) {
582
4
            DCHECK_EQ(seq_column, nullptr);
583
4
            seq_column = converted_result.second;
584
4
        }
585
48
        RETURN_IF_ERROR(_column_writers[cid]->append(converted_result.second->get_nullmap(),
586
48
                                                     converted_result.second->get_data(),
587
48
                                                     num_rows));
588
48
    }
589
12
    _num_rows_updated += stats.num_rows_updated;
590
12
    _num_rows_deleted += stats.num_rows_deleted;
591
12
    _num_rows_new_added += stats.num_rows_new_added;
592
12
    _num_rows_filtered += stats.num_rows_filtered;
593
12
    if (_tablet_schema->has_sequence_col() && !have_input_seq_column) {
594
4
        DCHECK_NE(seq_column, nullptr);
595
4
        if (_num_rows_written != row_pos ||
596
4
            _primary_key_index_builder->num_rows() != _num_rows_written) {
597
0
            return Status::InternalError(
598
0
                    "Correctness check failed, _num_rows_written: {}, row_pos: {}, primary key "
599
0
                    "index builder num rows: {}",
600
0
                    _num_rows_written, row_pos, _primary_key_index_builder->num_rows());
601
0
        }
602
4
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, num_rows, false));
603
4
    }
604
605
12
    _num_rows_written += num_rows;
606
12
    DCHECK_EQ(_primary_key_index_builder->num_rows(), _num_rows_written)
607
0
            << "primary key index builder num rows(" << _primary_key_index_builder->num_rows()
608
0
            << ") not equal to segment writer's num rows written(" << _num_rows_written << ")";
609
12
    _olap_data_convertor->clear_source_content();
610
611
12
    return Status::OK();
612
12
}
613
614
9.01k
Status SegmentWriter::append_block(const Block* block, size_t row_pos, size_t num_rows) {
615
9.01k
    if (_opts.rowset_ctx->partial_update_info &&
616
9.01k
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
617
9.01k
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
618
9.01k
        !_opts.rowset_ctx->is_transient_rowset_writer) {
619
12
        if (_opts.rowset_ctx->partial_update_info->is_fixed_partial_update()) {
620
12
            RETURN_IF_ERROR(append_block_with_partial_content(block, row_pos, num_rows));
621
12
        } else {
622
0
            return Status::NotSupported<false>(
623
0
                    "SegmentWriter doesn't support flexible partial update, please set "
624
0
                    "enable_vertical_segment_writer=true in be.conf on all BEs to use "
625
0
                    "VerticalSegmentWriter.");
626
0
        }
627
12
        return Status::OK();
628
12
    }
629
9.00k
    if (block->columns() < _column_writers.size()) {
630
0
        return Status::InternalError(
631
0
                "block->columns() < _column_writers.size(), block->columns()=" +
632
0
                std::to_string(block->columns()) +
633
0
                ", _column_writers.size()=" + std::to_string(_column_writers.size()) +
634
0
                ", _tablet_schema->dump_structure()=" + _tablet_schema->dump_structure());
635
0
    }
636
9.00k
    CHECK(block->columns() >= _column_writers.size())
637
0
            << ", block->columns()=" << block->columns()
638
0
            << ", _column_writers.size()=" << _column_writers.size()
639
0
            << ", _tablet_schema->dump_structure()=" << _tablet_schema->dump_structure();
640
    // Blocks from the seams arrive already transformed (variants parsed, row-store
641
    // column materialized); compaction-family callers bring rows that are already final.
642
9.00k
    _olap_data_convertor->set_source_content(block, row_pos, num_rows);
643
644
    // convert column data from engine format to storage layer format
645
9.00k
    std::vector<IOlapColumnDataAccessor*> key_columns;
646
9.00k
    IOlapColumnDataAccessor* seq_column = nullptr;
647
29.2k
    for (size_t id = 0; id < _column_writers.size(); ++id) {
648
        // olap data convertor alway start from id = 0
649
20.2k
        auto converted_result = _olap_data_convertor->convert_column_data(id);
650
20.2k
        if (!converted_result.first.ok()) {
651
0
            return converted_result.first;
652
0
        }
653
20.2k
        auto cid = _column_ids[id];
654
20.2k
        if (_has_key && cid < _tablet_schema->num_key_columns()) {
655
6.85k
            key_columns.push_back(converted_result.second);
656
13.4k
        } else if (_has_key && _tablet_schema->has_sequence_col() &&
657
13.4k
                   cid == _tablet_schema->sequence_col_idx()) {
658
147
            seq_column = converted_result.second;
659
147
        }
660
20.2k
        RETURN_IF_ERROR(_column_writers[id]->append(converted_result.second->get_nullmap(),
661
20.2k
                                                    converted_result.second->get_data(), num_rows));
662
20.2k
    }
663
9.00k
    if (_opts.write_type == DataWriteType::TYPE_COMPACTION) {
664
6.37k
        RETURN_IF_ERROR(
665
6.37k
                _variant_stats_calculator->calculate_variant_stats(block, row_pos, num_rows));
666
6.37k
    }
667
668
9.00k
    RETURN_IF_ERROR(build_key_index(key_columns, seq_column, num_rows));
669
670
9.00k
    _num_rows_written += num_rows;
671
9.00k
    _olap_data_convertor->clear_source_content();
672
9.00k
    return Status::OK();
673
9.00k
}
674
675
Status SegmentWriter::build_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
676
9.03k
                                      IOlapColumnDataAccessor* seq_column, size_t num_rows) {
677
9.03k
    if (!_has_key) {
678
3.05k
        return Status::OK();
679
3.05k
    }
680
681
    // find all row pos for short key indexes
682
5.97k
    std::vector<size_t> short_key_pos;
683
5.97k
    if (UNLIKELY(_short_key_row_pos == 0 && _num_rows_written == 0)) {
684
3.35k
        short_key_pos.push_back(0);
685
3.35k
    }
686
16.7k
    while (_short_key_row_pos + _opts.num_rows_per_block < _num_rows_written + num_rows) {
687
10.7k
        _short_key_row_pos += _opts.num_rows_per_block;
688
10.7k
        short_key_pos.push_back(_short_key_row_pos - _num_rows_written);
689
10.7k
    }
690
691
5.97k
    if (_is_mow_with_cluster_key()) {
692
        // For CLUSTER BY tables:
693
        // 1) generate primary key index (unique keys)
694
8
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, num_rows, true));
695
        // 2) generate short key index (cluster keys)
696
8
        key_columns.clear();
697
160
        for (const auto& cid : _tablet_schema->cluster_key_uids()) {
698
160
            auto cluster_key_index = _tablet_schema->field_index(cid);
699
160
            if (cluster_key_index == -1) {
700
0
                return Status::InternalError("could not find cluster key column with unique_id=" +
701
0
                                             std::to_string(cid) + " in tablet schema");
702
0
            }
703
160
            bool found = false;
704
1.68k
            for (auto i = 0; i < _column_ids.size(); ++i) {
705
1.68k
                if (_column_ids[i] == cluster_key_index) {
706
160
                    auto converted_result = _olap_data_convertor->convert_column_data(i);
707
160
                    if (!converted_result.first.ok()) {
708
0
                        return converted_result.first;
709
0
                    }
710
160
                    key_columns.push_back(converted_result.second);
711
160
                    found = true;
712
160
                    break;
713
160
                }
714
1.68k
            }
715
160
            if (!found) {
716
0
                return Status::InternalError(
717
0
                        "could not found cluster key column with unique_id=" + std::to_string(cid) +
718
0
                        ", tablet schema index=" + std::to_string(cluster_key_index));
719
0
            }
720
160
        }
721
8
        return _generate_short_key_index(key_columns, num_rows, short_key_pos);
722
8
    }
723
5.96k
    if (_is_mow()) {
724
88
        return _generate_primary_key_index(key_columns, seq_column, num_rows, false);
725
88
    }
726
5.88k
    return _generate_short_key_index(key_columns, num_rows, short_key_pos);
727
5.96k
}
728
729
2.85k
int64_t SegmentWriter::max_row_to_add(size_t row_avg_size_in_bytes) {
730
2.85k
    auto segment_size = estimate_segment_size();
731
2.85k
    if (segment_size >= MAX_SEGMENT_SIZE || _num_rows_written >= _opts.max_rows_per_segment)
732
367
            [[unlikely]] {
733
367
        return 0;
734
367
    }
735
2.48k
    int64_t size_rows = ((int64_t)MAX_SEGMENT_SIZE - (int64_t)segment_size) / row_avg_size_in_bytes;
736
2.48k
    int64_t count_rows = (int64_t)_opts.max_rows_per_segment - _num_rows_written;
737
738
2.48k
    return std::min(size_rows, count_rows);
739
2.85k
}
740
741
// TODO(lingbin): Currently this function does not include the size of various indexes,
742
// We should make this more precise.
743
// NOTE: This function will be called when any row of data is added, so we need to
744
// make this function efficient.
745
3.33k
uint64_t SegmentWriter::estimate_segment_size() {
746
    // footer_size(4) + checksum(4) + segment_magic(4)
747
3.33k
    uint64_t size = 12;
748
12.8k
    for (auto& column_writer : _column_writers) {
749
12.8k
        size += column_writer->estimate_buffer_size();
750
12.8k
    }
751
3.33k
    if (_is_mow_with_cluster_key()) {
752
0
        size += _primary_key_index_builder->size() + _short_key_index_builder->size();
753
3.33k
    } else if (_is_mow()) {
754
55
        size += _primary_key_index_builder->size();
755
3.27k
    } else {
756
3.27k
        size += _short_key_index_builder->size();
757
3.27k
    }
758
759
    // update the mem_tracker of segment size
760
3.33k
    _mem_tracker->consume(size - _mem_tracker->consumption());
761
3.33k
    return size;
762
3.33k
}
763
764
4.39k
Status SegmentWriter::finalize_columns_data() {
765
4.39k
    if (_has_key) {
766
3.44k
        _row_count = _num_rows_written;
767
3.44k
    } else {
768
958
        DCHECK(_row_count == _num_rows_written)
769
0
                << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
770
958
        if (_row_count != _num_rows_written) {
771
0
            std::stringstream ss;
772
0
            ss << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
773
0
            LOG(WARNING) << ss.str();
774
0
            return Status::InternalError(ss.str());
775
0
        }
776
958
    }
777
4.39k
    _num_rows_written = 0;
778
779
15.3k
    for (auto& column_writer : _column_writers) {
780
15.3k
        RETURN_IF_ERROR(column_writer->finish());
781
15.3k
    }
782
4.39k
    RETURN_IF_ERROR(_write_data());
783
784
4.39k
    return Status::OK();
785
4.39k
}
786
787
4.39k
Status SegmentWriter::finalize_columns_index(uint64_t* index_size) {
788
4.39k
    uint64_t index_start = _file_writer->bytes_appended();
789
    // Record each index range separately. Vertical compaction writes column groups as
790
    // data+index pairs, so a single [first index, EOF) range would include later column data.
791
    // This SegmentWriter path is shared by cloud load, non-vertical compaction, schema change
792
    // final output, and vertical compaction via VerticalBetaRowsetWriter.
793
4.39k
    RETURN_IF_ERROR(_write_ordinal_index());
794
4.39k
    RETURN_IF_ERROR(_write_zone_map());
795
4.39k
    RETURN_IF_ERROR(_write_inverted_index());
796
4.39k
    RETURN_IF_ERROR(_write_ann_index());
797
4.39k
    RETURN_IF_ERROR(_write_bloom_filter_index());
798
799
4.39k
    *index_size = _file_writer->bytes_appended() - index_start;
800
4.39k
    if (_has_key) {
801
3.44k
        if (_is_mow_with_cluster_key()) {
802
            // 1. sort primary keys
803
8
            std::sort(_primary_keys.begin(), _primary_keys.end());
804
            // 2. write primary keys index
805
8
            std::string last_key;
806
24
            for (const auto& key : _primary_keys) {
807
24
                DCHECK(key.compare(last_key) > 0)
808
0
                        << "found duplicate key or key is not sorted! current key: " << key
809
0
                        << ", last key: " << last_key;
810
24
                RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
811
24
                last_key = key;
812
24
            }
813
814
8
            RETURN_IF_ERROR(_write_short_key_index());
815
8
            *index_size = _file_writer->bytes_appended() - index_start;
816
8
            RETURN_IF_ERROR(_write_primary_key_index());
817
8
            *index_size += _primary_key_index_builder->disk_size();
818
3.43k
        } else if (_is_mow()) {
819
163
            RETURN_IF_ERROR(_write_primary_key_index());
820
            // IndexedColumnWriter write data pages mixed with segment data, we should use
821
            // the stat from primary key index builder.
822
163
            *index_size += _primary_key_index_builder->disk_size();
823
3.27k
        } else {
824
3.27k
            RETURN_IF_ERROR(_write_short_key_index());
825
3.27k
            *index_size = _file_writer->bytes_appended() - index_start;
826
3.27k
        }
827
3.44k
    }
828
4.39k
    uint64_t file_index_end = _file_writer->bytes_appended();
829
4.39k
    _index_file_cache_info.add_index_range(index_start, file_index_end - index_start);
830
    // reset all column writers and data_conveter
831
4.39k
    clear();
832
833
4.39k
    return Status::OK();
834
4.39k
}
835
836
Status SegmentWriter::finalize_footer(uint64_t* segment_file_size,
837
3.44k
                                      SegmentIndexFileCacheInfo* index_file_cache_info) {
838
3.44k
    uint64_t footer_start = _file_writer->bytes_appended();
839
3.44k
    RETURN_IF_ERROR(_write_footer());
840
    // finish
841
3.44k
    RETURN_IF_ERROR(_file_writer->close(true));
842
3.44k
    *segment_file_size = _file_writer->bytes_appended();
843
    // The closed size completes the preload range recorded above. Local temporary rowsets, such as
844
    // schema-change internal sorting output, are filtered by SegmentIndexFileCacheLoader.
845
3.44k
    _index_file_cache_info.segment_file_size = *segment_file_size;
846
3.44k
    _index_file_cache_info.add_index_range(footer_start, *segment_file_size - footer_start);
847
3.44k
    if (index_file_cache_info != nullptr) {
848
3.35k
        *index_file_cache_info = _index_file_cache_info;
849
3.35k
    }
850
3.44k
    if (*segment_file_size == 0) {
851
0
        return Status::Corruption("Bad segment, file size = 0");
852
0
    }
853
3.44k
    return Status::OK();
854
3.44k
}
855
856
Status SegmentWriter::finalize(uint64_t* segment_file_size, uint64_t* index_size,
857
2.22k
                               SegmentIndexFileCacheInfo* index_file_cache_info) {
858
2.22k
    MonotonicStopWatch timer;
859
2.22k
    timer.start();
860
    // check disk capacity
861
2.22k
    if (_data_dir != nullptr && _data_dir->reach_capacity_limit((int64_t)estimate_segment_size())) {
862
0
        return Status::Error<DISK_REACH_CAPACITY_LIMIT>("disk {} exceed capacity limit, path: {}",
863
0
                                                        _data_dir->path_hash(), _data_dir->path());
864
0
    }
865
    // write data
866
2.22k
    RETURN_IF_ERROR(finalize_columns_data());
867
    // write index
868
2.22k
    RETURN_IF_ERROR(finalize_columns_index(index_size));
869
    // write footer
870
2.22k
    RETURN_IF_ERROR(finalize_footer(segment_file_size, index_file_cache_info));
871
872
2.22k
    if (timer.elapsed_time() > 5000000000l) {
873
0
        LOG(INFO) << "segment flush consumes a lot time_ns " << timer.elapsed_time()
874
0
                  << ", segmemt_size " << *segment_file_size;
875
0
    }
876
2.22k
    return Status::OK();
877
2.22k
}
878
879
4.42k
void SegmentWriter::clear() {
880
15.3k
    for (auto& column_writer : _column_writers) {
881
15.3k
        column_writer.reset();
882
15.3k
    }
883
4.42k
    _column_writers.clear();
884
4.42k
    _column_ids.clear();
885
4.42k
    _olap_data_convertor.reset();
886
4.42k
}
887
888
// write column data to file one by one
889
4.39k
Status SegmentWriter::_write_data() {
890
15.3k
    for (auto& column_writer : _column_writers) {
891
15.3k
        RETURN_IF_ERROR(column_writer->write_data());
892
893
15.3k
        auto* column_meta = column_writer->get_column_meta();
894
15.3k
        DCHECK(column_meta != nullptr);
895
15.3k
        column_meta->set_compressed_data_bytes(
896
15.3k
                (column_meta->has_compressed_data_bytes() ? column_meta->compressed_data_bytes()
897
15.3k
                                                          : 0) +
898
15.3k
                column_writer->get_total_compressed_data_pages_bytes());
899
15.3k
        column_meta->set_uncompressed_data_bytes(
900
15.3k
                (column_meta->has_uncompressed_data_bytes() ? column_meta->uncompressed_data_bytes()
901
15.3k
                                                            : 0) +
902
15.3k
                column_writer->get_total_uncompressed_data_pages_bytes());
903
15.3k
        column_meta->set_raw_data_bytes(
904
15.3k
                (column_meta->has_raw_data_bytes() ? column_meta->raw_data_bytes() : 0) +
905
15.3k
                column_writer->get_raw_data_bytes());
906
15.3k
    }
907
4.39k
    return Status::OK();
908
4.39k
}
909
910
// write ordinal index after data has been written
911
4.39k
Status SegmentWriter::_write_ordinal_index() {
912
15.3k
    for (auto& column_writer : _column_writers) {
913
15.3k
        RETURN_IF_ERROR(column_writer->write_ordinal_index());
914
15.3k
    }
915
4.39k
    return Status::OK();
916
4.39k
}
917
918
4.39k
Status SegmentWriter::_write_zone_map() {
919
15.3k
    for (auto& column_writer : _column_writers) {
920
15.3k
        RETURN_IF_ERROR(column_writer->write_zone_map());
921
15.3k
    }
922
4.39k
    return Status::OK();
923
4.39k
}
924
925
4.39k
Status SegmentWriter::_write_inverted_index() {
926
15.3k
    for (auto& column_writer : _column_writers) {
927
15.3k
        RETURN_IF_ERROR(column_writer->write_inverted_index());
928
15.3k
    }
929
4.39k
    return Status::OK();
930
4.39k
}
931
932
4.39k
Status SegmentWriter::_write_ann_index() {
933
15.3k
    for (auto& column_writer : _column_writers) {
934
15.3k
        RETURN_IF_ERROR(column_writer->write_ann_index());
935
15.3k
    }
936
4.39k
    return Status::OK();
937
4.39k
}
938
939
4.39k
Status SegmentWriter::_write_bloom_filter_index() {
940
15.3k
    for (auto& column_writer : _column_writers) {
941
15.3k
        RETURN_IF_ERROR(column_writer->write_bloom_filter_index());
942
15.3k
    }
943
4.39k
    return Status::OK();
944
4.39k
}
945
946
3.27k
Status SegmentWriter::_write_short_key_index() {
947
3.27k
    std::vector<Slice> body;
948
3.27k
    PageFooterPB footer;
949
3.27k
    RETURN_IF_ERROR(_short_key_index_builder->finalize(_row_count, &body, &footer));
950
3.27k
    PagePointer pp;
951
    // short key index page is not compressed right now
952
3.27k
    RETURN_IF_ERROR(PageIO::write_page(_file_writer, body, footer, &pp));
953
3.27k
    pp.to_proto(_footer.mutable_short_key_index_page());
954
3.27k
    return Status::OK();
955
3.27k
}
956
957
171
Status SegmentWriter::_write_primary_key_index() {
958
171
    CHECK_EQ(_primary_key_index_builder->num_rows(), _row_count);
959
171
    return _primary_key_index_builder->finalize(_footer.mutable_primary_key_index_meta());
960
171
}
961
962
3.44k
Status SegmentWriter::_write_footer() {
963
3.44k
    _footer.set_num_rows(_row_count);
964
    // Decide whether to externalize ColumnMetaPB by tablet default, and stamp footer version
965
3.44k
    if (_tablet_schema->storage_format() == TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V3) {
966
218
        _footer.set_version(SEGMENT_FOOTER_VERSION_V3_EXT_COL_META);
967
218
        VLOG_DEBUG << "use external column meta";
968
        // External ColumnMetaPB writing (optional)
969
218
        RETURN_IF_ERROR(ExternalColMetaUtil::write_external_column_meta(
970
218
                _file_writer, &_footer, _opts.compression_type,
971
218
                [this](const std::vector<Slice>& slices) { return _write_raw_data(slices); }));
972
218
    }
973
974
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
975
3.44k
    std::string footer_buf;
976
3.44k
    VLOG_DEBUG << "footer " << _footer.DebugString();
977
3.44k
    if (!_footer.SerializeToString(&footer_buf)) {
978
0
        return Status::InternalError("failed to serialize segment footer");
979
0
    }
980
981
3.44k
    faststring fixed_buf;
982
    // footer's size
983
3.44k
    put_fixed32_le(&fixed_buf, cast_set<uint32_t>(footer_buf.size()));
984
    // footer's checksum
985
3.44k
    uint32_t checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
986
3.44k
    put_fixed32_le(&fixed_buf, checksum);
987
    // Append magic number. we don't write magic number in the header because
988
    // that will need an extra seek when reading
989
3.44k
    fixed_buf.append(k_segment_magic, k_segment_magic_length);
990
991
3.44k
    std::vector<Slice> slices {footer_buf, fixed_buf};
992
3.44k
    return _write_raw_data(slices);
993
3.44k
}
994
995
6.05k
Status SegmentWriter::_write_raw_data(const std::vector<Slice>& slices) {
996
6.05k
    RETURN_IF_ERROR(_file_writer->appendv(&slices[0], slices.size()));
997
6.05k
    return Status::OK();
998
6.05k
}
999
1000
3.43k
Slice SegmentWriter::min_encoded_key() {
1001
3.43k
    return (_primary_key_index_builder == nullptr) ? Slice(_min_key.data(), _min_key.size())
1002
3.43k
                                                   : _primary_key_index_builder->min_key();
1003
3.43k
}
1004
3.43k
Slice SegmentWriter::max_encoded_key() {
1005
3.43k
    return (_primary_key_index_builder == nullptr) ? Slice(_max_key.data(), _max_key.size())
1006
3.43k
                                                   : _primary_key_index_builder->max_key();
1007
3.43k
}
1008
1009
24.8k
void SegmentWriter::set_min_max_key(const Slice& key) {
1010
24.8k
    if (UNLIKELY(_is_first_row)) {
1011
12
        _min_key.append(key.get_data(), key.get_size());
1012
12
        _is_first_row = false;
1013
12
    }
1014
24.8k
    if (key.compare(_max_key) > 0) {
1015
24.8k
        _max_key.clear();
1016
24.8k
        _max_key.append(key.get_data(), key.get_size());
1017
24.8k
    }
1018
24.8k
}
1019
1020
5.88k
void SegmentWriter::set_min_key(const Slice& key) {
1021
5.88k
    if (UNLIKELY(_is_first_row)) {
1022
3.26k
        _min_key.append(key.get_data(), key.get_size());
1023
3.26k
        _is_first_row = false;
1024
3.26k
    }
1025
5.88k
}
1026
1027
5.88k
void SegmentWriter::set_max_key(const Slice& key) {
1028
5.88k
    _max_key.clear();
1029
5.88k
    _max_key.append(key.get_data(), key.get_size());
1030
5.88k
}
1031
1032
Status SegmentWriter::_generate_primary_key_index(
1033
        const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
1034
100
        IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort) {
1035
100
    if (!need_sort) { // mow table without cluster key
1036
92
        std::string last_key;
1037
1.10k
        for (size_t pos = 0; pos < num_rows; pos++) {
1038
1.01k
            std::string key = encode_mow_key_invalidate_cache(
1039
1.01k
                    _key_encoder, primary_key_columns, seq_column, pos,
1040
1.01k
                    _tablet_schema->has_sequence_col(), _opts.rowset_ctx->tablet_id,
1041
1.01k
                    *_tablet_schema, _opts.write_type);
1042
1.01k
            DCHECK(key.compare(last_key) > 0)
1043
0
                    << "found duplicate key or key is not sorted! current key: " << key
1044
0
                    << ", last key: " << last_key;
1045
1.01k
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1046
1.01k
            last_key = std::move(key);
1047
1.01k
        }
1048
92
    } else { // mow table with cluster key
1049
        // generate primary keys in memory
1050
32
        for (uint32_t pos = 0; pos < num_rows; pos++) {
1051
24
            std::string key = _key_encoder.full_encode_primary_keys(primary_key_columns, pos);
1052
24
            MowKeyProbe::maybe_invalidate_row_cache(_opts.rowset_ctx->tablet_id, *_tablet_schema,
1053
24
                                                    _opts.write_type, key);
1054
24
            if (_tablet_schema->has_sequence_col()) {
1055
12
                _key_encoder.append_seq_suffix(&key, seq_column, pos);
1056
12
            }
1057
24
            _key_encoder.append_rowid_suffix(&key, pos + _num_rows_written);
1058
24
            _primary_keys_size += key.size();
1059
24
            _primary_keys.emplace_back(std::move(key));
1060
24
        }
1061
8
    }
1062
100
    return Status::OK();
1063
100
}
1064
1065
Status SegmentWriter::_generate_short_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
1066
                                                size_t num_rows,
1067
5.88k
                                                const std::vector<size_t>& short_key_pos) {
1068
5.88k
    set_min_key(_key_encoder.full_encode(key_columns, 0));
1069
5.88k
    set_max_key(_key_encoder.full_encode(key_columns, num_rows - 1));
1070
5.88k
    DCHECK(Slice(_max_key.data(), _max_key.size())
1071
0
                   .compare(Slice(_min_key.data(), _min_key.size())) >= 0)
1072
0
            << "key is not sorted! min key: " << _min_key << ", max key: " << _max_key;
1073
1074
5.88k
    key_columns.resize(_num_short_key_columns);
1075
5.88k
    std::string last_key;
1076
14.0k
    for (const auto pos : short_key_pos) {
1077
14.0k
        std::string key = _key_encoder.encode_short_keys(key_columns, pos);
1078
14.0k
        DCHECK(key.compare(last_key) >= 0)
1079
0
                << "key is not sorted! current key: " << key << ", last key: " << last_key;
1080
14.0k
        RETURN_IF_ERROR(_short_key_index_builder->add_item(key));
1081
14.0k
        last_key = std::move(key);
1082
14.0k
    }
1083
5.88k
    return Status::OK();
1084
5.88k
}
1085
1086
} // namespace segment_v2
1087
} // namespace doris