Coverage Report

Created: 2026-08-07 13:02

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