Coverage Report

Created: 2026-02-09 19:49

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