Coverage Report

Created: 2026-08-10 06:16

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.5k
inline std::string segment_mem_tracker_name(uint32_t segment_id) {
90
15.5k
    return "SegmentWriter:Segment-" + std::to_string(segment_id);
91
15.5k
}
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.5k
        : _segment_id(segment_id),
98
15.5k
          _tablet_schema(std::move(tablet_schema)),
99
15.5k
          _tablet(std::move(tablet)),
100
15.5k
          _data_dir(data_dir),
101
15.5k
          _opts(opts),
102
15.5k
          _file_writer(file_writer),
103
15.5k
          _index_file_writer(index_file_writer),
104
15.5k
          _mem_tracker(std::make_unique<MemTracker>(segment_mem_tracker_name(segment_id))),
105
15.5k
          _key_encoder(*_tablet_schema, _is_mow()),
106
15.5k
          _mow_context(std::move(opts.mow_ctx)) {
107
15.5k
    CHECK_NOTNULL(file_writer);
108
15.5k
    _num_short_key_columns = _tablet_schema->num_short_key_columns();
109
15.5k
}
110
111
15.6k
SegmentWriter::~SegmentWriter() {
112
15.6k
    _mem_tracker->release(_mem_tracker->consumption());
113
15.6k
}
114
115
void SegmentWriter::init_column_meta(ColumnMetaPB* meta, uint32_t column_id,
116
129k
                                     const TabletColumn& column, const ColumnWriterOptions& opts) {
117
129k
    meta->set_column_id(column_id);
118
129k
    meta->set_type(int(column.type()));
119
129k
    meta->set_length(column.length());
120
129k
    meta->set_encoding(EncodingInfo::resolve_default_encoding(opts.storage_format, column));
121
129k
    meta->set_compression(_opts.compression_type);
122
129k
    meta->set_is_nullable(column.is_nullable());
123
129k
    meta->set_default_value(column.default_value());
124
129k
    meta->set_precision(column.precision());
125
129k
    meta->set_frac(column.frac());
126
129k
    if (column.has_path_info()) {
127
3.70k
        column.path_info_ptr()->to_protobuf(meta->mutable_column_path_info(),
128
3.70k
                                            column.parent_unique_id());
129
3.70k
    }
130
129k
    meta->set_unique_id(column.unique_id());
131
140k
    for (uint32_t i = 0; i < column.get_subtype_count(); ++i) {
132
11.6k
        init_column_meta(meta->add_children_columns(), column_id, column.get_sub_column(i), opts);
133
11.6k
    }
134
129k
    meta->set_result_is_nullable(column.get_result_is_nullable());
135
129k
    meta->set_function_name(column.get_aggregation_name());
136
129k
    meta->set_be_exec_version(column.get_be_exec_version());
137
129k
    if (column.is_variant_type()) {
138
1.20k
        meta->set_variant_max_subcolumns_count(column.variant_max_subcolumns_count());
139
1.20k
        meta->set_variant_enable_doc_mode(column.variant_enable_doc_mode());
140
1.20k
    }
141
129k
}
142
143
6.43k
Status SegmentWriter::init() {
144
6.43k
    std::vector<uint32_t> column_ids;
145
6.43k
    auto column_cnt = cast_set<int>(_tablet_schema->num_columns());
146
41.1k
    for (uint32_t i = 0; i < column_cnt; ++i) {
147
34.7k
        column_ids.emplace_back(i);
148
34.7k
    }
149
6.43k
    return init(column_ids, true);
150
6.43k
}
151
152
Status SegmentWriter::_create_column_writer(uint32_t cid, const TabletColumn& column,
153
117k
                                            const TabletSchemaSPtr& schema) {
154
117k
    ColumnWriterOptions opts;
155
117k
    opts.meta = _footer.add_columns();
156
117k
    opts.storage_format = schema->storage_format();
157
158
117k
    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
117k
    opts.need_zone_map = column.is_key() || schema->keys_type() != KeysType::AGG_KEYS;
163
117k
    opts.need_bloom_filter = column.is_bf_column();
164
117k
    if (opts.need_bloom_filter) {
165
313
        opts.bf_options.fpp = schema->has_bf_fpp() ? schema->bloom_filter_fpp() : 0.05;
166
313
    }
167
117k
    auto* tablet_index = schema->get_ngram_bf_index(column.unique_id());
168
117k
    if (tablet_index) {
169
184
        opts.need_bloom_filter = true;
170
184
        opts.is_ngram_bf_index = true;
171
        //narrow convert from int32_t to uint8_t and uint16_t which is dangerous
172
184
        auto gram_size = tablet_index->get_gram_size();
173
184
        auto gram_bf_size = tablet_index->get_gram_bf_size();
174
184
        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
184
        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
184
        opts.gram_size = cast_set<uint8_t>(gram_size);
183
184
        opts.gram_bf_size = cast_set<uint16_t>(gram_bf_size);
184
184
    }
185
186
117k
    bool skip_inverted_index = false;
187
117k
    if (_opts.rowset_ctx != nullptr) {
188
        // skip write inverted index for index compaction column
189
115k
        skip_inverted_index =
190
115k
                _opts.rowset_ctx->columns_to_do_index_compaction.count(column.unique_id()) > 0;
191
115k
    }
192
    // skip write inverted index on load if skip_write_index_on_load is true
193
117k
    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
117k
    if (!skip_inverted_index) {
198
116k
        auto inverted_indexs = schema->inverted_indexs(column);
199
116k
        if (!inverted_indexs.empty()) {
200
4.26k
            opts.inverted_indexes = inverted_indexs;
201
4.26k
            opts.need_inverted_index = true;
202
4.26k
            DCHECK(_index_file_writer != nullptr);
203
4.26k
        }
204
116k
    }
205
    // indexes for this column
206
117k
    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
117k
    opts.index_file_writer = _index_file_writer;
213
214
117k
#define DISABLE_INDEX_IF_FIELD_TYPE(TYPE)                     \
215
1.05M
    if (column.type() == FieldType::OLAP_FIELD_TYPE_##TYPE) { \
216
7.32k
        opts.need_zone_map = false;                           \
217
7.32k
        opts.need_bloom_filter = false;                       \
218
7.32k
    }
219
220
117k
    DISABLE_INDEX_IF_FIELD_TYPE(STRUCT)
221
117k
    DISABLE_INDEX_IF_FIELD_TYPE(ARRAY)
222
117k
    DISABLE_INDEX_IF_FIELD_TYPE(JSONB)
223
117k
    DISABLE_INDEX_IF_FIELD_TYPE(AGG_STATE)
224
117k
    DISABLE_INDEX_IF_FIELD_TYPE(MAP)
225
117k
    DISABLE_INDEX_IF_FIELD_TYPE(BITMAP)
226
117k
    DISABLE_INDEX_IF_FIELD_TYPE(HLL)
227
117k
    DISABLE_INDEX_IF_FIELD_TYPE(QUANTILE_STATE)
228
117k
    DISABLE_INDEX_IF_FIELD_TYPE(VARIANT)
229
230
117k
#undef DISABLE_INDEX_IF_FIELD_TYPE
231
232
117k
    int64_t storage_page_size = _tablet_schema->storage_page_size();
233
    // storage_page_size must be between 4KB and 10MB.
234
117k
    if (storage_page_size >= 4096 && storage_page_size <= 10485760) {
235
117k
        opts.data_page_size = storage_page_size;
236
117k
    }
237
117k
    opts.dict_page_size = _tablet_schema->storage_dict_page_size();
238
117k
    DBUG_EXECUTE_IF("VerticalSegmentWriter._create_column_writer.storage_page_size", {
239
117k
        auto table_id = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
240
117k
                "VerticalSegmentWriter._create_column_writer.storage_page_size", "table_id",
241
117k
                INT_MIN);
242
117k
        auto target_data_page_size = DebugPoints::instance()->get_debug_param_or_default<int64_t>(
243
117k
                "VerticalSegmentWriter._create_column_writer.storage_page_size",
244
117k
                "storage_page_size", INT_MIN);
245
117k
        if (table_id == INT_MIN || target_data_page_size == INT_MIN) {
246
117k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
247
117k
                    "Debug point parameters missing: either 'table_id' or 'storage_page_size' not "
248
117k
                    "set.");
249
117k
        }
250
117k
        if (table_id == _tablet_schema->table_id() &&
251
117k
            opts.data_page_size != target_data_page_size) {
252
117k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
253
117k
                    "Mismatch in 'storage_page_size': expected size does not match the current "
254
117k
                    "data page size. "
255
117k
                    "Expected: " +
256
117k
                    std::to_string(target_data_page_size) +
257
117k
                    ", Actual: " + std::to_string(opts.data_page_size) + ".");
258
117k
        }
259
117k
    })
260
117k
    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
174
        auto page_size = _tablet_schema->row_store_page_size();
264
174
        opts.data_page_size =
265
174
                (page_size > 0) ? page_size : segment_v2::ROW_STORE_PAGE_SIZE_DEFAULT_VALUE;
266
174
    }
267
268
117k
    opts.rowset_ctx = _opts.rowset_ctx;
269
117k
    opts.file_writer = _file_writer;
270
117k
    opts.compression_type = _opts.compression_type;
271
117k
    opts.footer = &_footer;
272
117k
    if (_opts.rowset_ctx != nullptr) {
273
115k
        opts.input_rs_readers = _opts.rowset_ctx->input_rs_readers;
274
115k
    }
275
276
117k
    std::unique_ptr<ColumnWriter> writer;
277
117k
    RETURN_IF_ERROR(ColumnWriter::create(opts, &column, _file_writer, &writer));
278
117k
    RETURN_IF_ERROR(writer->init());
279
117k
    _column_writers.push_back(std::move(writer));
280
281
117k
    _olap_data_convertor->add_column_data_convertor(column);
282
117k
    return Status::OK();
283
117k
}
284
285
29.3k
Status SegmentWriter::init(const std::vector<uint32_t>& col_ids, bool has_key) {
286
29.3k
    DCHECK(_column_writers.empty());
287
29.3k
    DCHECK(_column_ids.empty());
288
29.3k
    _has_key = has_key;
289
29.3k
    _column_writers.reserve(_tablet_schema->columns().size());
290
29.3k
    _column_ids.insert(_column_ids.end(), col_ids.begin(), col_ids.end());
291
29.3k
    _olap_data_convertor = std::make_unique<OlapBlockDataConvertor>();
292
29.3k
    if (_opts.compression_type == UNKNOWN_COMPRESSION) {
293
15.5k
        _opts.compression_type = _tablet_schema->compression_type();
294
15.5k
    }
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
29.3k
    const int variant_stats_footer_offset = _footer.columns_size();
299
29.3k
    RETURN_IF_ERROR(_create_writers(_tablet_schema, col_ids));
300
301
    // Initialize variant statistics calculator
302
29.3k
    _variant_stats_calculator = std::make_unique<VariantStatsCaculator>(
303
29.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
29.3k
    if (_has_key) {
307
15.5k
        if (_is_mow()) {
308
5.92k
            size_t seq_col_length = 0;
309
5.92k
            if (_tablet_schema->has_sequence_col()) {
310
152
                seq_col_length =
311
152
                        _tablet_schema->column(_tablet_schema->sequence_col_idx()).length() + 1;
312
152
            }
313
5.92k
            size_t rowid_length = 0;
314
5.92k
            if (_is_mow_with_cluster_key()) {
315
170
                rowid_length = PrimaryKeyIndexReader::ROW_ID_LENGTH;
316
170
                _short_key_index_builder.reset(
317
170
                        new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
318
170
            }
319
5.92k
            _primary_key_index_builder.reset(
320
5.92k
                    new PrimaryKeyIndexBuilder(_file_writer, seq_col_length, rowid_length));
321
5.92k
            RETURN_IF_ERROR(_primary_key_index_builder->init());
322
9.67k
        } else {
323
9.67k
            _short_key_index_builder.reset(
324
9.67k
                    new ShortKeyIndexBuilder(_segment_id, _opts.num_rows_per_block));
325
9.67k
        }
326
15.5k
    }
327
29.3k
    return Status::OK();
328
29.3k
}
329
330
Status SegmentWriter::_create_writers(const TabletSchemaSPtr& tablet_schema,
331
29.3k
                                      const std::vector<uint32_t>& col_ids) {
332
29.3k
    _olap_data_convertor->reserve(col_ids.size());
333
117k
    for (auto& cid : col_ids) {
334
117k
        RETURN_IF_ERROR(_create_column_writer(cid, tablet_schema->column(cid), tablet_schema));
335
117k
    }
336
29.3k
    return Status::OK();
337
29.3k
}
338
339
12
void SegmentWriter::_serialize_block_to_row_column(Block& block) {
340
12
    if (block.rows() == 0) {
341
0
        return;
342
0
    }
343
12
    MonotonicStopWatch watch;
344
12
    watch.start();
345
12
    int row_column_id = 0;
346
308
    for (int i = 0; i < _tablet_schema->num_columns(); ++i) {
347
300
        if (_tablet_schema->column(i).is_row_store_column()) {
348
4
            auto row_store_column_ptr = block.get_by_position(i).column->clone_empty();
349
4
            auto* row_store_column = static_cast<ColumnString*>(row_store_column_ptr.get());
350
4
            DataTypeSerDeSPtrs serdes = create_data_type_serdes(block.get_data_types());
351
4
            JsonbSerializeUtil::block_to_jsonb(*_tablet_schema, block, *row_store_column,
352
4
                                               cast_set<int>(_tablet_schema->num_columns()), serdes,
353
4
                                               {_tablet_schema->row_columns_uids().begin(),
354
4
                                                _tablet_schema->row_columns_uids().end()});
355
4
            block.replace_by_position(i, std::move(row_store_column_ptr));
356
4
            break;
357
4
        }
358
300
    }
359
360
12
    VLOG_DEBUG << "serialize , num_rows:" << block.rows() << ", row_column_id:" << row_column_id
361
0
               << ", total_byte_size:" << block.allocated_bytes() << ", serialize_cost(us)"
362
0
               << watch.elapsed_time() / 1000;
363
12
}
364
365
Status SegmentWriter::probe_key_for_mow(
366
        const MowKeyProbe& probe, std::string key, std::size_t segment_pos,
367
        bool have_input_seq_column, bool have_delete_sign,
368
        const std::vector<RowsetSharedPtr>& specified_rowsets,
369
        std::vector<std::unique_ptr<SegmentCacheHandle>>& segment_caches,
370
        bool& has_default_or_nullable, std::vector<bool>& use_default_or_null_flag,
371
        const std::function<void(const RowLocation& loc, const RowsetSharedPtr& rowset)>& found_cb,
372
36
        const std::function<Status()>& not_found_cb, PartialUpdateStats& stats) {
373
36
    ProbeOutcome outcome =
374
36
            DORIS_TRY(probe.probe(key, segment_pos, have_input_seq_column, have_delete_sign,
375
36
                                  specified_rowsets, segment_caches, stats));
376
36
    if (outcome.result == KeyProbeResult::NOT_FOUND) {
377
12
        if (!have_delete_sign) {
378
12
            RETURN_IF_ERROR(not_found_cb());
379
12
        }
380
12
        has_default_or_nullable = true;
381
12
        use_default_or_null_flag.emplace_back(true);
382
12
        return Status::OK();
383
12
    }
384
24
    if (outcome.use_default_or_null) {
385
0
        has_default_or_nullable = true;
386
0
        use_default_or_null_flag.emplace_back(true);
387
24
    } else {
388
        // partial update should not contain invisible columns
389
24
        use_default_or_null_flag.emplace_back(false);
390
24
        found_cb(outcome.loc, outcome.rowset);
391
24
    }
392
24
    return Status::OK();
393
36
}
394
395
12
Status SegmentWriter::partial_update_preconditions_check(size_t row_pos) {
396
12
    if (!_is_mow()) {
397
0
        auto msg = fmt::format(
398
0
                "Can only do partial update on merge-on-write unique table, but found: "
399
0
                "keys_type={}, _opts.enable_unique_key_merge_on_write={}, tablet_id={}",
400
0
                _tablet_schema->keys_type(), _opts.enable_unique_key_merge_on_write,
401
0
                _tablet->tablet_id());
402
0
        DCHECK(false) << msg;
403
0
        return Status::InternalError<false>(msg);
404
0
    }
405
12
    if (_opts.rowset_ctx->partial_update_info == nullptr) {
406
0
        auto msg =
407
0
                fmt::format("partial_update_info should not be nullptr, please check, tablet_id={}",
408
0
                            _tablet->tablet_id());
409
0
        DCHECK(false) << msg;
410
0
        return Status::InternalError<false>(msg);
411
0
    }
412
12
    if (!_opts.rowset_ctx->partial_update_info->is_fixed_partial_update()) {
413
0
        auto msg = fmt::format(
414
0
                "in fixed partial update code, but update_mode={}, please check, tablet_id={}",
415
0
                _opts.rowset_ctx->partial_update_info->update_mode(), _tablet->tablet_id());
416
0
        DCHECK(false) << msg;
417
0
        return Status::InternalError<false>(msg);
418
0
    }
419
12
    if (row_pos != 0) {
420
0
        auto msg = fmt::format("row_pos should be 0, but found {}, tablet_id={}", row_pos,
421
0
                               _tablet->tablet_id());
422
0
        DCHECK(false) << msg;
423
0
        return Status::InternalError<false>(msg);
424
0
    }
425
12
    return Status::OK();
426
12
}
427
428
// for partial update, we should do following steps to fill content of block:
429
// 1. set block data to data convertor, and get all key_column's converted slice
430
// 2. get pk of input block, and read missing columns
431
//       2.1 first find key location{rowset_id, segment_id, row_id}
432
//       2.2 build read plan to read by batch
433
//       2.3 fill block
434
// 3. set columns to data convertor and then write all columns
435
Status SegmentWriter::append_block_with_partial_content(const Block* block, size_t row_pos,
436
12
                                                        size_t num_rows) {
437
12
    if (block->columns() < _tablet_schema->num_key_columns() ||
438
12
        block->columns() >= _tablet_schema->num_columns()) {
439
0
        return Status::InvalidArgument(
440
0
                fmt::format("illegal partial update block columns: {}, num key columns: {}, total "
441
0
                            "schema columns: {}",
442
0
                            block->columns(), _tablet_schema->num_key_columns(),
443
0
                            _tablet_schema->num_columns()));
444
0
    }
445
12
    RETURN_IF_ERROR(partial_update_preconditions_check(row_pos));
446
447
    // find missing column cids
448
12
    const auto& missing_cids = _opts.rowset_ctx->partial_update_info->missing_cids;
449
12
    const auto& including_cids = _opts.rowset_ctx->partial_update_info->update_cids;
450
451
    // create full block and fill with input columns
452
12
    auto full_block = _tablet_schema->create_block();
453
12
    size_t input_id = 0;
454
260
    for (auto i : including_cids) {
455
260
        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
42.3k
Status SegmentWriter::append_block(const Block* block, size_t row_pos, size_t num_rows) {
612
42.3k
    if (_opts.rowset_ctx->partial_update_info &&
613
42.3k
        _opts.rowset_ctx->partial_update_info->is_partial_update() &&
614
42.3k
        _opts.write_type == DataWriteType::TYPE_DIRECT &&
615
42.3k
        !_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
42.3k
    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
18.4E
    CHECK(block->columns() >= _column_writers.size())
634
18.4E
            << ", block->columns()=" << block->columns()
635
18.4E
            << ", _column_writers.size()=" << _column_writers.size()
636
18.4E
            << ", _tablet_schema->dump_structure()=" << _tablet_schema->dump_structure();
637
    // Blocks from the seams arrive already transformed (variants parsed, row-store
638
    // column materialized); compaction-family callers bring rows that are already final.
639
42.3k
    _olap_data_convertor->set_source_content(block, row_pos, num_rows);
640
641
    // convert column data from engine format to storage layer format
642
42.3k
    std::vector<IOlapColumnDataAccessor*> key_columns;
643
42.3k
    IOlapColumnDataAccessor* seq_column = nullptr;
644
204k
    for (size_t id = 0; id < _column_writers.size(); ++id) {
645
        // olap data convertor alway start from id = 0
646
162k
        auto converted_result = _olap_data_convertor->convert_column_data(id);
647
162k
        if (!converted_result.first.ok()) {
648
0
            return converted_result.first;
649
0
        }
650
162k
        auto cid = _column_ids[id];
651
162k
        if (_has_key && cid < _tablet_schema->num_key_columns()) {
652
47.2k
            key_columns.push_back(converted_result.second);
653
115k
        } else if (_has_key && _tablet_schema->has_sequence_col() &&
654
115k
                   cid == _tablet_schema->sequence_col_idx()) {
655
208
            seq_column = converted_result.second;
656
208
        }
657
162k
        RETURN_IF_ERROR(_column_writers[id]->append(converted_result.second->get_nullmap(),
658
162k
                                                    converted_result.second->get_data(), num_rows));
659
162k
    }
660
42.3k
    if (_opts.write_type == DataWriteType::TYPE_COMPACTION) {
661
34.6k
        RETURN_IF_ERROR(
662
34.6k
                _variant_stats_calculator->calculate_variant_stats(block, row_pos, num_rows));
663
34.6k
    }
664
665
42.3k
    RETURN_IF_ERROR(build_key_index(key_columns, seq_column, num_rows));
666
667
42.3k
    _num_rows_written += num_rows;
668
42.3k
    _olap_data_convertor->clear_source_content();
669
42.3k
    return Status::OK();
670
42.3k
}
671
672
Status SegmentWriter::build_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
673
42.3k
                                      IOlapColumnDataAccessor* seq_column, size_t num_rows) {
674
42.3k
    if (!_has_key) {
675
21.6k
        return Status::OK();
676
21.6k
    }
677
678
    // find all row pos for short key indexes
679
20.7k
    std::vector<size_t> short_key_pos;
680
20.7k
    if (UNLIKELY(_short_key_row_pos == 0 && _num_rows_written == 0)) {
681
15.5k
        short_key_pos.push_back(0);
682
15.5k
    }
683
40.9k
    while (_short_key_row_pos + _opts.num_rows_per_block < _num_rows_written + num_rows) {
684
20.1k
        _short_key_row_pos += _opts.num_rows_per_block;
685
20.1k
        short_key_pos.push_back(_short_key_row_pos - _num_rows_written);
686
20.1k
    }
687
688
20.7k
    if (_is_mow_with_cluster_key()) {
689
        // For CLUSTER BY tables:
690
        // 1) generate primary key index (unique keys)
691
262
        RETURN_IF_ERROR(_generate_primary_key_index(key_columns, seq_column, num_rows, true));
692
        // 2) generate short key index (cluster keys)
693
262
        key_columns.clear();
694
1.66k
        for (const auto& cid : _tablet_schema->cluster_key_uids()) {
695
1.66k
            auto cluster_key_index = _tablet_schema->field_index(cid);
696
1.66k
            if (cluster_key_index == -1) {
697
0
                return Status::InternalError("could not find cluster key column with unique_id=" +
698
0
                                             std::to_string(cid) + " in tablet schema");
699
0
            }
700
1.66k
            bool found = false;
701
14.8k
            for (auto i = 0; i < _column_ids.size(); ++i) {
702
14.8k
                if (_column_ids[i] == cluster_key_index) {
703
1.66k
                    auto converted_result = _olap_data_convertor->convert_column_data(i);
704
1.66k
                    if (!converted_result.first.ok()) {
705
0
                        return converted_result.first;
706
0
                    }
707
1.66k
                    key_columns.push_back(converted_result.second);
708
1.66k
                    found = true;
709
1.66k
                    break;
710
1.66k
                }
711
14.8k
            }
712
1.66k
            if (!found) {
713
0
                return Status::InternalError(
714
0
                        "could not found cluster key column with unique_id=" + std::to_string(cid) +
715
0
                        ", tablet schema index=" + std::to_string(cluster_key_index));
716
0
            }
717
1.66k
        }
718
262
        return _generate_short_key_index(key_columns, num_rows, short_key_pos);
719
262
    }
720
20.4k
    if (_is_mow()) {
721
6.21k
        return _generate_primary_key_index(key_columns, seq_column, num_rows, false);
722
6.21k
    }
723
14.2k
    return _generate_short_key_index(key_columns, num_rows, short_key_pos);
724
20.4k
}
725
726
7.92k
int64_t SegmentWriter::max_row_to_add(size_t row_avg_size_in_bytes) {
727
7.92k
    auto segment_size = estimate_segment_size();
728
7.92k
    if (segment_size >= MAX_SEGMENT_SIZE || _num_rows_written >= _opts.max_rows_per_segment)
729
367
            [[unlikely]] {
730
367
        return 0;
731
367
    }
732
7.55k
    int64_t size_rows = ((int64_t)MAX_SEGMENT_SIZE - (int64_t)segment_size) / row_avg_size_in_bytes;
733
7.55k
    int64_t count_rows = (int64_t)_opts.max_rows_per_segment - _num_rows_written;
734
735
7.55k
    return std::min(size_rows, count_rows);
736
7.92k
}
737
738
// TODO(lingbin): Currently this function does not include the size of various indexes,
739
// We should make this more precise.
740
// NOTE: This function will be called when any row of data is added, so we need to
741
// make this function efficient.
742
8.38k
uint64_t SegmentWriter::estimate_segment_size() {
743
    // footer_size(4) + checksum(4) + segment_magic(4)
744
8.38k
    uint64_t size = 12;
745
44.8k
    for (auto& column_writer : _column_writers) {
746
44.8k
        size += column_writer->estimate_buffer_size();
747
44.8k
    }
748
8.38k
    if (_is_mow_with_cluster_key()) {
749
199
        size += _primary_key_index_builder->size() + _short_key_index_builder->size();
750
8.18k
    } else if (_is_mow()) {
751
488
        size += _primary_key_index_builder->size();
752
7.69k
    } else {
753
7.69k
        size += _short_key_index_builder->size();
754
7.69k
    }
755
756
    // update the mem_tracker of segment size
757
8.38k
    _mem_tracker->consume(size - _mem_tracker->consumption());
758
8.38k
    return size;
759
8.38k
}
760
761
29.3k
Status SegmentWriter::finalize_columns_data() {
762
29.3k
    if (_has_key) {
763
15.5k
        _row_count = _num_rows_written;
764
15.5k
    } else {
765
18.4E
        DCHECK(_row_count == _num_rows_written)
766
18.4E
                << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
767
13.7k
        if (_row_count != _num_rows_written) {
768
0
            std::stringstream ss;
769
0
            ss << "_row_count != _num_rows_written:" << _row_count << " vs. " << _num_rows_written;
770
0
            LOG(WARNING) << ss.str();
771
0
            return Status::InternalError(ss.str());
772
0
        }
773
13.7k
    }
774
29.3k
    _num_rows_written = 0;
775
776
117k
    for (auto& column_writer : _column_writers) {
777
117k
        RETURN_IF_ERROR(column_writer->finish());
778
117k
    }
779
29.3k
    RETURN_IF_ERROR(_write_data());
780
781
29.3k
    return Status::OK();
782
29.3k
}
783
784
29.3k
Status SegmentWriter::finalize_columns_index(uint64_t* index_size) {
785
29.3k
    uint64_t index_start = _file_writer->bytes_appended();
786
    // Record each index range separately. Vertical compaction writes column groups as
787
    // data+index pairs, so a single [first index, EOF) range would include later column data.
788
    // This SegmentWriter path is shared by cloud load, non-vertical compaction, schema change
789
    // final output, and vertical compaction via VerticalBetaRowsetWriter.
790
29.3k
    RETURN_IF_ERROR(_write_ordinal_index());
791
29.3k
    RETURN_IF_ERROR(_write_zone_map());
792
29.3k
    RETURN_IF_ERROR(_write_inverted_index());
793
29.3k
    RETURN_IF_ERROR(_write_ann_index());
794
29.3k
    RETURN_IF_ERROR(_write_bloom_filter_index());
795
796
29.3k
    *index_size = _file_writer->bytes_appended() - index_start;
797
29.3k
    if (_has_key) {
798
15.5k
        if (_is_mow_with_cluster_key()) {
799
            // 1. sort primary keys
800
170
            std::sort(_primary_keys.begin(), _primary_keys.end());
801
            // 2. write primary keys index
802
170
            std::string last_key;
803
420k
            for (const auto& key : _primary_keys) {
804
420k
                DCHECK(key.compare(last_key) > 0)
805
0
                        << "found duplicate key or key is not sorted! current key: " << key
806
0
                        << ", last key: " << last_key;
807
420k
                RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
808
420k
                last_key = key;
809
420k
            }
810
811
170
            RETURN_IF_ERROR(_write_short_key_index());
812
170
            *index_size = _file_writer->bytes_appended() - index_start;
813
170
            RETURN_IF_ERROR(_write_primary_key_index());
814
170
            *index_size += _primary_key_index_builder->disk_size();
815
15.4k
        } else if (_is_mow()) {
816
5.75k
            RETURN_IF_ERROR(_write_primary_key_index());
817
            // IndexedColumnWriter write data pages mixed with segment data, we should use
818
            // the stat from primary key index builder.
819
5.75k
            *index_size += _primary_key_index_builder->disk_size();
820
9.66k
        } else {
821
9.66k
            RETURN_IF_ERROR(_write_short_key_index());
822
9.66k
            *index_size = _file_writer->bytes_appended() - index_start;
823
9.66k
        }
824
15.5k
    }
825
29.3k
    uint64_t file_index_end = _file_writer->bytes_appended();
826
29.3k
    _index_file_cache_info.add_index_range(index_start, file_index_end - index_start);
827
    // reset all column writers and data_conveter
828
29.3k
    clear();
829
830
29.3k
    return Status::OK();
831
29.3k
}
832
833
Status SegmentWriter::finalize_footer(uint64_t* segment_file_size,
834
15.5k
                                      SegmentIndexFileCacheInfo* index_file_cache_info) {
835
15.5k
    uint64_t footer_start = _file_writer->bytes_appended();
836
15.5k
    RETURN_IF_ERROR(_write_footer());
837
    // finish
838
15.5k
    RETURN_IF_ERROR(_file_writer->close(true));
839
15.5k
    *segment_file_size = _file_writer->bytes_appended();
840
    // The closed size completes the preload range recorded above. Local temporary rowsets, such as
841
    // schema-change internal sorting output, are filtered by SegmentIndexFileCacheLoader.
842
15.5k
    _index_file_cache_info.segment_file_size = *segment_file_size;
843
15.5k
    _index_file_cache_info.add_index_range(footer_start, *segment_file_size - footer_start);
844
15.5k
    if (index_file_cache_info != nullptr) {
845
15.5k
        *index_file_cache_info = _index_file_cache_info;
846
15.5k
    }
847
15.5k
    if (*segment_file_size == 0) {
848
0
        return Status::Corruption("Bad segment, file size = 0");
849
0
    }
850
15.5k
    return Status::OK();
851
15.5k
}
852
853
Status SegmentWriter::finalize(uint64_t* segment_file_size, uint64_t* index_size,
854
6.43k
                               SegmentIndexFileCacheInfo* index_file_cache_info) {
855
6.43k
    MonotonicStopWatch timer;
856
6.43k
    timer.start();
857
    // check disk capacity
858
6.43k
    if (_data_dir != nullptr && _data_dir->reach_capacity_limit((int64_t)estimate_segment_size())) {
859
0
        return Status::Error<DISK_REACH_CAPACITY_LIMIT>("disk {} exceed capacity limit, path: {}",
860
0
                                                        _data_dir->path_hash(), _data_dir->path());
861
0
    }
862
    // write data
863
6.43k
    RETURN_IF_ERROR(finalize_columns_data());
864
    // write index
865
6.43k
    RETURN_IF_ERROR(finalize_columns_index(index_size));
866
    // write footer
867
6.43k
    RETURN_IF_ERROR(finalize_footer(segment_file_size, index_file_cache_info));
868
869
6.43k
    if (timer.elapsed_time() > 5000000000l) {
870
3
        LOG(INFO) << "segment flush consumes a lot time_ns " << timer.elapsed_time()
871
3
                  << ", segmemt_size " << *segment_file_size;
872
3
    }
873
6.43k
    return Status::OK();
874
6.43k
}
875
876
29.3k
void SegmentWriter::clear() {
877
117k
    for (auto& column_writer : _column_writers) {
878
117k
        column_writer.reset();
879
117k
    }
880
29.3k
    _column_writers.clear();
881
29.3k
    _column_ids.clear();
882
29.3k
    _olap_data_convertor.reset();
883
29.3k
}
884
885
// write column data to file one by one
886
29.3k
Status SegmentWriter::_write_data() {
887
117k
    for (auto& column_writer : _column_writers) {
888
117k
        RETURN_IF_ERROR(column_writer->write_data());
889
890
117k
        auto* column_meta = column_writer->get_column_meta();
891
117k
        DCHECK(column_meta != nullptr);
892
117k
        column_meta->set_compressed_data_bytes(
893
117k
                (column_meta->has_compressed_data_bytes() ? column_meta->compressed_data_bytes()
894
117k
                                                          : 0) +
895
117k
                column_writer->get_total_compressed_data_pages_bytes());
896
117k
        column_meta->set_uncompressed_data_bytes(
897
117k
                (column_meta->has_uncompressed_data_bytes() ? column_meta->uncompressed_data_bytes()
898
117k
                                                            : 0) +
899
117k
                column_writer->get_total_uncompressed_data_pages_bytes());
900
117k
        column_meta->set_raw_data_bytes(
901
117k
                (column_meta->has_raw_data_bytes() ? column_meta->raw_data_bytes() : 0) +
902
117k
                column_writer->get_raw_data_bytes());
903
117k
    }
904
29.3k
    return Status::OK();
905
29.3k
}
906
907
// write ordinal index after data has been written
908
29.3k
Status SegmentWriter::_write_ordinal_index() {
909
117k
    for (auto& column_writer : _column_writers) {
910
117k
        RETURN_IF_ERROR(column_writer->write_ordinal_index());
911
117k
    }
912
29.3k
    return Status::OK();
913
29.3k
}
914
915
29.3k
Status SegmentWriter::_write_zone_map() {
916
117k
    for (auto& column_writer : _column_writers) {
917
117k
        RETURN_IF_ERROR(column_writer->write_zone_map());
918
117k
    }
919
29.3k
    return Status::OK();
920
29.3k
}
921
922
29.3k
Status SegmentWriter::_write_inverted_index() {
923
117k
    for (auto& column_writer : _column_writers) {
924
117k
        RETURN_IF_ERROR(column_writer->write_inverted_index());
925
117k
    }
926
29.3k
    return Status::OK();
927
29.3k
}
928
929
29.3k
Status SegmentWriter::_write_ann_index() {
930
117k
    for (auto& column_writer : _column_writers) {
931
117k
        RETURN_IF_ERROR(column_writer->write_ann_index());
932
117k
    }
933
29.3k
    return Status::OK();
934
29.3k
}
935
936
29.3k
Status SegmentWriter::_write_bloom_filter_index() {
937
117k
    for (auto& column_writer : _column_writers) {
938
117k
        RETURN_IF_ERROR(column_writer->write_bloom_filter_index());
939
117k
    }
940
29.3k
    return Status::OK();
941
29.3k
}
942
943
9.83k
Status SegmentWriter::_write_short_key_index() {
944
9.83k
    std::vector<Slice> body;
945
9.83k
    PageFooterPB footer;
946
9.83k
    RETURN_IF_ERROR(_short_key_index_builder->finalize(_row_count, &body, &footer));
947
9.83k
    PagePointer pp;
948
    // short key index page is not compressed right now
949
9.83k
    RETURN_IF_ERROR(PageIO::write_page(_file_writer, body, footer, &pp));
950
9.83k
    pp.to_proto(_footer.mutable_short_key_index_page());
951
9.83k
    return Status::OK();
952
9.83k
}
953
954
5.92k
Status SegmentWriter::_write_primary_key_index() {
955
5.92k
    CHECK_EQ(_primary_key_index_builder->num_rows(), _row_count);
956
5.92k
    return _primary_key_index_builder->finalize(_footer.mutable_primary_key_index_meta());
957
5.92k
}
958
959
15.5k
Status SegmentWriter::_write_footer() {
960
15.5k
    _footer.set_num_rows(_row_count);
961
    // Decide whether to externalize ColumnMetaPB by tablet default, and stamp footer version
962
15.5k
    if (_tablet_schema->storage_format() == TabletStorageFormatPB::TABLET_STORAGE_FORMAT_V3) {
963
5.53k
        _footer.set_version(SEGMENT_FOOTER_VERSION_V3_EXT_COL_META);
964
5.53k
        VLOG_DEBUG << "use external column meta";
965
        // External ColumnMetaPB writing (optional)
966
5.53k
        RETURN_IF_ERROR(ExternalColMetaUtil::write_external_column_meta(
967
5.53k
                _file_writer, &_footer, _opts.compression_type,
968
5.53k
                [this](const std::vector<Slice>& slices) { return _write_raw_data(slices); }));
969
5.53k
    }
970
971
    // Footer := SegmentFooterPB, FooterPBSize(4), FooterPBChecksum(4), MagicNumber(4)
972
15.5k
    std::string footer_buf;
973
18.4E
    VLOG_DEBUG << "footer " << _footer.DebugString();
974
15.5k
    if (!_footer.SerializeToString(&footer_buf)) {
975
0
        return Status::InternalError("failed to serialize segment footer");
976
0
    }
977
978
15.5k
    faststring fixed_buf;
979
    // footer's size
980
15.5k
    put_fixed32_le(&fixed_buf, cast_set<uint32_t>(footer_buf.size()));
981
    // footer's checksum
982
15.5k
    uint32_t checksum = crc32c::Crc32c(footer_buf.data(), footer_buf.size());
983
15.5k
    put_fixed32_le(&fixed_buf, checksum);
984
    // Append magic number. we don't write magic number in the header because
985
    // that will need an extra seek when reading
986
15.5k
    fixed_buf.append(k_segment_magic, k_segment_magic_length);
987
988
15.5k
    std::vector<Slice> slices {footer_buf, fixed_buf};
989
15.5k
    return _write_raw_data(slices);
990
15.5k
}
991
992
71.8k
Status SegmentWriter::_write_raw_data(const std::vector<Slice>& slices) {
993
71.8k
    RETURN_IF_ERROR(_file_writer->appendv(&slices[0], slices.size()));
994
71.8k
    return Status::OK();
995
71.8k
}
996
997
15.5k
Slice SegmentWriter::min_encoded_key() {
998
15.5k
    return (_primary_key_index_builder == nullptr) ? Slice(_min_key.data(), _min_key.size())
999
15.5k
                                                   : _primary_key_index_builder->min_key();
1000
15.5k
}
1001
15.5k
Slice SegmentWriter::max_encoded_key() {
1002
15.5k
    return (_primary_key_index_builder == nullptr) ? Slice(_max_key.data(), _max_key.size())
1003
15.5k
                                                   : _primary_key_index_builder->max_key();
1004
15.5k
}
1005
1006
24.8k
void SegmentWriter::set_min_max_key(const Slice& key) {
1007
24.8k
    if (UNLIKELY(_is_first_row)) {
1008
12
        _min_key.append(key.get_data(), key.get_size());
1009
12
        _is_first_row = false;
1010
12
    }
1011
24.8k
    if (key.compare(_max_key) > 0) {
1012
24.8k
        _max_key.clear();
1013
24.8k
        _max_key.append(key.get_data(), key.get_size());
1014
24.8k
    }
1015
24.8k
}
1016
1017
14.5k
void SegmentWriter::set_min_key(const Slice& key) {
1018
14.5k
    if (UNLIKELY(_is_first_row)) {
1019
9.83k
        _min_key.append(key.get_data(), key.get_size());
1020
9.83k
        _is_first_row = false;
1021
9.83k
    }
1022
14.5k
}
1023
1024
14.5k
void SegmentWriter::set_max_key(const Slice& key) {
1025
14.5k
    _max_key.clear();
1026
14.5k
    _max_key.append(key.get_data(), key.get_size());
1027
14.5k
}
1028
1029
Status SegmentWriter::_generate_primary_key_index(
1030
        const std::vector<IOlapColumnDataAccessor*>& primary_key_columns,
1031
6.47k
        IOlapColumnDataAccessor* seq_column, size_t num_rows, bool need_sort) {
1032
6.47k
    if (!need_sort) { // mow table without cluster key
1033
6.21k
        std::string last_key;
1034
2.77M
        for (size_t pos = 0; pos < num_rows; pos++) {
1035
2.77M
            std::string key = encode_mow_key_invalidate_cache(
1036
2.77M
                    _key_encoder, primary_key_columns, seq_column, pos,
1037
2.77M
                    _tablet_schema->has_sequence_col(), _opts.rowset_ctx->tablet_id,
1038
2.77M
                    *_tablet_schema, _opts.write_type);
1039
2.77M
            DCHECK(key.compare(last_key) > 0)
1040
6.15k
                    << "found duplicate key or key is not sorted! current key: " << key
1041
6.15k
                    << ", last key: " << last_key;
1042
2.77M
            RETURN_IF_ERROR(_primary_key_index_builder->add_item(key));
1043
2.77M
            last_key = std::move(key);
1044
2.77M
        }
1045
6.21k
    } else { // mow table with cluster key
1046
        // generate primary keys in memory
1047
420k
        for (uint32_t pos = 0; pos < num_rows; pos++) {
1048
420k
            std::string key = _key_encoder.full_encode_primary_keys(primary_key_columns, pos);
1049
420k
            MowKeyProbe::maybe_invalidate_row_cache(_opts.rowset_ctx->tablet_id, *_tablet_schema,
1050
420k
                                                    _opts.write_type, key);
1051
420k
            if (_tablet_schema->has_sequence_col()) {
1052
24
                _key_encoder.append_seq_suffix(&key, seq_column, pos);
1053
24
            }
1054
420k
            _key_encoder.append_rowid_suffix(&key, pos + _num_rows_written);
1055
420k
            _primary_keys_size += key.size();
1056
420k
            _primary_keys.emplace_back(std::move(key));
1057
420k
        }
1058
262
    }
1059
6.47k
    return Status::OK();
1060
6.47k
}
1061
1062
Status SegmentWriter::_generate_short_key_index(std::vector<IOlapColumnDataAccessor*>& key_columns,
1063
                                                size_t num_rows,
1064
14.4k
                                                const std::vector<size_t>& short_key_pos) {
1065
14.4k
    set_min_key(_key_encoder.full_encode(key_columns, 0));
1066
14.4k
    set_max_key(_key_encoder.full_encode(key_columns, num_rows - 1));
1067
18.4E
    DCHECK(Slice(_max_key.data(), _max_key.size())
1068
18.4E
                   .compare(Slice(_min_key.data(), _min_key.size())) >= 0)
1069
18.4E
            << "key is not sorted! min key: " << _min_key << ", max key: " << _max_key;
1070
1071
14.4k
    key_columns.resize(_num_short_key_columns);
1072
14.4k
    std::string last_key;
1073
27.8k
    for (const auto pos : short_key_pos) {
1074
27.8k
        std::string key = _key_encoder.encode_short_keys(key_columns, pos);
1075
18.4E
        DCHECK(key.compare(last_key) >= 0)
1076
18.4E
                << "key is not sorted! current key: " << key << ", last key: " << last_key;
1077
27.8k
        RETURN_IF_ERROR(_short_key_index_builder->add_item(key));
1078
27.8k
        last_key = std::move(key);
1079
27.8k
    }
1080
14.4k
    return Status::OK();
1081
14.4k
}
1082
1083
} // namespace segment_v2
1084
} // namespace doris