Coverage Report

Created: 2026-07-28 14:33

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