Coverage Report

Created: 2026-03-14 20:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/schema_change/schema_change.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/schema_change/schema_change.h"
19
20
#include <gen_cpp/olap_file.pb.h>
21
#include <glog/logging.h>
22
#include <thrift/protocol/TDebugProtocol.h>
23
24
#include <algorithm>
25
#include <exception>
26
#include <map>
27
#include <memory>
28
#include <mutex>
29
#include <roaring/roaring.hh>
30
#include <tuple>
31
#include <utility>
32
33
#include "agent/be_exec_version_manager.h"
34
#include "cloud/cloud_schema_change_job.h"
35
#include "cloud/config.h"
36
#include "common/cast_set.h"
37
#include "common/consts.h"
38
#include "common/logging.h"
39
#include "common/signal_handler.h"
40
#include "common/status.h"
41
#include "core/assert_cast.h"
42
#include "core/block/block.h"
43
#include "core/block/column_with_type_and_name.h"
44
#include "core/column/column.h"
45
#include "core/column/column_nullable.h"
46
#include "exec/common/variant_util.h"
47
#include "exprs/aggregate/aggregate_function.h"
48
#include "exprs/aggregate/aggregate_function_reader.h"
49
#include "exprs/vexpr.h"
50
#include "exprs/vexpr_context.h"
51
#include "information_schema/schema_metadata_name_ids_scanner.h"
52
#include "io/fs/file_system.h"
53
#include "io/io_common.h"
54
#include "runtime/exec_env.h"
55
#include "runtime/memory/mem_tracker.h"
56
#include "runtime/runtime_state.h"
57
#include "storage/data_dir.h"
58
#include "storage/delete/delete_handler.h"
59
#include "storage/field.h"
60
#include "storage/index/inverted/inverted_index_desc.h"
61
#include "storage/index/inverted/inverted_index_writer.h"
62
#include "storage/iterator/olap_data_convertor.h"
63
#include "storage/iterators.h"
64
#include "storage/merger.h"
65
#include "storage/olap_common.h"
66
#include "storage/olap_define.h"
67
#include "storage/rowset/beta_rowset.h"
68
#include "storage/rowset/pending_rowset_helper.h"
69
#include "storage/rowset/rowset_meta.h"
70
#include "storage/rowset/rowset_reader_context.h"
71
#include "storage/rowset/rowset_writer_context.h"
72
#include "storage/schema.h"
73
#include "storage/segment/column_reader.h"
74
#include "storage/segment/segment.h"
75
#include "storage/segment/segment_loader.h"
76
#include "storage/storage_engine.h"
77
#include "storage/tablet/base_tablet.h"
78
#include "storage/tablet/tablet.h"
79
#include "storage/tablet/tablet_fwd.h"
80
#include "storage/tablet/tablet_manager.h"
81
#include "storage/tablet/tablet_meta.h"
82
#include "storage/tablet/tablet_schema.h"
83
#include "storage/types.h"
84
#include "storage/utils.h"
85
#include "util/debug_points.h"
86
#include "util/defer_op.h"
87
#include "util/trace.h"
88
89
namespace doris {
90
91
#include "common/compile_check_begin.h"
92
93
class CollectionValue;
94
95
using namespace ErrorCode;
96
97
constexpr int ALTER_TABLE_BATCH_SIZE = 4064;
98
99
class MultiBlockMerger {
100
public:
101
0
    MultiBlockMerger(BaseTabletSPtr tablet) : _tablet(tablet), _cmp(*tablet) {}
102
103
    Status merge(const std::vector<std::unique_ptr<Block>>& blocks, RowsetWriter* rowset_writer,
104
0
                 uint64_t* merged_rows) {
105
0
        int rows = 0;
106
0
        for (const auto& block : blocks) {
107
0
            rows += block->rows();
108
0
        }
109
0
        if (!rows) {
110
0
            return Status::OK();
111
0
        }
112
113
0
        std::vector<RowRef> row_refs;
114
0
        row_refs.reserve(rows);
115
0
        for (const auto& block : blocks) {
116
0
            for (uint16_t i = 0; i < block->rows(); i++) {
117
0
                row_refs.emplace_back(block.get(), i);
118
0
            }
119
0
        }
120
        // TODO: try to use pdqsort to replace std::sort
121
        // The block version is incremental.
122
0
        std::stable_sort(row_refs.begin(), row_refs.end(), _cmp);
123
124
0
        auto finalized_block = _tablet->tablet_schema()->create_block();
125
0
        int columns = finalized_block.columns();
126
0
        *merged_rows += rows;
127
128
0
        if (_tablet->keys_type() == KeysType::AGG_KEYS) {
129
0
            auto tablet_schema = _tablet->tablet_schema();
130
0
            int key_number = cast_set<int>(_tablet->num_key_columns());
131
132
0
            std::vector<AggregateFunctionPtr> agg_functions;
133
0
            std::vector<AggregateDataPtr> agg_places;
134
135
0
            for (int i = key_number; i < columns; i++) {
136
0
                try {
137
0
                    AggregateFunctionPtr function = tablet_schema->column(i).get_aggregate_function(
138
0
                            AGG_LOAD_SUFFIX, tablet_schema->column(i).get_be_exec_version());
139
0
                    if (!function) {
140
0
                        return Status::InternalError(
141
0
                                "could not find aggregate function on column {}, aggregation={}",
142
0
                                tablet_schema->column(i).name(),
143
0
                                tablet_schema->column(i).aggregation());
144
0
                    }
145
0
                    agg_functions.push_back(function);
146
                    // create aggregate data
147
0
                    auto* place = new char[function->size_of_data()];
148
0
                    function->create(place);
149
0
                    agg_places.push_back(place);
150
0
                } catch (...) {
151
0
                    for (int j = 0; j < i - key_number; ++j) {
152
0
                        agg_functions[j]->destroy(agg_places[j]);
153
0
                        delete[] agg_places[j];
154
0
                    }
155
0
                    throw;
156
0
                }
157
0
            }
158
159
0
            DEFER({
160
0
                for (int i = 0; i < columns - key_number; i++) {
161
0
                    agg_functions[i]->destroy(agg_places[i]);
162
0
                    delete[] agg_places[i];
163
0
                }
164
0
            });
165
166
0
            for (int i = 0; i < rows; i++) {
167
0
                auto row_ref = row_refs[i];
168
0
                for (int j = key_number; j < columns; j++) {
169
0
                    const auto* column_ptr = row_ref.get_column(j).get();
170
0
                    agg_functions[j - key_number]->add(agg_places[j - key_number],
171
0
                                                       const_cast<const IColumn**>(&column_ptr),
172
0
                                                       row_ref.position, _arena);
173
0
                }
174
175
0
                if (i == rows - 1 || _cmp.compare(row_refs[i], row_refs[i + 1])) {
176
0
                    for (int j = 0; j < key_number; j++) {
177
0
                        finalized_block.get_by_position(j).column->assume_mutable()->insert_from(
178
0
                                *row_ref.get_column(j), row_ref.position);
179
0
                    }
180
181
0
                    for (int j = key_number; j < columns; j++) {
182
0
                        agg_functions[j - key_number]->insert_result_into(
183
0
                                agg_places[j - key_number],
184
0
                                finalized_block.get_by_position(j).column->assume_mutable_ref());
185
0
                        agg_functions[j - key_number]->reset(agg_places[j - key_number]);
186
0
                    }
187
188
0
                    if (i == rows - 1 || finalized_block.rows() == ALTER_TABLE_BATCH_SIZE) {
189
0
                        *merged_rows -= finalized_block.rows();
190
0
                        RETURN_IF_ERROR(rowset_writer->add_block(&finalized_block));
191
0
                        finalized_block.clear_column_data();
192
0
                    }
193
0
                }
194
0
            }
195
0
        } else {
196
0
            std::vector<RowRef> pushed_row_refs;
197
0
            if (_tablet->keys_type() == KeysType::DUP_KEYS) {
198
0
                std::swap(pushed_row_refs, row_refs);
199
0
            } else if (_tablet->keys_type() == KeysType::UNIQUE_KEYS) {
200
0
                for (int i = 0; i < rows; i++) {
201
0
                    if (i == rows - 1 || _cmp.compare(row_refs[i], row_refs[i + 1])) {
202
0
                        pushed_row_refs.push_back(row_refs[i]);
203
0
                    }
204
0
                }
205
0
                if (!_tablet->tablet_schema()->cluster_key_uids().empty()) {
206
0
                    std::vector<uint32_t> ids;
207
0
                    for (const auto& cid : _tablet->tablet_schema()->cluster_key_uids()) {
208
0
                        auto index = _tablet->tablet_schema()->field_index(cid);
209
0
                        if (index == -1) {
210
0
                            return Status::InternalError(
211
0
                                    "could not find cluster key column with unique_id=" +
212
0
                                    std::to_string(cid) + " in tablet schema");
213
0
                        }
214
0
                        ids.push_back(index);
215
0
                    }
216
                    // sort by cluster key
217
0
                    std::stable_sort(pushed_row_refs.begin(), pushed_row_refs.end(),
218
0
                                     ClusterKeyRowRefComparator(ids));
219
0
                }
220
0
            }
221
222
            // update real inserted row number
223
0
            rows = cast_set<int>(pushed_row_refs.size());
224
0
            *merged_rows -= rows;
225
226
0
            for (int i = 0; i < rows; i += ALTER_TABLE_BATCH_SIZE) {
227
0
                int limit = std::min(ALTER_TABLE_BATCH_SIZE, rows - i);
228
229
0
                for (int idx = 0; idx < columns; idx++) {
230
0
                    auto column = finalized_block.get_by_position(idx).column->assume_mutable();
231
232
0
                    for (int j = 0; j < limit; j++) {
233
0
                        auto row_ref = pushed_row_refs[i + j];
234
0
                        column->insert_from(*row_ref.get_column(idx), row_ref.position);
235
0
                    }
236
0
                }
237
0
                RETURN_IF_ERROR(rowset_writer->add_block(&finalized_block));
238
0
                finalized_block.clear_column_data();
239
0
            }
240
0
        }
241
242
0
        RETURN_IF_ERROR(rowset_writer->flush());
243
0
        return Status::OK();
244
0
    }
245
246
private:
247
    struct RowRef {
248
0
        RowRef(Block* block_, uint16_t position_) : block(block_), position(position_) {}
249
0
        ColumnPtr get_column(int index) const { return block->get_by_position(index).column; }
250
        const Block* block;
251
        uint16_t position;
252
    };
253
254
    struct RowRefComparator {
255
0
        RowRefComparator(const BaseTablet& tablet) : _num_columns(tablet.num_key_columns()) {}
256
257
0
        int compare(const RowRef& lhs, const RowRef& rhs) const {
258
            // Notice: does not compare sequence column for mow table
259
            // read from rowsets with delete bitmap, so there should be no duplicated keys
260
0
            return lhs.block->compare_at(lhs.position, rhs.position, _num_columns, *rhs.block, -1);
261
0
        }
262
263
0
        bool operator()(const RowRef& lhs, const RowRef& rhs) const {
264
0
            return compare(lhs, rhs) < 0;
265
0
        }
266
267
        const size_t _num_columns;
268
    };
269
270
    struct ClusterKeyRowRefComparator {
271
0
        ClusterKeyRowRefComparator(std::vector<uint32_t> columns) : _columns(columns) {}
272
273
0
        int compare(const RowRef& lhs, const RowRef& rhs) const {
274
0
            return lhs.block->compare_at(lhs.position, rhs.position, &_columns, *rhs.block, -1);
275
0
        }
276
277
0
        bool operator()(const RowRef& lhs, const RowRef& rhs) const {
278
0
            return compare(lhs, rhs) < 0;
279
0
        }
280
281
        const std::vector<uint32_t> _columns;
282
    };
283
284
    BaseTabletSPtr _tablet;
285
    RowRefComparator _cmp;
286
    Arena _arena;
287
};
288
289
BlockChanger::BlockChanger(TabletSchemaSPtr tablet_schema, DescriptorTbl desc_tbl,
290
                           std::shared_ptr<RuntimeState> state)
291
0
        : _desc_tbl(std::move(desc_tbl)), _state(std::move(state)) {
292
0
    CHECK(_state != nullptr);
293
0
    _schema_mapping.resize(tablet_schema->num_columns());
294
0
}
295
296
0
BlockChanger::~BlockChanger() {
297
0
    _schema_mapping.clear();
298
0
}
299
300
0
ColumnMapping* BlockChanger::get_mutable_column_mapping(size_t column_index) {
301
0
    if (column_index >= _schema_mapping.size()) {
302
0
        return nullptr;
303
0
    }
304
305
0
    return &(_schema_mapping[column_index]);
306
0
}
307
308
0
Status BlockChanger::change_block(Block* ref_block, Block* new_block) const {
309
    // for old version request compatibility
310
0
    _state->set_desc_tbl(&_desc_tbl);
311
0
    _state->set_be_exec_version(_fe_compatible_version);
312
0
    RowDescriptor row_desc =
313
0
            RowDescriptor(_desc_tbl.get_tuple_descriptor(_desc_tbl.get_row_tuples()[0]));
314
315
0
    if (_where_expr != nullptr) {
316
0
        VExprContextSPtr ctx = nullptr;
317
0
        RETURN_IF_ERROR(VExpr::create_expr_tree(*_where_expr, ctx));
318
0
        RETURN_IF_ERROR(ctx->prepare(_state.get(), row_desc));
319
0
        RETURN_IF_ERROR(ctx->open(_state.get()));
320
321
0
        RETURN_IF_ERROR(VExprContext::filter_block(ctx.get(), ref_block));
322
0
    }
323
324
0
    const int row_num = cast_set<int>(ref_block->rows());
325
0
    const int new_schema_cols_num = new_block->columns();
326
327
    // will be used for swaping ref_block[entry.first] and new_block[entry.second]
328
0
    std::list<std::pair<int, int>> swap_idx_list;
329
0
    for (int idx = 0; idx < new_schema_cols_num; idx++) {
330
0
        auto expr = _schema_mapping[idx].expr;
331
0
        if (expr != nullptr) {
332
0
            VExprContextSPtr ctx;
333
0
            RETURN_IF_ERROR(VExpr::create_expr_tree(*expr, ctx));
334
0
            RETURN_IF_ERROR(ctx->prepare(_state.get(), row_desc));
335
0
            RETURN_IF_ERROR(ctx->open(_state.get()));
336
337
0
            int result_tmp_column_idx = -1;
338
0
            RETURN_IF_ERROR(ctx->execute(ref_block, &result_tmp_column_idx));
339
0
            auto& result_tmp_column_def = ref_block->get_by_position(result_tmp_column_idx);
340
0
            if (!result_tmp_column_def.column) {
341
0
                return Status::Error<ErrorCode::INTERNAL_ERROR>(
342
0
                        "result column={} is nullptr, input expr={}", result_tmp_column_def.name,
343
0
                        apache::thrift::ThriftDebugString(*expr));
344
0
            }
345
0
            ref_block->replace_by_position_if_const(result_tmp_column_idx);
346
347
0
            if (result_tmp_column_def.column->size() != row_num) {
348
0
                return Status::Error<ErrorCode::INTERNAL_ERROR>(
349
0
                        "result size invalid, expect={}, real={}; input expr={}, block={}", row_num,
350
0
                        result_tmp_column_def.column->size(),
351
0
                        apache::thrift::ThriftDebugString(*expr), ref_block->dump_structure());
352
0
            }
353
354
0
            auto lhs = _schema_mapping[idx].new_column->get_vec_type()->get_primitive_type();
355
0
            auto rhs = result_tmp_column_def.type->get_primitive_type();
356
0
            if (is_string_type(lhs) != is_string_type(rhs) && lhs != rhs) {
357
0
                return Status::Error<ErrorCode::INTERNAL_ERROR>(
358
0
                        "result type invalid, expect={}, real={}; input expr={}, block={}",
359
0
                        _schema_mapping[idx].new_column->get_vec_type()->get_name(),
360
0
                        result_tmp_column_def.type->get_name(),
361
0
                        apache::thrift::ThriftDebugString(*expr), ref_block->dump_structure());
362
0
            }
363
364
0
            if (_type == SCHEMA_CHANGE) {
365
                // danger casts (expected to be rejected by upstream caller) may cause data to be null and result in data loss in schema change
366
                // for rollup, this check is unecessary, and ref columns are not set in this case, it works on exprs
367
368
                // column_idx in base schema
369
0
                int32_t ref_column_idx = _schema_mapping[idx].ref_column_idx;
370
0
                DCHECK_GE(ref_column_idx, 0);
371
0
                auto& ref_column_def = ref_block->get_by_position(ref_column_idx);
372
0
                RETURN_IF_ERROR(
373
0
                        _check_cast_valid(ref_column_def.column, result_tmp_column_def.column));
374
0
            }
375
0
            swap_idx_list.emplace_back(result_tmp_column_idx, idx);
376
0
        } else if (_schema_mapping[idx].ref_column_idx < 0) {
377
            // new column, write default value
378
0
            const auto& value = _schema_mapping[idx].default_value;
379
0
            auto column = new_block->get_by_position(idx).column->assume_mutable();
380
0
            if (value.is_null()) {
381
0
                DCHECK(column->is_nullable());
382
0
                column->insert_many_defaults(row_num);
383
0
            } else {
384
0
                column = column->convert_to_predicate_column_if_dictionary();
385
0
                column->insert_duplicate_fields(value, row_num);
386
0
            }
387
0
        } else {
388
            // same type, just swap column
389
0
            swap_idx_list.emplace_back(_schema_mapping[idx].ref_column_idx, idx);
390
0
        }
391
0
    }
392
393
0
    for (auto it : swap_idx_list) {
394
0
        auto& ref_col = ref_block->get_by_position(it.first).column;
395
0
        auto& new_col = new_block->get_by_position(it.second).column;
396
397
0
        bool ref_col_nullable = ref_col->is_nullable();
398
0
        bool new_col_nullable = new_col->is_nullable();
399
400
0
        if (ref_col_nullable != new_col_nullable) {
401
            // not nullable to nullable
402
0
            if (new_col_nullable) {
403
0
                auto* new_nullable_col =
404
0
                        assert_cast<ColumnNullable*>(new_col->assume_mutable().get());
405
406
0
                new_nullable_col->change_nested_column(ref_col);
407
0
                new_nullable_col->get_null_map_data().resize_fill(ref_col->size());
408
0
            } else {
409
                // nullable to not nullable:
410
                // suppose column `c_phone` is originally varchar(16) NOT NULL,
411
                // then do schema change `alter table test modify column c_phone int not null`,
412
                // the cast expr of schema change is `CastExpr(CAST String to Nullable(Int32))`,
413
                // so need to handle nullable to not nullable here
414
0
                auto* ref_nullable_col =
415
0
                        assert_cast<ColumnNullable*>(ref_col->assume_mutable().get());
416
417
0
                new_col = ref_nullable_col->get_nested_column_ptr();
418
0
            }
419
0
        } else {
420
0
            new_block->get_by_position(it.second).column =
421
0
                    ref_block->get_by_position(it.first).column;
422
0
        }
423
0
    }
424
0
    return Status::OK();
425
0
}
426
427
// This check can prevent schema-change from causing data loss after type cast
428
0
Status BlockChanger::_check_cast_valid(ColumnPtr input_column, ColumnPtr output_column) {
429
0
    if (input_column->size() != output_column->size()) {
430
0
        return Status::InternalError(
431
0
                "column size is changed, input_column_size={}, output_column_size={}; "
432
0
                "input_column={}",
433
0
                input_column->size(), output_column->size(), input_column->get_name());
434
0
    }
435
0
    DCHECK_EQ(input_column->size(), output_column->size())
436
0
            << "length check should have done before calling this function!";
437
438
0
    if (input_column->is_nullable() != output_column->is_nullable()) {
439
0
        if (input_column->is_nullable()) {
440
0
            const auto* ref_null_map = check_and_get_column<ColumnNullable>(input_column.get())
441
0
                                               ->get_null_map_column()
442
0
                                               .get_data()
443
0
                                               .data();
444
445
0
            bool is_changed = false;
446
0
            for (size_t i = 0; i < input_column->size(); i++) {
447
0
                is_changed |= ref_null_map[i];
448
0
            }
449
0
            if (is_changed) {
450
0
                return Status::DataQualityError(
451
0
                        "some null data is changed to not null, intput_column={}",
452
0
                        input_column->get_name());
453
0
            }
454
0
        } else {
455
0
            const auto& null_map_column = check_and_get_column<ColumnNullable>(output_column.get())
456
0
                                                  ->get_null_map_column();
457
0
            const auto& nested_column =
458
0
                    check_and_get_column<ColumnNullable>(output_column.get())->get_nested_column();
459
0
            const auto* new_null_map = null_map_column.get_data().data();
460
461
0
            if (null_map_column.size() != output_column->size()) {
462
0
                return Status::InternalError(
463
0
                        "null_map_column size mismatch output_column_size, "
464
0
                        "null_map_column_size={}, output_column_size={}; input_column={}",
465
0
                        null_map_column.size(), output_column->size(), input_column->get_name());
466
0
            }
467
468
0
            if (nested_column.size() != output_column->size()) {
469
0
                return Status::InternalError(
470
0
                        "nested_column size is changed, nested_column_size={}, "
471
0
                        "ouput_column_size={}; input_column={}",
472
0
                        nested_column.size(), output_column->size(), input_column->get_name());
473
0
            }
474
475
0
            bool is_changed = false;
476
0
            for (size_t i = 0; i < input_column->size(); i++) {
477
0
                is_changed |= new_null_map[i];
478
0
            }
479
0
            if (is_changed) {
480
0
                return Status::DataQualityError(
481
0
                        "some not null data is changed to null, intput_column={}",
482
0
                        input_column->get_name());
483
0
            }
484
0
        }
485
0
    }
486
487
0
    if (input_column->is_nullable() && output_column->is_nullable()) {
488
0
        const auto* ref_null_map = check_and_get_column<ColumnNullable>(input_column.get())
489
0
                                           ->get_null_map_column()
490
0
                                           .get_data()
491
0
                                           .data();
492
0
        const auto* new_null_map = check_and_get_column<ColumnNullable>(output_column.get())
493
0
                                           ->get_null_map_column()
494
0
                                           .get_data()
495
0
                                           .data();
496
497
0
        bool is_changed = false;
498
0
        for (size_t i = 0; i < input_column->size(); i++) {
499
0
            is_changed |= (ref_null_map[i] != new_null_map[i]);
500
0
        }
501
0
        if (is_changed) {
502
0
            return Status::DataQualityError(
503
0
                    "null map is changed after calculation, input_column={}",
504
0
                    input_column->get_name());
505
0
        }
506
0
    }
507
0
    return Status::OK();
508
0
}
509
510
Status LinkedSchemaChange::process(RowsetReaderSharedPtr rowset_reader, RowsetWriter* rowset_writer,
511
                                   BaseTabletSPtr new_tablet, BaseTabletSPtr base_tablet,
512
                                   TabletSchemaSPtr base_tablet_schema,
513
0
                                   TabletSchemaSPtr new_tablet_schema) {
514
0
    Status status = rowset_writer->add_rowset_for_linked_schema_change(rowset_reader->rowset());
515
0
    if (!status) {
516
0
        LOG(WARNING) << "fail to convert rowset."
517
0
                     << ", new_tablet=" << new_tablet->tablet_id()
518
0
                     << ", version=" << rowset_writer->version().first << "-"
519
0
                     << rowset_writer->version().second << ", error status " << status;
520
0
        return status;
521
0
    }
522
    // copy delete bitmap to new tablet.
523
0
    if (new_tablet->keys_type() == UNIQUE_KEYS && new_tablet->enable_unique_key_merge_on_write()) {
524
0
        DeleteBitmap origin_delete_bitmap(base_tablet->tablet_id());
525
0
        base_tablet->tablet_meta()->delete_bitmap().subset(
526
0
                {rowset_reader->rowset()->rowset_id(), 0, 0},
527
0
                {rowset_reader->rowset()->rowset_id(), UINT32_MAX, INT64_MAX},
528
0
                &origin_delete_bitmap);
529
0
        for (auto& iter : origin_delete_bitmap.delete_bitmap) {
530
0
            int ret = new_tablet->tablet_meta()->delete_bitmap().set(
531
0
                    {rowset_writer->rowset_id(), std::get<1>(iter.first), std::get<2>(iter.first)},
532
0
                    iter.second);
533
0
            DCHECK(ret == 1);
534
0
        }
535
0
    }
536
0
    return Status::OK();
537
0
}
538
539
Status next_batch(RowsetReaderSharedPtr rowset_reader, Block* input_block,
540
0
                  std::vector<bool>& row_same_bit) {
541
0
    Status st;
542
0
    if (rowset_reader->is_merge_iterator()) {
543
0
        row_same_bit.clear();
544
0
        BlockWithSameBit block_with_same_bit = {.block = input_block, .same_bit = row_same_bit};
545
0
        st = rowset_reader->next_batch(&block_with_same_bit);
546
        // todo: use row_same_bit to clean some useless row
547
0
    } else {
548
0
        st = rowset_reader->next_batch(input_block);
549
0
    }
550
0
    return st;
551
0
}
552
553
Status VSchemaChangeDirectly::_inner_process(RowsetReaderSharedPtr rowset_reader,
554
                                             RowsetWriter* rowset_writer, BaseTabletSPtr new_tablet,
555
                                             TabletSchemaSPtr base_tablet_schema,
556
0
                                             TabletSchemaSPtr new_tablet_schema) {
557
0
    bool eof = false;
558
0
    do {
559
0
        auto new_block = Block::create_unique(new_tablet_schema->create_block());
560
        // create_block() skips dropped columns (from light-weight schema change).
561
        // Dropped columns are only needed for delete predicate evaluation, which
562
        // SegmentIterator handles internally — it creates temporary columns for
563
        // predicate columns not present in the block (via `i >= block->columns()`
564
        // guard in _init_current_block). If dropped columns were included here,
565
        // the block would have more columns than VMergeIterator's output_schema
566
        // expects, causing DCHECK failures in copy_rows.
567
0
        auto ref_block = Block::create_unique(base_tablet_schema->create_block());
568
569
0
        Status st = next_batch(rowset_reader, ref_block.get(), _row_same_bit);
570
0
        if (!st) {
571
0
            if (st.is<ErrorCode::END_OF_FILE>()) {
572
0
                if (ref_block->rows() == 0) {
573
0
                    break;
574
0
                } else {
575
0
                    eof = true;
576
0
                }
577
0
            } else {
578
0
                return st;
579
0
            }
580
0
        }
581
582
0
        RETURN_IF_ERROR(_changer.change_block(ref_block.get(), new_block.get()));
583
0
        RETURN_IF_ERROR(rowset_writer->add_block(new_block.get()));
584
0
    } while (!eof);
585
586
0
    RETURN_IF_ERROR(rowset_writer->flush());
587
0
    return Status::OK();
588
0
}
589
590
VBaseSchemaChangeWithSorting::VBaseSchemaChangeWithSorting(const BlockChanger& changer,
591
                                                           size_t memory_limitation)
592
0
        : _changer(changer),
593
0
          _memory_limitation(memory_limitation),
594
0
          _temp_delta_versions(Version::mock()) {
595
0
    _mem_tracker = std::make_unique<MemTracker>(
596
0
            fmt::format("VSchemaChangeWithSorting:changer={}", std::to_string(int64_t(&changer))));
597
0
}
598
599
Status VBaseSchemaChangeWithSorting::_inner_process(RowsetReaderSharedPtr rowset_reader,
600
                                                    RowsetWriter* rowset_writer,
601
                                                    BaseTabletSPtr new_tablet,
602
                                                    TabletSchemaSPtr base_tablet_schema,
603
0
                                                    TabletSchemaSPtr new_tablet_schema) {
604
    // for internal sorting
605
0
    std::vector<std::unique_ptr<Block>> blocks;
606
607
0
    RowsetSharedPtr rowset = rowset_reader->rowset();
608
0
    SegmentsOverlapPB segments_overlap = rowset->rowset_meta()->segments_overlap();
609
0
    int64_t newest_write_timestamp = rowset->newest_write_timestamp();
610
0
    _temp_delta_versions.first = _temp_delta_versions.second;
611
0
    _src_rowsets.clear(); // init _src_rowsets
612
0
    auto create_rowset = [&]() -> Status {
613
0
        if (blocks.empty()) {
614
0
            return Status::OK();
615
0
        }
616
617
0
        auto rowset = DORIS_TRY(_internal_sorting(
618
0
                blocks, Version(_temp_delta_versions.second, _temp_delta_versions.second + 1),
619
0
                newest_write_timestamp, new_tablet, BETA_ROWSET, segments_overlap,
620
0
                new_tablet_schema));
621
0
        _src_rowsets.push_back(std::move(rowset));
622
0
        for (auto& block : blocks) {
623
0
            _mem_tracker->release(block->allocated_bytes());
624
0
        }
625
0
        blocks.clear();
626
627
        // increase temp version
628
0
        _temp_delta_versions.second += 2;
629
0
        return Status::OK();
630
0
    };
631
632
0
    auto new_block = Block::create_unique(new_tablet_schema->create_block());
633
634
0
    bool eof = false;
635
0
    do {
636
        // create_block() skips dropped columns (from light-weight schema change).
637
        // Dropped columns are only needed for delete predicate evaluation, which
638
        // SegmentIterator handles internally — it creates temporary columns for
639
        // predicate columns not present in the block (via `i >= block->columns()`
640
        // guard in _init_current_block). If dropped columns were included here,
641
        // the block would have more columns than VMergeIterator's output_schema
642
        // expects, causing DCHECK failures in copy_rows.
643
0
        auto ref_block = Block::create_unique(base_tablet_schema->create_block());
644
0
        Status st = next_batch(rowset_reader, ref_block.get(), _row_same_bit);
645
0
        if (!st) {
646
0
            if (st.is<ErrorCode::END_OF_FILE>()) {
647
0
                if (ref_block->rows() == 0) {
648
0
                    break;
649
0
                } else {
650
0
                    eof = true;
651
0
                }
652
0
            } else {
653
0
                return st;
654
0
            }
655
0
        }
656
657
0
        RETURN_IF_ERROR(_changer.change_block(ref_block.get(), new_block.get()));
658
659
0
        constexpr double HOLD_BLOCK_MEMORY_RATE =
660
0
                0.66; // Reserve some memory for use by other parts of this job
661
0
        if (_mem_tracker->consumption() + new_block->allocated_bytes() > _memory_limitation ||
662
0
            cast_set<double>(_mem_tracker->consumption()) >
663
0
                    cast_set<double>(_memory_limitation) * HOLD_BLOCK_MEMORY_RATE ||
664
0
            DebugPoints::instance()->is_enable(
665
0
                    "VBaseSchemaChangeWithSorting._inner_process.create_rowset")) {
666
0
            RETURN_IF_ERROR(create_rowset());
667
668
0
            if (_mem_tracker->consumption() + new_block->allocated_bytes() > _memory_limitation) {
669
0
                return Status::Error<INVALID_ARGUMENT>(
670
0
                        "Memory limitation is too small for Schema Change. _memory_limitation={}, "
671
0
                        "new_block->allocated_bytes()={}, consumption={}",
672
0
                        _memory_limitation, new_block->allocated_bytes(),
673
0
                        _mem_tracker->consumption());
674
0
            }
675
0
        }
676
0
        _mem_tracker->consume(new_block->allocated_bytes());
677
678
        // move unique ptr
679
0
        blocks.push_back(Block::create_unique(new_tablet_schema->create_block()));
680
0
        swap(blocks.back(), new_block);
681
0
    } while (!eof);
682
683
0
    RETURN_IF_ERROR(create_rowset());
684
685
0
    if (_src_rowsets.empty()) {
686
0
        RETURN_IF_ERROR(rowset_writer->flush());
687
0
    } else {
688
0
        RETURN_IF_ERROR(
689
0
                _external_sorting(_src_rowsets, rowset_writer, new_tablet, new_tablet_schema));
690
0
    }
691
692
0
    return Status::OK();
693
0
}
694
695
Result<RowsetSharedPtr> VBaseSchemaChangeWithSorting::_internal_sorting(
696
        const std::vector<std::unique_ptr<Block>>& blocks, const Version& version,
697
        int64_t newest_write_timestamp, BaseTabletSPtr new_tablet, RowsetTypePB new_rowset_type,
698
0
        SegmentsOverlapPB segments_overlap, TabletSchemaSPtr new_tablet_schema) {
699
0
    uint64_t merged_rows = 0;
700
0
    MultiBlockMerger merger(new_tablet);
701
0
    RowsetWriterContext context;
702
0
    context.version = version;
703
0
    context.rowset_state = VISIBLE;
704
0
    context.segments_overlap = segments_overlap;
705
0
    context.tablet_schema = new_tablet_schema;
706
0
    context.newest_write_timestamp = newest_write_timestamp;
707
0
    context.write_type = DataWriteType::TYPE_SCHEMA_CHANGE;
708
0
    context.allow_packed_file = false;
709
0
    std::unique_ptr<RowsetWriter> rowset_writer;
710
    // TODO(plat1ko): Use monad op
711
0
    if (auto result = new_tablet->create_rowset_writer(context, false); !result.has_value())
712
0
            [[unlikely]] {
713
0
        return unexpected(std::move(result).error());
714
0
    } else {
715
0
        rowset_writer = std::move(result).value();
716
0
    }
717
0
    RETURN_IF_ERROR_RESULT(merger.merge(blocks, rowset_writer.get(), &merged_rows));
718
0
    _add_merged_rows(merged_rows);
719
0
    RowsetSharedPtr rowset;
720
0
    RETURN_IF_ERROR_RESULT(rowset_writer->build(rowset));
721
0
    return rowset;
722
0
}
723
724
Result<RowsetSharedPtr> VLocalSchemaChangeWithSorting::_internal_sorting(
725
        const std::vector<std::unique_ptr<Block>>& blocks, const Version& version,
726
        int64_t newest_write_timestamp, BaseTabletSPtr new_tablet, RowsetTypePB new_rowset_type,
727
0
        SegmentsOverlapPB segments_overlap, TabletSchemaSPtr new_tablet_schema) {
728
0
    uint64_t merged_rows = 0;
729
0
    MultiBlockMerger merger(new_tablet);
730
0
    RowsetWriterContext context;
731
0
    context.version = version;
732
0
    context.rowset_state = VISIBLE;
733
0
    context.segments_overlap = segments_overlap;
734
0
    context.tablet_schema = new_tablet_schema;
735
0
    context.newest_write_timestamp = newest_write_timestamp;
736
0
    context.write_type = DataWriteType::TYPE_SCHEMA_CHANGE;
737
0
    context.allow_packed_file = false;
738
0
    std::unique_ptr<RowsetWriter> rowset_writer;
739
    // TODO(plat1ko): Use monad op
740
0
    if (auto result = new_tablet->create_rowset_writer(context, false); !result.has_value())
741
0
            [[unlikely]] {
742
0
        return unexpected(std::move(result).error());
743
0
    } else {
744
0
        rowset_writer = std::move(result).value();
745
0
    }
746
0
    auto guard = _local_storage_engine.pending_local_rowsets().add(context.rowset_id);
747
0
    _pending_rs_guards.push_back(std::move(guard));
748
0
    RETURN_IF_ERROR_RESULT(merger.merge(blocks, rowset_writer.get(), &merged_rows));
749
0
    _add_merged_rows(merged_rows);
750
0
    RowsetSharedPtr rowset;
751
0
    RETURN_IF_ERROR_RESULT(rowset_writer->build(rowset));
752
0
    return rowset;
753
0
}
754
755
Status VBaseSchemaChangeWithSorting::_external_sorting(std::vector<RowsetSharedPtr>& src_rowsets,
756
                                                       RowsetWriter* rowset_writer,
757
                                                       BaseTabletSPtr new_tablet,
758
0
                                                       TabletSchemaSPtr new_tablet_schema) {
759
0
    std::vector<RowsetReaderSharedPtr> rs_readers;
760
0
    for (auto& rowset : src_rowsets) {
761
0
        RowsetReaderSharedPtr rs_reader;
762
0
        RETURN_IF_ERROR(rowset->create_reader(&rs_reader));
763
0
        rs_readers.push_back(rs_reader);
764
0
    }
765
766
0
    Merger::Statistics stats;
767
0
    if (!new_tablet_schema->cluster_key_uids().empty()) {
768
        // schema change read rowsets with delete bitmap, so there should be no duplicated keys
769
        // RETURN_IF_ERROR(Compaction::update_delete_bitmap());
770
0
        int64_t way_num = 0;
771
0
        int64_t input_rowsets_data_size = 0;
772
0
        int64_t input_row_num = 0;
773
0
        for (auto& rowset : src_rowsets) {
774
0
            way_num += rowset->rowset_meta()->get_merge_way_num();
775
0
            input_rowsets_data_size += rowset->data_disk_size();
776
0
            input_row_num += rowset->num_rows();
777
0
        }
778
0
        int64_t avg_segment_rows = config::vertical_compaction_max_segment_size /
779
0
                                   (input_rowsets_data_size / (input_row_num + 1) + 1);
780
0
        RETURN_IF_ERROR(Merger::vertical_merge_rowsets(
781
0
                new_tablet, ReaderType::READER_ALTER_TABLE, *new_tablet_schema, rs_readers,
782
0
                rowset_writer, cast_set<uint32_t>(avg_segment_rows), way_num, &stats));
783
0
    } else {
784
0
        RETURN_IF_ERROR(Merger::vmerge_rowsets(new_tablet, ReaderType::READER_ALTER_TABLE,
785
0
                                               *new_tablet_schema, rs_readers, rowset_writer,
786
0
                                               &stats));
787
0
    }
788
0
    _add_merged_rows(stats.merged_rows);
789
0
    _add_filtered_rows(stats.filtered_rows);
790
0
    return Status::OK();
791
0
}
792
793
Status VLocalSchemaChangeWithSorting::_inner_process(RowsetReaderSharedPtr rowset_reader,
794
                                                     RowsetWriter* rowset_writer,
795
                                                     BaseTabletSPtr new_tablet,
796
                                                     TabletSchemaSPtr base_tablet_schema,
797
0
                                                     TabletSchemaSPtr new_tablet_schema) {
798
0
    Defer defer {[&]() {
799
        // remove the intermediate rowsets generated by internal sorting
800
0
        for (auto& row_set : _src_rowsets) {
801
0
            _local_storage_engine.add_unused_rowset(row_set);
802
0
        }
803
0
    }};
804
0
    _pending_rs_guards.clear();
805
0
    return VBaseSchemaChangeWithSorting::_inner_process(rowset_reader, rowset_writer, new_tablet,
806
0
                                                        base_tablet_schema, new_tablet_schema);
807
0
}
808
809
0
Status SchemaChangeJob::process_alter_tablet(const TAlterTabletReqV2& request) {
810
0
    if (!request.__isset.desc_tbl) {
811
0
        return Status::Error<INVALID_ARGUMENT>(
812
0
                "desc_tbl is not set. Maybe the FE version is not equal to the BE "
813
0
                "version.");
814
0
    }
815
0
    if (_base_tablet == nullptr) {
816
0
        return Status::Error<TABLE_NOT_FOUND>("fail to find base tablet. base_tablet={}",
817
0
                                              request.base_tablet_id);
818
0
    }
819
0
    if (_new_tablet == nullptr) {
820
0
        return Status::Error<TABLE_NOT_FOUND>("fail to find new tablet. new_tablet={}",
821
0
                                              request.new_tablet_id);
822
0
    }
823
824
0
    LOG(INFO) << "begin to do request alter tablet: base_tablet_id=" << request.base_tablet_id
825
0
              << ", new_tablet_id=" << request.new_tablet_id
826
0
              << ", alter_version=" << request.alter_version;
827
828
    // Lock schema_change_lock util schema change info is stored in tablet header
829
0
    static constexpr long TRY_LOCK_TIMEOUT = 30;
830
0
    std::unique_lock schema_change_lock(_base_tablet->get_schema_change_lock(), std::defer_lock);
831
0
    bool owns_lock = schema_change_lock.try_lock_for(std::chrono::seconds(TRY_LOCK_TIMEOUT));
832
833
0
    if (!owns_lock) {
834
0
        return Status::Error<TRY_LOCK_FAILED>(
835
0
                "Failed to obtain schema change lock, there might be inverted index being "
836
0
                "built or cooldown runnning on base_tablet={}",
837
0
                request.base_tablet_id);
838
0
    }
839
840
0
    Status res = _do_process_alter_tablet(request);
841
0
    LOG(INFO) << "finished alter tablet process, res=" << res;
842
0
    DBUG_EXECUTE_IF("SchemaChangeJob::process_alter_tablet.leave.sleep", { sleep(5); });
843
0
    return res;
844
0
}
845
846
SchemaChangeJob::SchemaChangeJob(StorageEngine& local_storage_engine,
847
                                 const TAlterTabletReqV2& request, const std::string& job_id)
848
0
        : _local_storage_engine(local_storage_engine) {
849
0
    _base_tablet = _local_storage_engine.tablet_manager()->get_tablet(request.base_tablet_id);
850
0
    _new_tablet = _local_storage_engine.tablet_manager()->get_tablet(request.new_tablet_id);
851
0
    if (_base_tablet && _new_tablet) {
852
0
        _base_tablet_schema = std::make_shared<TabletSchema>();
853
0
        _base_tablet_schema->update_tablet_columns(*_base_tablet->tablet_schema(), request.columns);
854
        // The request only include column info, do not include bitmap or bloomfilter index info,
855
        // So we also need to copy index info from the real base tablet
856
0
        _base_tablet_schema->update_index_info_from(*_base_tablet->tablet_schema());
857
        // During a schema change, the extracted columns of a variant should not be included in the tablet schema.
858
        // This is because the schema change for a variant needs to ignore the extracted columns.
859
        // Otherwise, the schema types in different rowsets might be inconsistent. When performing a schema change,
860
        // the complete variant is constructed by reading all the sub-columns of the variant.
861
0
        _new_tablet_schema = _new_tablet->tablet_schema()->copy_without_variant_extracted_columns();
862
0
    }
863
0
    _job_id = job_id;
864
0
}
865
866
// In the past schema change and rollup will create new tablet  and will wait for txns starting before the task to finished
867
// It will cost a lot of time to wait and the task is very difficult to understand.
868
// In alter task v2, FE will call BE to create tablet and send an alter task to BE to convert historical data.
869
// The admin should upgrade all BE and then upgrade FE.
870
// Should delete the old code after upgrade finished.
871
0
Status SchemaChangeJob::_do_process_alter_tablet(const TAlterTabletReqV2& request) {
872
0
    DBUG_EXECUTE_IF("SchemaChangeJob._do_process_alter_tablet.sleep", { sleep(10); })
873
0
    Status res;
874
0
    signal::tablet_id = _base_tablet->get_table_id();
875
876
    // check if tablet's state is not_ready, if it is ready, it means the tablet already finished
877
    // check whether the tablet's max continuous version == request.version
878
0
    if (_new_tablet->tablet_state() != TABLET_NOTREADY) {
879
0
        res = _validate_alter_result(request);
880
0
        LOG(INFO) << "tablet's state=" << _new_tablet->tablet_state()
881
0
                  << " the convert job already finished, check its version"
882
0
                  << " res=" << res;
883
0
        return res;
884
0
    }
885
0
    _new_tablet->set_alter_failed(false);
886
0
    Defer defer([this] {
887
        // if tablet state is not TABLET_RUNNING when return, indicates that alter has failed.
888
0
        if (_new_tablet->tablet_state() != TABLET_RUNNING) {
889
0
            _new_tablet->set_alter_failed(true);
890
0
        }
891
0
    });
892
893
0
    LOG(INFO) << "finish to validate alter tablet request. begin to convert data from base tablet "
894
0
                 "to new tablet"
895
0
              << " base_tablet=" << _base_tablet->tablet_id()
896
0
              << " new_tablet=" << _new_tablet->tablet_id();
897
898
0
    std::shared_lock base_migration_rlock(_base_tablet->get_migration_lock(), std::try_to_lock);
899
0
    if (!base_migration_rlock.owns_lock()) {
900
0
        return Status::Error<TRY_LOCK_FAILED>(
901
0
                "SchemaChangeJob::_do_process_alter_tablet get lock failed");
902
0
    }
903
0
    std::shared_lock new_migration_rlock(_new_tablet->get_migration_lock(), std::try_to_lock);
904
0
    if (!new_migration_rlock.owns_lock()) {
905
0
        return Status::Error<TRY_LOCK_FAILED>(
906
0
                "SchemaChangeJob::_do_process_alter_tablet get lock failed");
907
0
    }
908
909
0
    std::vector<Version> versions_to_be_changed;
910
0
    int64_t end_version = -1;
911
    // reader_context is stack variables, it's lifetime should keep the same
912
    // with rs_readers
913
0
    RowsetReaderContext reader_context;
914
0
    std::vector<RowSetSplits> rs_splits;
915
    // delete handlers for new tablet
916
0
    DeleteHandler delete_handler;
917
0
    std::vector<ColumnId> return_columns;
918
919
    // Use tablet schema directly from base tablet, they are the newest schema, not contain
920
    // dropped column during light weight schema change.
921
    // But the tablet schema in base tablet maybe not the latest from FE, so that if fe pass through
922
    // a tablet schema, then use request schema.
923
    //
924
    // return_columns does NOT include dropped columns. It is computed here BEFORE
925
    // merge_dropped_columns() appends dropped columns to _base_tablet_schema below.
926
    // This means return_columns only covers the original (non-dropped) columns.
927
    //
928
    // This is important because:
929
    // - BetaRowsetReader builds _output_schema from return_columns, which determines the
930
    //   number of columns in ref_block (via create_block() which also skips dropped cols).
931
    // - VMergeIterator's copy_rows iterates over _output_schema columns, so ref_block
932
    //   must match _output_schema exactly.
933
    // - Dropped columns are only needed for delete predicate evaluation, and SegmentIterator
934
    //   handles them internally (creates temporary columns for predicate columns not present
935
    //   in the block via `i >= block->columns()` guard in _init_current_block).
936
    //
937
    // Example: table has columns [k1, v1, v2], then DROP COLUMN v1, then
938
    //   DELETE FROM t WHERE v1 = 'x' was issued before the drop.
939
    //   - _base_tablet_schema after merge_dropped_columns: [k1, v2, v1(DROPPED)]
940
    //   - return_columns (computed before merge): [0, 1] → [k1, v2]
941
    //   - _output_schema / ref_block columns: [k1, v2] (2 columns)
942
    //   - SegmentIterator reads v1 internally for delete predicate, but does not
943
    //     output it to ref_block. copy_rows only iterates 2 columns — no OOB access.
944
0
    size_t num_cols =
945
0
            request.columns.empty() ? _base_tablet_schema->num_columns() : request.columns.size();
946
0
    return_columns.resize(num_cols);
947
0
    for (int i = 0; i < num_cols; ++i) {
948
0
        return_columns[i] = i;
949
0
    }
950
0
    std::vector<uint32_t> cluster_key_idxes;
951
952
0
    DBUG_EXECUTE_IF("SchemaChangeJob::_do_process_alter_tablet.block", DBUG_BLOCK);
953
954
    // begin to find deltas to convert from base tablet to new tablet so that
955
    // obtain base tablet and new tablet's push lock and header write lock to prevent loading data
956
0
    {
957
0
        std::lock_guard base_tablet_lock(_base_tablet->get_push_lock());
958
0
        std::lock_guard new_tablet_lock(_new_tablet->get_push_lock());
959
0
        std::lock_guard base_tablet_wlock(_base_tablet->get_header_lock());
960
0
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
961
0
        std::lock_guard<std::shared_mutex> new_tablet_wlock(_new_tablet->get_header_lock());
962
963
0
        do {
964
0
            RowsetSharedPtr max_rowset;
965
            // get history data to be converted and it will check if there is hold in base tablet
966
0
            res = _get_versions_to_be_changed(&versions_to_be_changed, &max_rowset);
967
0
            if (!res) {
968
0
                LOG(WARNING) << "fail to get version to be changed. res=" << res;
969
0
                break;
970
0
            }
971
972
0
            DBUG_EXECUTE_IF("SchemaChangeJob.process_alter_tablet.alter_fail", {
973
0
                res = Status::InternalError(
974
0
                        "inject alter tablet failed. base_tablet={}, new_tablet={}",
975
0
                        request.base_tablet_id, request.new_tablet_id);
976
0
                LOG(WARNING) << "inject error. res=" << res;
977
0
                break;
978
0
            });
979
980
            // should check the max_version >= request.alter_version, if not the convert is useless
981
0
            if (max_rowset == nullptr || max_rowset->end_version() < request.alter_version) {
982
0
                res = Status::InternalError(
983
0
                        "base tablet's max version={} is less than request version={}",
984
0
                        (max_rowset == nullptr ? 0 : max_rowset->end_version()),
985
0
                        request.alter_version);
986
0
                break;
987
0
            }
988
            // before calculating version_to_be_changed,
989
            // remove all data from new tablet, prevent to rewrite data(those double pushed when wait)
990
0
            LOG(INFO) << "begin to remove all data before end version from new tablet to prevent "
991
0
                         "rewrite."
992
0
                      << " new_tablet=" << _new_tablet->tablet_id()
993
0
                      << ", end_version=" << max_rowset->end_version();
994
0
            std::vector<RowsetSharedPtr> rowsets_to_delete;
995
0
            std::vector<std::pair<Version, RowsetSharedPtr>> version_rowsets;
996
0
            _new_tablet->acquire_version_and_rowsets(&version_rowsets);
997
0
            std::sort(version_rowsets.begin(), version_rowsets.end(),
998
0
                      [](const std::pair<Version, RowsetSharedPtr>& l,
999
0
                         const std::pair<Version, RowsetSharedPtr>& r) {
1000
0
                          return l.first.first < r.first.first;
1001
0
                      });
1002
0
            for (auto& pair : version_rowsets) {
1003
0
                if (pair.first.second <= max_rowset->end_version()) {
1004
0
                    rowsets_to_delete.push_back(pair.second);
1005
0
                } else if (pair.first.first <= max_rowset->end_version()) {
1006
                    // If max version is [X-10] and new tablet has version [7-9][10-12],
1007
                    // we only can remove [7-9] from new tablet. If we add [X-10] to new tablet, it will has version
1008
                    // cross: [X-10] [10-12].
1009
                    // So, we should return OLAP_ERR_VERSION_ALREADY_MERGED for fast fail.
1010
0
                    return Status::Error<VERSION_ALREADY_MERGED>(
1011
0
                            "New tablet has a version {} crossing base tablet's max_version={}",
1012
0
                            pair.first.to_string(), max_rowset->end_version());
1013
0
                }
1014
0
            }
1015
0
            std::vector<RowsetSharedPtr> empty_vec;
1016
0
            RETURN_IF_ERROR(_new_tablet->delete_rowsets(rowsets_to_delete, false));
1017
            // inherit cumulative_layer_point from base_tablet
1018
            // check if new_tablet.ce_point > base_tablet.ce_point?
1019
0
            _new_tablet->set_cumulative_layer_point(-1);
1020
            // save tablet meta
1021
0
            _new_tablet->save_meta();
1022
0
            for (auto& rowset : rowsets_to_delete) {
1023
                // do not call rowset.remove directly, using gc thread to delete it
1024
0
                _local_storage_engine.add_unused_rowset(rowset);
1025
0
            }
1026
1027
            // init one delete handler
1028
0
            for (auto& version : versions_to_be_changed) {
1029
0
                end_version = std::max(end_version, version.second);
1030
0
            }
1031
1032
            // acquire data sources correspond to history versions
1033
0
            RETURN_IF_ERROR(
1034
0
                    _base_tablet->capture_rs_readers_unlocked(versions_to_be_changed, &rs_splits));
1035
0
            if (rs_splits.empty()) {
1036
0
                res = Status::Error<ALTER_DELTA_DOES_NOT_EXISTS>(
1037
0
                        "fail to acquire all data sources. version_num={}, data_source_num={}",
1038
0
                        versions_to_be_changed.size(), rs_splits.size());
1039
0
                break;
1040
0
            }
1041
0
            std::vector<RowsetMetaSharedPtr> del_preds;
1042
0
            for (auto&& split : rs_splits) {
1043
0
                const auto& rs_meta = split.rs_reader->rowset()->rowset_meta();
1044
0
                if (!rs_meta->has_delete_predicate() || rs_meta->start_version() > end_version) {
1045
0
                    continue;
1046
0
                }
1047
0
                _base_tablet_schema->merge_dropped_columns(*rs_meta->tablet_schema());
1048
0
                del_preds.push_back(rs_meta);
1049
0
            }
1050
0
            res = delete_handler.init(_base_tablet_schema, del_preds, end_version);
1051
0
            if (!res) {
1052
0
                LOG(WARNING) << "init delete handler failed. base_tablet="
1053
0
                             << _base_tablet->tablet_id() << ", end_version=" << end_version;
1054
0
                break;
1055
0
            }
1056
1057
0
            reader_context.reader_type = ReaderType::READER_ALTER_TABLE;
1058
0
            reader_context.tablet_schema = _base_tablet_schema;
1059
0
            reader_context.need_ordered_result = true;
1060
0
            reader_context.delete_handler = &delete_handler;
1061
0
            reader_context.return_columns = &return_columns;
1062
0
            reader_context.sequence_id_idx = reader_context.tablet_schema->sequence_col_idx();
1063
0
            reader_context.is_unique = _base_tablet->keys_type() == UNIQUE_KEYS;
1064
0
            reader_context.batch_size = ALTER_TABLE_BATCH_SIZE;
1065
0
            reader_context.delete_bitmap = _base_tablet->tablet_meta()->delete_bitmap_ptr();
1066
0
            reader_context.version = Version(0, end_version);
1067
0
            if (!_base_tablet_schema->cluster_key_uids().empty()) {
1068
0
                for (const auto& uid : _base_tablet_schema->cluster_key_uids()) {
1069
0
                    cluster_key_idxes.emplace_back(_base_tablet_schema->field_index(uid));
1070
0
                }
1071
0
                reader_context.read_orderby_key_columns = &cluster_key_idxes;
1072
0
                reader_context.is_unique = false;
1073
0
                reader_context.sequence_id_idx = -1;
1074
0
            }
1075
0
            for (auto& rs_split : rs_splits) {
1076
0
                res = rs_split.rs_reader->init(&reader_context);
1077
0
                if (!res) {
1078
0
                    LOG(WARNING) << "failed to init rowset reader: " << _base_tablet->tablet_id();
1079
0
                    break;
1080
0
                }
1081
0
            }
1082
0
        } while (false);
1083
0
    }
1084
1085
0
    do {
1086
0
        if (!res) {
1087
0
            break;
1088
0
        }
1089
0
        SchemaChangeParams sc_params;
1090
1091
0
        if (request.__isset.query_globals && request.__isset.query_options) {
1092
0
            sc_params.runtime_state =
1093
0
                    std::make_shared<RuntimeState>(request.query_options, request.query_globals);
1094
0
        } else {
1095
            // for old version request compatibility
1096
0
            sc_params.runtime_state = std::make_shared<RuntimeState>();
1097
0
        }
1098
1099
0
        RETURN_IF_ERROR(
1100
0
                DescriptorTbl::create(&sc_params.pool, request.desc_tbl, &sc_params.desc_tbl));
1101
0
        sc_params.ref_rowset_readers.reserve(rs_splits.size());
1102
0
        for (RowSetSplits& split : rs_splits) {
1103
0
            sc_params.ref_rowset_readers.emplace_back(split.rs_reader);
1104
0
        }
1105
0
        sc_params.delete_handler = &delete_handler;
1106
0
        sc_params.be_exec_version = request.be_exec_version;
1107
0
        DCHECK(request.__isset.alter_tablet_type);
1108
0
        switch (request.alter_tablet_type) {
1109
0
        case TAlterTabletType::SCHEMA_CHANGE:
1110
0
            sc_params.alter_tablet_type = AlterTabletType::SCHEMA_CHANGE;
1111
0
            break;
1112
0
        case TAlterTabletType::ROLLUP:
1113
0
            sc_params.alter_tablet_type = AlterTabletType::ROLLUP;
1114
0
            break;
1115
0
        case TAlterTabletType::MIGRATION:
1116
0
            sc_params.alter_tablet_type = AlterTabletType::MIGRATION;
1117
0
            break;
1118
0
        }
1119
0
        if (request.__isset.materialized_view_params) {
1120
0
            for (auto item : request.materialized_view_params) {
1121
0
                AlterMaterializedViewParam mv_param;
1122
0
                mv_param.column_name = item.column_name;
1123
1124
0
                if (item.__isset.mv_expr) {
1125
0
                    mv_param.expr = std::make_shared<TExpr>(item.mv_expr);
1126
0
                }
1127
0
                sc_params.materialized_params_map.insert(
1128
0
                        std::make_pair(to_lower(item.column_name), mv_param));
1129
0
            }
1130
0
        }
1131
0
        {
1132
0
            std::lock_guard<std::shared_mutex> wrlock(_mutex);
1133
0
            _tablet_ids_in_converting.insert(_new_tablet->tablet_id());
1134
0
        }
1135
0
        int64_t real_alter_version = 0;
1136
0
        sc_params.enable_unique_key_merge_on_write =
1137
0
                _new_tablet->enable_unique_key_merge_on_write();
1138
0
        res = _convert_historical_rowsets(sc_params, &real_alter_version);
1139
0
        {
1140
0
            std::lock_guard<std::shared_mutex> wrlock(_mutex);
1141
0
            _tablet_ids_in_converting.erase(_new_tablet->tablet_id());
1142
0
        }
1143
0
        if (!res) {
1144
0
            break;
1145
0
        }
1146
1147
0
        DCHECK_GE(real_alter_version, request.alter_version);
1148
1149
0
        if (_new_tablet->keys_type() == UNIQUE_KEYS &&
1150
0
            _new_tablet->enable_unique_key_merge_on_write()) {
1151
0
            res = _calc_delete_bitmap_for_mow_table(real_alter_version);
1152
0
            if (!res) {
1153
0
                break;
1154
0
            }
1155
0
        } else {
1156
            // set state to ready
1157
0
            std::lock_guard<std::shared_mutex> new_wlock(_new_tablet->get_header_lock());
1158
0
            SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1159
0
            res = _new_tablet->set_tablet_state(TabletState::TABLET_RUNNING);
1160
0
            if (!res) {
1161
0
                break;
1162
0
            }
1163
0
            _new_tablet->save_meta();
1164
0
        }
1165
0
    } while (false);
1166
1167
0
    if (res) {
1168
        // _validate_alter_result should be outside the above while loop.
1169
        // to avoid requiring the header lock twice.
1170
0
        res = _validate_alter_result(request);
1171
0
    }
1172
1173
    // if failed convert history data, then just remove the new tablet
1174
0
    if (!res) {
1175
0
        LOG(WARNING) << "failed to alter tablet. base_tablet=" << _base_tablet->tablet_id()
1176
0
                     << ", drop new_tablet=" << _new_tablet->tablet_id();
1177
        // do not drop the new tablet and its data. GC thread will
1178
0
    }
1179
1180
0
    return res;
1181
0
}
1182
1183
0
bool SchemaChangeJob::tablet_in_converting(int64_t tablet_id) {
1184
0
    std::shared_lock rdlock(_mutex);
1185
0
    return _tablet_ids_in_converting.find(tablet_id) != _tablet_ids_in_converting.end();
1186
0
}
1187
1188
Status SchemaChangeJob::_get_versions_to_be_changed(std::vector<Version>* versions_to_be_changed,
1189
0
                                                    RowsetSharedPtr* max_rowset) {
1190
0
    RowsetSharedPtr rowset = _base_tablet->get_rowset_with_max_version();
1191
0
    if (rowset == nullptr) {
1192
0
        return Status::Error<ALTER_DELTA_DOES_NOT_EXISTS>("Tablet has no version. base_tablet={}",
1193
0
                                                          _base_tablet->tablet_id());
1194
0
    }
1195
0
    *max_rowset = rowset;
1196
1197
0
    *versions_to_be_changed = DORIS_TRY(_base_tablet->capture_consistent_versions_unlocked(
1198
0
            Version(0, rowset->version().second), {}));
1199
0
    return Status::OK();
1200
0
}
1201
1202
// The `real_alter_version` parameter indicates that the version of [0-real_alter_version] is
1203
// converted from a base tablet, only used for the mow table now.
1204
Status SchemaChangeJob::_convert_historical_rowsets(const SchemaChangeParams& sc_params,
1205
0
                                                    int64_t* real_alter_version) {
1206
0
    LOG(INFO) << "begin to convert historical rowsets for new_tablet from base_tablet."
1207
0
              << " base_tablet=" << _base_tablet->tablet_id()
1208
0
              << ", new_tablet=" << _new_tablet->tablet_id() << ", job_id=" << _job_id;
1209
1210
    // find end version
1211
0
    int64_t end_version = -1;
1212
0
    for (const auto& ref_rowset_reader : sc_params.ref_rowset_readers) {
1213
0
        if (ref_rowset_reader->version().second > end_version) {
1214
0
            end_version = ref_rowset_reader->version().second;
1215
0
        }
1216
0
    }
1217
1218
    // Add filter information in change, and filter column information will be set in parse_request
1219
    // And filter some data every time the row block changes
1220
0
    BlockChanger changer(_new_tablet_schema, *sc_params.desc_tbl, sc_params.runtime_state);
1221
1222
0
    bool sc_sorting = false;
1223
0
    bool sc_directly = false;
1224
1225
    // a.Parse the Alter request and convert it into an internal representation
1226
0
    Status res = parse_request(sc_params, _base_tablet_schema.get(), _new_tablet_schema.get(),
1227
0
                               &changer, &sc_sorting, &sc_directly);
1228
0
    LOG(INFO) << "schema change type, sc_sorting: " << sc_sorting
1229
0
              << ", sc_directly: " << sc_directly << ", base_tablet=" << _base_tablet->tablet_id()
1230
0
              << ", new_tablet=" << _new_tablet->tablet_id();
1231
1232
0
    auto process_alter_exit = [&]() -> Status {
1233
0
        {
1234
            // save tablet meta here because rowset meta is not saved during add rowset
1235
0
            std::lock_guard new_wlock(_new_tablet->get_header_lock());
1236
0
            SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1237
0
            _new_tablet->save_meta();
1238
0
        }
1239
0
        if (res) {
1240
0
            Version test_version(0, end_version);
1241
0
            res = _new_tablet->check_version_integrity(test_version);
1242
0
        }
1243
1244
0
        LOG(INFO) << "finish converting rowsets for new_tablet from base_tablet. "
1245
0
                  << "base_tablet=" << _base_tablet->tablet_id()
1246
0
                  << ", new_tablet=" << _new_tablet->tablet_id();
1247
0
        return res;
1248
0
    };
1249
1250
0
    if (!res) {
1251
0
        LOG(WARNING) << "failed to parse the request. res=" << res;
1252
0
        return process_alter_exit();
1253
0
    }
1254
1255
0
    if (!sc_sorting && !sc_directly && sc_params.alter_tablet_type == AlterTabletType::ROLLUP) {
1256
0
        res = Status::Error<SCHEMA_SCHEMA_INVALID>(
1257
0
                "Don't support to add materialized view by linked schema change");
1258
0
        return process_alter_exit();
1259
0
    }
1260
1261
    // b. Generate historical data converter
1262
0
    auto sc_procedure = _get_sc_procedure(
1263
0
            changer, sc_sorting, sc_directly,
1264
0
            _local_storage_engine.memory_limitation_bytes_per_thread_for_schema_change());
1265
1266
0
    DBUG_EXECUTE_IF("SchemaChangeJob::_convert_historical_rowsets.block", DBUG_BLOCK);
1267
1268
    // c.Convert historical data
1269
0
    bool have_failure_rowset = false;
1270
0
    for (const auto& rs_reader : sc_params.ref_rowset_readers) {
1271
        // set status for monitor
1272
        // As long as there is a new_table as running, ref table is set as running
1273
        // NOTE If the first sub_table fails first, it will continue to go as normal here
1274
        // When tablet create new rowset writer, it may change rowset type, in this case
1275
        // linked schema change will not be used.
1276
0
        RowsetWriterContext context;
1277
0
        context.version = rs_reader->version();
1278
0
        context.rowset_state = VISIBLE;
1279
0
        context.segments_overlap = rs_reader->rowset()->rowset_meta()->segments_overlap();
1280
0
        context.tablet_schema = _new_tablet_schema;
1281
0
        context.newest_write_timestamp = rs_reader->newest_write_timestamp();
1282
0
        context.allow_packed_file = false;
1283
1284
0
        if (!rs_reader->rowset()->is_local()) {
1285
0
            auto maybe_resource = rs_reader->rowset()->rowset_meta()->remote_storage_resource();
1286
0
            if (!maybe_resource) {
1287
0
                return maybe_resource.error();
1288
0
            }
1289
0
            context.storage_resource = *maybe_resource.value();
1290
0
        }
1291
1292
0
        context.write_type = DataWriteType::TYPE_SCHEMA_CHANGE;
1293
        // TODO if support VerticalSegmentWriter, also need to handle cluster key primary key index
1294
0
        bool vertical = false;
1295
0
        if (sc_sorting && !_new_tablet->tablet_schema()->cluster_key_uids().empty()) {
1296
            // see VBaseSchemaChangeWithSorting::_external_sorting
1297
0
            vertical = true;
1298
0
        }
1299
0
        auto result = _new_tablet->create_rowset_writer(context, vertical);
1300
0
        if (!result.has_value()) {
1301
0
            res = Status::Error<ROWSET_BUILDER_INIT>("create_rowset_writer failed, reason={}",
1302
0
                                                     result.error().to_string());
1303
0
            return process_alter_exit();
1304
0
        }
1305
0
        auto rowset_writer = std::move(result).value();
1306
0
        auto pending_rs_guard = _local_storage_engine.add_pending_rowset(context);
1307
1308
0
        if (res = sc_procedure->process(rs_reader, rowset_writer.get(), _new_tablet, _base_tablet,
1309
0
                                        _base_tablet_schema, _new_tablet_schema);
1310
0
            !res) {
1311
0
            LOG(WARNING) << "failed to process the version."
1312
0
                         << " version=" << rs_reader->version().first << "-"
1313
0
                         << rs_reader->version().second << ", " << res.to_string();
1314
0
            return process_alter_exit();
1315
0
        }
1316
        // Add the new version of the data to the header
1317
        // In order to prevent the occurrence of deadlock, we must first lock the old table, and then lock the new table
1318
0
        std::lock_guard lock(_new_tablet->get_push_lock());
1319
0
        RowsetSharedPtr new_rowset;
1320
0
        if (!(res = rowset_writer->build(new_rowset)).ok()) {
1321
0
            LOG(WARNING) << "failed to build rowset, exit alter process";
1322
0
            return process_alter_exit();
1323
0
        }
1324
0
        res = _new_tablet->add_rowset(new_rowset);
1325
0
        if (res.is<PUSH_VERSION_ALREADY_EXIST>()) {
1326
0
            LOG(WARNING) << "version already exist, version revert occurred. "
1327
0
                         << "tablet=" << _new_tablet->tablet_id() << ", version='"
1328
0
                         << rs_reader->version().first << "-" << rs_reader->version().second;
1329
0
            _local_storage_engine.add_unused_rowset(new_rowset);
1330
0
            have_failure_rowset = true;
1331
0
            res = Status::OK();
1332
0
        } else if (!res) {
1333
0
            LOG(WARNING) << "failed to register new version. "
1334
0
                         << " tablet=" << _new_tablet->tablet_id()
1335
0
                         << ", version=" << rs_reader->version().first << "-"
1336
0
                         << rs_reader->version().second;
1337
0
            _local_storage_engine.add_unused_rowset(new_rowset);
1338
0
            return process_alter_exit();
1339
0
        } else {
1340
0
            VLOG_NOTICE << "register new version. tablet=" << _new_tablet->tablet_id()
1341
0
                        << ", version=" << rs_reader->version().first << "-"
1342
0
                        << rs_reader->version().second;
1343
0
        }
1344
0
        if (!have_failure_rowset) {
1345
0
            *real_alter_version = rs_reader->version().second;
1346
0
        }
1347
1348
0
        VLOG_TRACE << "succeed to convert a history version."
1349
0
                   << " version=" << rs_reader->version().first << "-"
1350
0
                   << rs_reader->version().second;
1351
0
    }
1352
1353
    // XXX:The SchemaChange state should not be canceled at this time, because the new Delta has to be converted to the old and new Schema version
1354
0
    return process_alter_exit();
1355
0
}
1356
1357
static const std::string WHERE_SIGN_LOWER = to_lower("__DORIS_WHERE_SIGN__");
1358
1359
// @static
1360
// Analyze the mapping of the column and the mapping of the filter key
1361
Status SchemaChangeJob::parse_request(const SchemaChangeParams& sc_params,
1362
                                      TabletSchema* base_tablet_schema,
1363
                                      TabletSchema* new_tablet_schema, BlockChanger* changer,
1364
0
                                      bool* sc_sorting, bool* sc_directly) {
1365
0
    changer->set_type(sc_params.alter_tablet_type);
1366
0
    changer->set_compatible_version(sc_params.be_exec_version);
1367
1368
0
    const std::unordered_map<std::string, AlterMaterializedViewParam>& materialized_function_map =
1369
0
            sc_params.materialized_params_map;
1370
0
    DescriptorTbl desc_tbl = *sc_params.desc_tbl;
1371
1372
    // set column mapping
1373
0
    for (size_t i = 0, new_schema_size = new_tablet_schema->num_columns(); i < new_schema_size;
1374
0
         ++i) {
1375
0
        const TabletColumn& new_column = new_tablet_schema->column(i);
1376
0
        const std::string& column_name_lower = to_lower(new_column.name());
1377
0
        ColumnMapping* column_mapping = changer->get_mutable_column_mapping(i);
1378
0
        column_mapping->new_column = &new_column;
1379
1380
0
        column_mapping->ref_column_idx = base_tablet_schema->field_index(new_column.name());
1381
1382
0
        if (materialized_function_map.find(column_name_lower) != materialized_function_map.end()) {
1383
0
            auto mv_param = materialized_function_map.find(column_name_lower)->second;
1384
0
            column_mapping->expr = mv_param.expr;
1385
0
            if (column_mapping->expr != nullptr) {
1386
0
                continue;
1387
0
            }
1388
0
        }
1389
1390
0
        if (column_mapping->ref_column_idx >= 0) {
1391
0
            continue;
1392
0
        }
1393
1394
0
        if (sc_params.alter_tablet_type == ROLLUP) {
1395
0
            std::string materialized_function_map_str;
1396
0
            for (auto str : materialized_function_map) {
1397
0
                if (!materialized_function_map_str.empty()) {
1398
0
                    materialized_function_map_str += ',';
1399
0
                }
1400
0
                materialized_function_map_str += str.first;
1401
0
            }
1402
0
            return Status::InternalError(
1403
0
                    "referenced column was missing. [column={},materialized_function_map={}]",
1404
0
                    new_column.name(), materialized_function_map_str);
1405
0
        }
1406
1407
0
        if (new_column.name().find("__doris_shadow_") == 0) {
1408
            // Should delete in the future, just a protection for bug.
1409
0
            LOG(INFO) << "a shadow column is encountered " << new_column.name();
1410
0
            return Status::InternalError("failed due to operate on shadow column");
1411
0
        }
1412
        // Newly added column go here
1413
0
        column_mapping->ref_column_idx = -1;
1414
1415
0
        if (i < base_tablet_schema->num_short_key_columns()) {
1416
0
            *sc_directly = true;
1417
0
        }
1418
0
        RETURN_IF_ERROR(
1419
0
                _init_column_mapping(column_mapping, new_column, new_column.default_value()));
1420
1421
0
        LOG(INFO) << "A column with default value will be added after schema changing. "
1422
0
                  << "column=" << new_column.name()
1423
0
                  << ", default_value=" << new_column.default_value();
1424
0
    }
1425
1426
0
    if (materialized_function_map.contains(WHERE_SIGN_LOWER)) {
1427
0
        changer->set_where_expr(materialized_function_map.find(WHERE_SIGN_LOWER)->second.expr);
1428
0
    }
1429
1430
    // If the reference sequence of the Key column is out of order, it needs to be reordered
1431
0
    int num_default_value = 0;
1432
1433
0
    for (int i = 0, new_schema_size = cast_set<int>(new_tablet_schema->num_key_columns());
1434
0
         i < new_schema_size; ++i) {
1435
0
        ColumnMapping* column_mapping = changer->get_mutable_column_mapping(i);
1436
1437
0
        if (!column_mapping->has_reference()) {
1438
0
            num_default_value++;
1439
0
            continue;
1440
0
        }
1441
1442
0
        if (column_mapping->ref_column_idx != i - num_default_value) {
1443
0
            *sc_sorting = true;
1444
0
            return Status::OK();
1445
0
        }
1446
0
    }
1447
1448
0
    if (base_tablet_schema->keys_type() != new_tablet_schema->keys_type()) {
1449
        // only when base table is dup and mv is agg
1450
        // the rollup job must be reagg.
1451
0
        *sc_sorting = true;
1452
0
        return Status::OK();
1453
0
    }
1454
1455
    // If the sort of key has not been changed but the new keys num is less then base's,
1456
    // the new table should be re agg.
1457
    // So we also need to set sc_sorting = true.
1458
    // A, B, C are keys(sort keys), D is value
1459
    // followings need resort:
1460
    //      old keys:    A   B   C   D
1461
    //      new keys:    A   B
1462
0
    if (new_tablet_schema->keys_type() != KeysType::DUP_KEYS &&
1463
0
        new_tablet_schema->num_key_columns() < base_tablet_schema->num_key_columns()) {
1464
        // this is a table with aggregate key type, and num of key columns in new schema
1465
        // is less, which means the data in new tablet should be more aggregated.
1466
        // so we use sorting schema change to sort and merge the data.
1467
0
        *sc_sorting = true;
1468
0
        return Status::OK();
1469
0
    }
1470
1471
0
    if (sc_params.alter_tablet_type == ROLLUP) {
1472
0
        *sc_directly = true;
1473
0
        return Status::OK();
1474
0
    }
1475
1476
0
    if (sc_params.enable_unique_key_merge_on_write &&
1477
0
        new_tablet_schema->num_key_columns() > base_tablet_schema->num_key_columns()) {
1478
0
        *sc_directly = true;
1479
0
        return Status::OK();
1480
0
    }
1481
1482
0
    if (base_tablet_schema->num_short_key_columns() != new_tablet_schema->num_short_key_columns()) {
1483
        // the number of short_keys changed, can't do linked schema change
1484
0
        *sc_directly = true;
1485
0
        return Status::OK();
1486
0
    }
1487
1488
0
    if (!sc_params.delete_handler->empty()) {
1489
        // there exists delete condition in header, can't do linked schema change
1490
0
        *sc_directly = true;
1491
0
        return Status::OK();
1492
0
    }
1493
1494
    // if new tablet enable row store, or new tablet has different row store columns
1495
0
    if ((!base_tablet_schema->exist_column(BeConsts::ROW_STORE_COL) &&
1496
0
         new_tablet_schema->exist_column(BeConsts::ROW_STORE_COL)) ||
1497
0
        !std::equal(new_tablet_schema->row_columns_uids().begin(),
1498
0
                    new_tablet_schema->row_columns_uids().end(),
1499
0
                    base_tablet_schema->row_columns_uids().begin(),
1500
0
                    base_tablet_schema->row_columns_uids().end())) {
1501
0
        *sc_directly = true;
1502
0
    }
1503
1504
0
    for (size_t i = 0; i < new_tablet_schema->num_columns(); ++i) {
1505
0
        ColumnMapping* column_mapping = changer->get_mutable_column_mapping(i);
1506
0
        if (column_mapping->expr != nullptr) {
1507
0
            *sc_directly = true;
1508
0
            return Status::OK();
1509
0
        } else if (column_mapping->ref_column_idx >= 0) {
1510
            // index changed
1511
0
            if (variant_util::has_schema_index_diff(new_tablet_schema, base_tablet_schema,
1512
0
                                                    cast_set<int32_t>(i),
1513
0
                                                    column_mapping->ref_column_idx)) {
1514
0
                *sc_directly = true;
1515
0
                return Status::OK();
1516
0
            }
1517
0
        }
1518
0
    }
1519
1520
    // if rs_reader has remote files, link schema change is not supported,
1521
    // use directly schema change instead.
1522
0
    if (!(*sc_directly) && !(*sc_sorting)) {
1523
        // check has remote rowset
1524
        // work for cloud and cold storage
1525
0
        for (const auto& rs_reader : sc_params.ref_rowset_readers) {
1526
0
            if (!rs_reader->rowset()->is_local()) {
1527
0
                *sc_directly = true;
1528
0
                break;
1529
0
            }
1530
0
        }
1531
0
    }
1532
1533
0
    return Status::OK();
1534
0
}
1535
1536
Status SchemaChangeJob::_init_column_mapping(ColumnMapping* column_mapping,
1537
                                             const TabletColumn& column_schema,
1538
0
                                             const std::string& value) {
1539
0
    auto t = StorageFieldFactory::create(column_schema);
1540
0
    Defer defer([t]() { delete t; });
1541
0
    if (t == nullptr) {
1542
0
        return Status::Uninitialized("Unsupport field creation of {}", column_schema.name());
1543
0
    }
1544
1545
0
    if (!column_schema.is_nullable() || value.length() != 0) {
1546
0
        DataTypeSerDe::FormatOptions options;
1547
0
        RETURN_IF_ERROR(column_schema.get_vec_type()->get_serde()->from_olap_string(
1548
0
                value, column_mapping->default_value, options));
1549
0
    }
1550
1551
0
    return Status::OK();
1552
0
}
1553
1554
0
Status SchemaChangeJob::_validate_alter_result(const TAlterTabletReqV2& request) {
1555
0
    Version max_continuous_version = {-1, 0};
1556
0
    _new_tablet->max_continuous_version_from_beginning(&max_continuous_version);
1557
0
    LOG(INFO) << "find max continuous version of tablet=" << _new_tablet->tablet_id()
1558
0
              << ", start_version=" << max_continuous_version.first
1559
0
              << ", end_version=" << max_continuous_version.second;
1560
0
    if (max_continuous_version.second < request.alter_version) {
1561
0
        return Status::InternalError("result version={} is less than request version={}",
1562
0
                                     max_continuous_version.second, request.alter_version);
1563
0
    }
1564
1565
0
    std::vector<std::pair<Version, RowsetSharedPtr>> version_rowsets;
1566
0
    {
1567
0
        std::shared_lock rdlock(_new_tablet->get_header_lock());
1568
0
        _new_tablet->acquire_version_and_rowsets(&version_rowsets);
1569
0
    }
1570
0
    for (auto& pair : version_rowsets) {
1571
0
        RowsetSharedPtr rowset = pair.second;
1572
0
        if (!rowset->check_file_exist()) {
1573
0
            return Status::Error<NOT_FOUND>(
1574
0
                    "SchemaChangeJob::_validate_alter_result meet invalid rowset");
1575
0
        }
1576
0
    }
1577
0
    return Status::OK();
1578
0
}
1579
1580
// For unique with merge-on-write table, should process delete bitmap here.
1581
// 1. During double write, the newly imported rowsets does not calculate
1582
// delete bitmap and publish successfully.
1583
// 2. After conversion, calculate delete bitmap for the rowsets imported
1584
// during double write. During this period, new data can still be imported
1585
// witout calculating delete bitmap and publish successfully.
1586
// 3. Block the new publish, calculate the delete bitmap of the
1587
// incremental rowsets.
1588
// 4. Switch the tablet status to TABLET_RUNNING. The newly imported
1589
// data will calculate delete bitmap.
1590
0
Status SchemaChangeJob::_calc_delete_bitmap_for_mow_table(int64_t alter_version) {
1591
0
    DBUG_EXECUTE_IF("SchemaChangeJob._calc_delete_bitmap_for_mow_table.random_failed", {
1592
0
        if (rand() % 100 < (100 * dp->param("percent", 0.1))) {
1593
0
            LOG_WARNING("SchemaChangeJob._calc_delete_bitmap_for_mow_table.random_failed");
1594
0
            return Status::InternalError("debug schema change calc delete bitmap random failed");
1595
0
        }
1596
0
    });
1597
1598
    // can't do compaction when calc delete bitmap, if the rowset being calculated does
1599
    // a compaction, it may cause the delete bitmap to be missed.
1600
0
    std::lock_guard base_compaction_lock(_new_tablet->get_base_compaction_lock());
1601
0
    std::lock_guard cumu_compaction_lock(_new_tablet->get_cumulative_compaction_lock());
1602
1603
    // step 2
1604
0
    int64_t max_version = _new_tablet->max_version().second;
1605
0
    std::vector<RowsetSharedPtr> rowsets;
1606
0
    if (alter_version < max_version) {
1607
0
        LOG(INFO) << "alter table for unique with merge-on-write, calculate delete bitmap of "
1608
0
                  << "double write rowsets for version: " << alter_version + 1 << "-" << max_version
1609
0
                  << " new_tablet=" << _new_tablet->tablet_id();
1610
0
        std::shared_lock rlock(_new_tablet->get_header_lock());
1611
0
        auto ret = DORIS_TRY(_new_tablet->capture_consistent_rowsets_unlocked(
1612
0
                {alter_version + 1, max_version}, CaptureRowsetOps {}));
1613
0
        rowsets = std::move(ret.rowsets);
1614
0
    }
1615
0
    for (auto rowset_ptr : rowsets) {
1616
0
        std::lock_guard rwlock(_new_tablet->get_rowset_update_lock());
1617
0
        std::shared_lock rlock(_new_tablet->get_header_lock());
1618
0
        RETURN_IF_ERROR(Tablet::update_delete_bitmap_without_lock(_new_tablet, rowset_ptr));
1619
0
    }
1620
1621
    // step 3
1622
0
    std::lock_guard rwlock(_new_tablet->get_rowset_update_lock());
1623
0
    std::lock_guard new_wlock(_new_tablet->get_header_lock());
1624
0
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
1625
0
    int64_t new_max_version = _new_tablet->max_version_unlocked();
1626
0
    rowsets.clear();
1627
0
    if (max_version < new_max_version) {
1628
0
        LOG(INFO) << "alter table for unique with merge-on-write, calculate delete bitmap of "
1629
0
                  << "incremental rowsets for version: " << max_version + 1 << "-"
1630
0
                  << new_max_version << " new_tablet=" << _new_tablet->tablet_id();
1631
0
        auto ret = DORIS_TRY(_new_tablet->capture_consistent_rowsets_unlocked(
1632
0
                {max_version + 1, new_max_version}, CaptureRowsetOps {}));
1633
0
        rowsets = std::move(ret.rowsets);
1634
0
    }
1635
0
    for (auto&& rowset_ptr : rowsets) {
1636
0
        RETURN_IF_ERROR(Tablet::update_delete_bitmap_without_lock(_new_tablet, rowset_ptr));
1637
0
    }
1638
    // step 4
1639
0
    RETURN_IF_ERROR(_new_tablet->set_tablet_state(TabletState::TABLET_RUNNING));
1640
0
    _new_tablet->save_meta();
1641
0
    return Status::OK();
1642
0
}
1643
1644
#include "common/compile_check_end.h"
1645
1646
} // namespace doris