Coverage Report

Created: 2026-08-16 01:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_schema_change_job.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 "cloud/cloud_schema_change_job.h"
19
20
#include <gen_cpp/Types_types.h>
21
#include <gen_cpp/cloud.pb.h>
22
23
#include <algorithm>
24
#include <chrono>
25
#include <memory>
26
#include <mutex>
27
#include <random>
28
#include <ranges>
29
#include <thread>
30
31
#include "cloud/cloud_meta_mgr.h"
32
#include "cloud/cloud_tablet_mgr.h"
33
#include "common/status.h"
34
#include "service/backend_options.h"
35
#include "storage/delete/delete_handler.h"
36
#include "storage/index/inverted/inverted_index_desc.h"
37
#include "storage/olap_define.h"
38
#include "storage/rowset/beta_rowset.h"
39
#include "storage/rowset/rowset.h"
40
#include "storage/rowset/rowset_factory.h"
41
#include "storage/storage_engine.h"
42
#include "storage/tablet/tablet.h"
43
#include "storage/tablet/tablet_fwd.h"
44
#include "storage/tablet/tablet_meta.h"
45
#include "util/debug_points.h"
46
47
namespace doris {
48
using namespace ErrorCode;
49
50
static constexpr int ALTER_TABLE_BATCH_SIZE = 4096;
51
static constexpr int SCHEMA_CHANGE_DELETE_BITMAP_LOCK_ID = -2;
52
53
std::unique_ptr<SchemaChange> get_sc_procedure(const BlockChanger& changer, bool sc_sorting,
54
1
                                               int64_t mem_limit) {
55
1
    if (sc_sorting) {
56
0
        return std::make_unique<VBaseSchemaChangeWithSorting>(changer, mem_limit);
57
0
    }
58
    // else sc_directly
59
1
    return std::make_unique<VSchemaChangeDirectly>(changer);
60
1
}
61
62
CloudSchemaChangeJob::CloudSchemaChangeJob(CloudStorageEngine& cloud_storage_engine,
63
                                           std::string job_id, int64_t expiration)
64
5
        : _cloud_storage_engine(cloud_storage_engine),
65
5
          _job_id(std::move(job_id)),
66
5
          _expiration(expiration) {
67
5
    _initiator = boost::uuids::hash_value(UUIDGenerator::instance()->next_uuid()) &
68
5
                 std::numeric_limits<int64_t>::max();
69
5
}
70
71
5
CloudSchemaChangeJob::~CloudSchemaChangeJob() = default;
72
73
5
Status CloudSchemaChangeJob::process_alter_tablet(const TAlterTabletReqV2& request) {
74
5
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::process_alter_tablet.block", DBUG_BLOCK);
75
    // new tablet has to exist
76
5
    _new_tablet = DORIS_TRY(_cloud_storage_engine.tablet_mgr().get_tablet(request.new_tablet_id));
77
5
    if (_new_tablet->tablet_state() == TABLET_RUNNING) {
78
0
        LOG(INFO) << "schema change job has already finished. base_tablet_id="
79
0
                  << request.base_tablet_id << ", new_tablet_id=" << request.new_tablet_id
80
0
                  << ", alter_version=" << request.alter_version << ", job_id=" << _job_id;
81
0
        return Status::OK();
82
0
    }
83
84
5
    _base_tablet = DORIS_TRY(_cloud_storage_engine.tablet_mgr().get_tablet(request.base_tablet_id));
85
86
5
    static constexpr long TRY_LOCK_TIMEOUT = 30;
87
5
    std::unique_lock schema_change_lock(_base_tablet->get_schema_change_lock(), std::defer_lock);
88
5
    bool owns_lock = schema_change_lock.try_lock_for(std::chrono::seconds(TRY_LOCK_TIMEOUT));
89
90
5
    _new_tablet->set_alter_failed(false);
91
5
    Defer defer([this] {
92
        // if tablet state is not TABLET_RUNNING when return, indicates that alter has failed.
93
5
        if (_new_tablet->tablet_state() != TABLET_RUNNING) {
94
4
            _new_tablet->set_alter_failed(true);
95
4
        }
96
5
    });
97
98
5
    if (!owns_lock) {
99
0
        LOG(WARNING) << "Failed to obtain schema change lock, there might be inverted index being "
100
0
                        "built on base_tablet="
101
0
                     << request.base_tablet_id;
102
0
        return Status::Error<TRY_LOCK_FAILED>(
103
0
                "Failed to obtain schema change lock, there might be inverted index being "
104
0
                "built on base_tablet=",
105
0
                request.base_tablet_id);
106
0
    }
107
    // MUST sync rowsets before capturing rowset readers and building DeleteHandler
108
5
    SyncOptions options;
109
    // The SC boundary (V1) must be calculated from the latest visible rowsets of the base
110
    // tablet. Do not cap this sync by request.alter_version, which may be stale across retries.
111
5
    RETURN_IF_ERROR(_base_tablet->sync_rowsets(options));
112
    // ATTN: Only convert rowsets of version larger than 1, MUST let the new tablet cache have rowset [0-1]
113
5
    _output_cumulative_point = _base_tablet->cumulative_layer_point();
114
5
    std::vector<RowSetSplits> rs_splits;
115
5
    int64_t base_max_version = _base_tablet->max_version_unlocked();
116
5
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::process_alter_tablet.override_base_max_version", {
117
5
        auto v = dp->param<int64_t>("version", -1);
118
5
        if (v > 0) {
119
5
            LOG(INFO) << "override base_max_version from " << base_max_version << " to " << v;
120
5
            base_max_version = v;
121
5
        }
122
5
    });
123
5
    cloud::TabletJobInfoPB job;
124
5
    auto* idx = job.mutable_idx();
125
5
    idx->set_tablet_id(_base_tablet->tablet_id());
126
5
    idx->set_table_id(_base_tablet->table_id());
127
5
    idx->set_index_id(_base_tablet->index_id());
128
5
    idx->set_partition_id(_base_tablet->partition_id());
129
5
    auto* sc_job = job.mutable_schema_change();
130
5
    sc_job->set_id(_job_id);
131
5
    sc_job->set_initiator(BackendOptions::get_localhost() + ':' +
132
5
                          std::to_string(config::heartbeat_service_port));
133
5
    sc_job->set_alter_version(base_max_version);
134
5
    auto* new_tablet_idx = sc_job->mutable_new_tablet_idx();
135
5
    new_tablet_idx->set_tablet_id(_new_tablet->tablet_id());
136
5
    new_tablet_idx->set_table_id(_new_tablet->table_id());
137
5
    new_tablet_idx->set_index_id(_new_tablet->index_id());
138
5
    new_tablet_idx->set_partition_id(_new_tablet->partition_id());
139
5
    cloud::StartTabletJobResponse start_resp;
140
5
    auto st = _cloud_storage_engine.meta_mgr().prepare_tablet_job(job, &start_resp);
141
5
    if (!st.ok()) {
142
1
        if (start_resp.status().code() == cloud::JOB_ALREADY_SUCCESS) {
143
1
            st = _new_tablet->sync_rowsets();
144
1
            if (!st.ok()) {
145
0
                LOG_WARNING("failed to sync new tablet")
146
0
                        .tag("tablet_id", _new_tablet->tablet_id())
147
0
                        .error(st);
148
0
            }
149
1
            return Status::OK();
150
1
        }
151
0
        return st;
152
1
    }
153
4
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::process_alter_tablet.alter_fail", {
154
4
        auto res =
155
4
                Status::InternalError("inject alter tablet failed. base_tablet={}, new_tablet={}",
156
4
                                      request.base_tablet_id, request.new_tablet_id);
157
4
        LOG(WARNING) << "inject error. res=" << res;
158
4
        return res;
159
4
    });
160
161
    // Check for cross-V1 compaction rowsets on new tablet.
162
    // A compaction may have committed a rowset that crosses the alter_version
163
    // boundary (V1) before prepare_tablet_job's clear_compaction took effect.
164
    // If detected, abort the SC job in meta-service so the next retry registers
165
    // a fresh job with a higher V1 (where the crossing rowset falls within range).
166
4
    {
167
4
        RETURN_IF_ERROR(_new_tablet->sync_rowsets());
168
4
        std::shared_lock rlock(_new_tablet->get_header_lock());
169
5
        for (auto& [v, rs] : _new_tablet->rowset_map()) {
170
5
            if (v.first > 1 && v.first <= start_resp.alter_version() &&
171
5
                v.second > start_resp.alter_version()) {
172
3
                LOG(WARNING) << "cross-V1 compaction detected on new tablet"
173
3
                             << ", tablet_id=" << _new_tablet->tablet_id() << ", rowset=["
174
3
                             << v.first << "-" << v.second << "]"
175
3
                             << ", alter_version=" << start_resp.alter_version()
176
3
                             << ", job_id=" << _job_id << ". Aborting SC job and retrying.";
177
                // Abort the SC job so the next retry can register with a higher alter_version.
178
                // retry_rpc() may already have committed an ABORT but lost the reply; the
179
                // replay then sees INVALID_ARGUMENT "there is no running schema_change",
180
                // which means the job is in fact cleared. Treat that as success so FE can
181
                // still retry. Any other failure is ambiguous — the stale job may remain
182
                // and subsequent retries would hit meta-service idempotency, so return a
183
                // non-retryable error to avoid burning retries on a stuck state.
184
3
                auto abort_st = _cloud_storage_engine.meta_mgr().abort_tablet_job(job);
185
3
                bool job_already_cleared =
186
3
                        abort_st.is<ErrorCode::INVALID_ARGUMENT>() &&
187
3
                        abort_st.to_string().find("no running schema_change") != std::string::npos;
188
3
                if (!abort_st.ok() && !job_already_cleared) {
189
1
                    LOG(WARNING) << "failed to abort SC job after cross-V1 detection"
190
1
                                 << ", tablet_id=" << _new_tablet->tablet_id()
191
1
                                 << ", error=" << abort_st
192
1
                                 << ". Returning non-retryable error to avoid stale job retries.";
193
1
                    return Status::InternalError(
194
1
                            "cross-V1 compaction detected but failed to abort SC job, "
195
1
                            "tablet_id={}, rowset=[{}-{}], alter_version={}, abort_err={}",
196
1
                            _new_tablet->tablet_id(), v.first, v.second, start_resp.alter_version(),
197
1
                            abort_st.to_string());
198
1
                }
199
2
                if (job_already_cleared) {
200
1
                    LOG(INFO) << "SC job already cleared (idempotent abort replay), safe to retry"
201
1
                              << ", tablet_id=" << _new_tablet->tablet_id();
202
1
                }
203
2
                return Status::Error<ErrorCode::SC_COMPACTION_CONFLICT>(
204
2
                        "cross-V1 compaction detected on new tablet, tablet_id={}, "
205
2
                        "rowset=[{}-{}], alter_version={}",
206
2
                        _new_tablet->tablet_id(), v.first, v.second, start_resp.alter_version());
207
3
            }
208
5
        }
209
4
    }
210
211
    // Use the registered alter_version returned by meta-service instead of the original FE task
212
    // version. The task can be created when FE still sees version 1, but by the time BE starts
213
    // the schema change new data may already have been published and start_tablet_job can advance
214
    // alter_version. In that case we still need to capture historical rowsets in [2, alter_version].
215
1
    if (start_resp.alter_version() > 1) {
216
        // [0-1] is a placeholder rowset, no need to convert
217
1
        RETURN_IF_ERROR(_base_tablet->capture_rs_readers({2, start_resp.alter_version()},
218
1
                                                         &rs_splits,
219
1
                                                         {.skip_missing_versions = false,
220
1
                                                          .enable_prefer_cached_rowset = false,
221
1
                                                          .query_freshness_tolerance_ms = -1}));
222
1
    }
223
    // Between prepare_tablet_job (SC job registered in meta-service) and
224
    // set_alter_version (local alter_version update). Used to test cross-V1 race.
225
1
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::process_alter_tablet.after_prepare_job", DBUG_BLOCK);
226
227
1
    Defer defer2 {[&]() {
228
1
        _new_tablet->set_alter_version(-1);
229
1
        _base_tablet->set_alter_version(-1);
230
1
    }};
231
1
    _new_tablet->set_alter_version(start_resp.alter_version());
232
1
    _base_tablet->set_alter_version(start_resp.alter_version());
233
1
    LOG(INFO) << "Begin to alter tablet. base_tablet_id=" << request.base_tablet_id
234
1
              << ", new_tablet_id=" << request.new_tablet_id
235
1
              << ", alter_version=" << start_resp.alter_version() << ", job_id=" << _job_id;
236
1
    sc_job->set_alter_version(start_resp.alter_version());
237
238
    // FIXME(cyx): Should trigger compaction on base_tablet if there are too many rowsets to convert.
239
240
    // Create a new tablet schema, should merge with dropped columns in light weight schema change
241
1
    _base_tablet_schema = std::make_shared<TabletSchema>();
242
1
    _base_tablet_schema->update_tablet_columns(*_base_tablet->tablet_schema(), request.columns);
243
1
    _new_tablet_schema = _new_tablet->tablet_schema();
244
245
1
    std::vector<ColumnId> return_columns;
246
1
    return_columns.resize(_base_tablet_schema->num_columns());
247
1
    std::iota(return_columns.begin(), return_columns.end(), 0);
248
249
    // delete handlers to filter out deleted rows
250
1
    DeleteHandler delete_handler;
251
1
    std::vector<RowsetMetaSharedPtr> delete_predicates;
252
1
    for (auto& split : rs_splits) {
253
1
        auto& rs_meta = split.rs_reader->rowset()->rowset_meta();
254
1
        if (rs_meta->has_delete_predicate()) {
255
0
            _base_tablet_schema->merge_dropped_columns(*rs_meta->tablet_schema());
256
0
            delete_predicates.push_back(rs_meta);
257
0
        }
258
1
    }
259
1
    RETURN_IF_ERROR(delete_handler.init(_base_tablet_schema, delete_predicates,
260
1
                                        start_resp.alter_version()));
261
262
    // reader_context is stack variables, it's lifetime MUST keep the same with rs_readers
263
1
    RowsetReaderContext reader_context;
264
1
    reader_context.reader_type = ReaderType::READER_ALTER_TABLE;
265
1
    reader_context.tablet_schema = _base_tablet_schema;
266
1
    reader_context.need_ordered_result = true;
267
1
    reader_context.delete_handler = &delete_handler;
268
1
    reader_context.return_columns = &return_columns;
269
1
    reader_context.sequence_id_idx = reader_context.tablet_schema->sequence_col_idx();
270
1
    reader_context.is_unique = _base_tablet->keys_type() == UNIQUE_KEYS;
271
1
    reader_context.batch_size = ALTER_TABLE_BATCH_SIZE;
272
1
    reader_context.delete_bitmap = _base_tablet->tablet_meta()->delete_bitmap_ptr();
273
1
    reader_context.version = Version(0, start_resp.alter_version());
274
1
    std::vector<uint32_t> cluster_key_idxes;
275
1
    if (!_base_tablet_schema->cluster_key_uids().empty()) {
276
0
        for (const auto& uid : _base_tablet_schema->cluster_key_uids()) {
277
0
            cluster_key_idxes.emplace_back(_base_tablet_schema->field_index(uid));
278
0
        }
279
0
        reader_context.read_orderby_key_columns = &cluster_key_idxes;
280
0
        reader_context.is_unique = false;
281
0
        reader_context.sequence_id_idx = -1;
282
0
    }
283
284
1
    for (auto& split : rs_splits) {
285
1
        RETURN_IF_ERROR(split.rs_reader->init(&reader_context));
286
1
    }
287
288
1
    SchemaChangeParams sc_params;
289
290
    // cache schema change output to file cache
291
1
    std::vector<RowsetSharedPtr> rowsets;
292
1
    rowsets.resize(rs_splits.size());
293
1
    std::transform(rs_splits.begin(), rs_splits.end(), rowsets.begin(),
294
1
                   [](RowSetSplits& split) { return split.rs_reader->rowset(); });
295
1
    sc_params.output_to_file_cache = _should_cache_sc_output(rowsets);
296
1
    if (request.__isset.query_globals && request.__isset.query_options) {
297
0
        sc_params.runtime_state =
298
0
                std::make_shared<RuntimeState>(request.query_options, request.query_globals);
299
1
    } else {
300
        // for old version request compatibility
301
1
        sc_params.runtime_state = std::make_shared<RuntimeState>();
302
1
    }
303
304
1
    RETURN_IF_ERROR(DescriptorTbl::create(&sc_params.pool, request.desc_tbl, &sc_params.desc_tbl));
305
1
    sc_params.ref_rowset_readers.reserve(rs_splits.size());
306
1
    for (RowSetSplits& split : rs_splits) {
307
1
        sc_params.ref_rowset_readers.emplace_back(std::move(split.rs_reader));
308
1
    }
309
1
    sc_params.delete_handler = &delete_handler;
310
1
    sc_params.be_exec_version = request.be_exec_version;
311
1
    DCHECK(request.__isset.alter_tablet_type);
312
1
    switch (request.alter_tablet_type) {
313
1
    case TAlterTabletType::SCHEMA_CHANGE:
314
1
        sc_params.alter_tablet_type = AlterTabletType::SCHEMA_CHANGE;
315
1
        break;
316
0
    case TAlterTabletType::ROLLUP:
317
0
        sc_params.alter_tablet_type = AlterTabletType::ROLLUP;
318
0
        break;
319
0
    case TAlterTabletType::MIGRATION:
320
0
        sc_params.alter_tablet_type = AlterTabletType::MIGRATION;
321
0
        break;
322
1
    }
323
1
    sc_params.vault_id = request.storage_vault_id;
324
1
    if (!request.__isset.materialized_view_params) {
325
1
        return _convert_historical_rowsets(sc_params, job);
326
1
    }
327
0
    for (auto item : request.materialized_view_params) {
328
0
        AlterMaterializedViewParam mv_param;
329
0
        mv_param.column_name = item.column_name;
330
        /*
331
         * origin_column_name is always be set now,
332
         * but origin_column_name may be not set in some materialized view function. eg:count(1)
333
        */
334
0
        if (item.__isset.origin_column_name) {
335
0
            mv_param.origin_column_name = item.origin_column_name;
336
0
        }
337
338
0
        if (item.__isset.mv_expr) {
339
0
            mv_param.expr = std::make_shared<TExpr>(item.mv_expr);
340
0
        }
341
0
        sc_params.materialized_params_map.insert(
342
0
                std::make_pair(to_lower(item.column_name), mv_param));
343
0
    }
344
0
    sc_params.enable_unique_key_merge_on_write = _new_tablet->enable_unique_key_merge_on_write();
345
0
    return _convert_historical_rowsets(sc_params, job);
346
1
}
347
348
Status CloudSchemaChangeJob::_convert_historical_rowsets(const SchemaChangeParams& sc_params,
349
1
                                                         cloud::TabletJobInfoPB& job) {
350
1
    LOG(INFO) << "Begin to convert historical rowsets for new_tablet from base_tablet. base_tablet="
351
1
              << _base_tablet->tablet_id() << ", new_tablet=" << _new_tablet->tablet_id()
352
1
              << ", job_id=" << _job_id;
353
354
    // Add filter information in change, and filter column information will be set in _parse_request
355
    // And filter some data every time the row block changes
356
1
    BlockChanger changer(_new_tablet->tablet_schema(), *sc_params.desc_tbl,
357
1
                         sc_params.runtime_state);
358
359
1
    bool sc_sorting = false;
360
1
    bool sc_directly = false;
361
362
    // 1. Parse the Alter request and convert it into an internal representation
363
1
    RETURN_IF_ERROR(SchemaChangeJob::parse_request(sc_params, _base_tablet_schema.get(),
364
1
                                                   _new_tablet_schema.get(), &changer, &sc_sorting,
365
1
                                                   &sc_directly));
366
1
    if (!sc_sorting && !sc_directly && sc_params.alter_tablet_type == AlterTabletType::ROLLUP) {
367
0
        LOG(INFO) << "Don't support to add materialized view by linked schema change";
368
0
        return Status::InternalError(
369
0
                "Don't support to add materialized view by linked schema change");
370
0
    }
371
372
1
    LOG(INFO) << "schema change type, sc_sorting: " << sc_sorting
373
1
              << ", sc_directly: " << sc_directly << ", base_tablet=" << _base_tablet->tablet_id()
374
1
              << ", new_tablet=" << _new_tablet->tablet_id();
375
376
    // 2. Generate historical data converter
377
1
    auto sc_procedure = get_sc_procedure(
378
1
            changer, sc_sorting,
379
1
            _cloud_storage_engine.memory_limitation_bytes_per_thread_for_schema_change());
380
381
1
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::_convert_historical_rowsets.block", DBUG_BLOCK);
382
383
    // 3. Convert historical data
384
1
    bool already_exist_any_version = false;
385
1
    for (const auto& rs_reader : sc_params.ref_rowset_readers) {
386
1
        VLOG_TRACE << "Begin to convert a history rowset. version=" << rs_reader->version();
387
388
1
        RowsetWriterContext context;
389
1
        context.txn_id = rs_reader->rowset()->txn_id();
390
1
        context.txn_expiration = _expiration;
391
1
        context.version = rs_reader->version();
392
1
        context.rowset_state = VISIBLE;
393
1
        context.segments_overlap = rs_reader->rowset()->rowset_meta()->segments_overlap();
394
1
        context.tablet_schema = _new_tablet->tablet_schema();
395
1
        context.newest_write_timestamp = rs_reader->newest_write_timestamp();
396
1
        context.storage_resource = _cloud_storage_engine.get_storage_resource(sc_params.vault_id);
397
1
        context.job_id = _job_id;
398
1
        context.write_file_cache = sc_params.output_to_file_cache;
399
1
        context.tablet = _new_tablet;
400
1
        if (!context.storage_resource) {
401
0
            return Status::InternalError("vault id not found, maybe not sync, vault id {}",
402
0
                                         sc_params.vault_id);
403
0
        }
404
405
1
        context.write_type = DataWriteType::TYPE_SCHEMA_CHANGE;
406
        // TODO if support VerticalSegmentWriter, also need to handle cluster key primary key index
407
1
        bool vertical = false;
408
1
        if (sc_sorting && !_new_tablet->tablet_schema()->cluster_key_uids().empty()) {
409
            // see VBaseSchemaChangeWithSorting::_external_sorting
410
0
            vertical = true;
411
0
        }
412
1
        auto rowset_writer = DORIS_TRY(_new_tablet->create_rowset_writer(context, vertical));
413
414
1
        RowsetMetaSharedPtr existed_rs_meta;
415
1
        auto st = _cloud_storage_engine.meta_mgr().prepare_rowset(
416
1
                *rowset_writer->rowset_meta(), _job_id, _new_tablet->table_id(), &existed_rs_meta);
417
1
        if (!st.ok()) {
418
0
            if (st.is<ALREADY_EXIST>()) {
419
0
                LOG(INFO) << "Rowset " << rs_reader->version() << " has already existed in tablet "
420
0
                          << _new_tablet->tablet_id();
421
                // Add already committed rowset to _output_rowsets.
422
0
                DCHECK(existed_rs_meta != nullptr);
423
0
                RowsetSharedPtr rowset;
424
                // schema is nullptr implies using RowsetMeta.tablet_schema
425
0
                RETURN_IF_ERROR(
426
0
                        RowsetFactory::create_rowset(nullptr, "", existed_rs_meta, &rowset));
427
0
                _output_rowsets.push_back(std::move(rowset));
428
0
                already_exist_any_version = true;
429
0
                continue;
430
0
            } else {
431
0
                return st;
432
0
            }
433
0
        }
434
435
1
        st = sc_procedure->process(rs_reader, rowset_writer.get(), _new_tablet, _base_tablet,
436
1
                                   _base_tablet_schema, _new_tablet_schema);
437
1
        if (!st.ok()) {
438
0
            return Status::InternalError(
439
0
                    "failed to process schema change on rowset, version=[{}-{}], status={}",
440
0
                    rs_reader->version().first, rs_reader->version().second, st.to_string());
441
0
        }
442
443
1
        RowsetSharedPtr new_rowset;
444
1
        st = rowset_writer->build(new_rowset);
445
1
        if (!st.ok()) {
446
0
            return Status::InternalError("failed to build rowset, version=[{}-{}] status={}",
447
0
                                         rs_reader->version().first, rs_reader->version().second,
448
0
                                         st.to_string());
449
0
        }
450
451
1
        st = _cloud_storage_engine.meta_mgr().commit_rowset(
452
1
                *rowset_writer->rowset_meta(), _job_id, _new_tablet->table_id(), &existed_rs_meta);
453
1
        if (!st.ok()) {
454
0
            if (st.is<ALREADY_EXIST>()) {
455
0
                LOG(INFO) << "Rowset " << rs_reader->version() << " has already existed in tablet "
456
0
                          << _new_tablet->tablet_id();
457
                // Add already committed rowset to _output_rowsets.
458
0
                DCHECK(existed_rs_meta != nullptr);
459
0
                RowsetSharedPtr rowset;
460
                // schema is nullptr implies using RowsetMeta.tablet_schema
461
0
                RETURN_IF_ERROR(
462
0
                        RowsetFactory::create_rowset(nullptr, "", existed_rs_meta, &rowset));
463
0
                _output_rowsets.push_back(std::move(rowset));
464
0
                continue;
465
0
            } else {
466
0
                return st;
467
0
            }
468
0
        }
469
1
        _output_rowsets.push_back(std::move(new_rowset));
470
471
1
        VLOG_TRACE << "Successfully convert a history version " << rs_reader->version();
472
1
    }
473
1
    auto* sc_job = job.mutable_schema_change();
474
1
    if (!sc_params.ref_rowset_readers.empty()) {
475
1
        int64_t num_output_rows = 0;
476
1
        int64_t size_output_rowsets = 0;
477
1
        int64_t num_output_segments = 0;
478
1
        int64_t index_size_output_rowsets = 0;
479
1
        int64_t segment_size_output_rowsets = 0;
480
1
        for (auto& rs : _output_rowsets) {
481
1
            sc_job->add_txn_ids(rs->txn_id());
482
1
            sc_job->add_output_versions(rs->end_version());
483
1
            num_output_rows += rs->num_rows();
484
1
            size_output_rowsets += rs->total_disk_size();
485
1
            num_output_segments += rs->num_segments();
486
1
            index_size_output_rowsets += rs->index_disk_size();
487
1
            segment_size_output_rowsets += rs->data_disk_size();
488
1
        }
489
1
        sc_job->set_num_output_rows(num_output_rows);
490
1
        sc_job->set_size_output_rowsets(size_output_rowsets);
491
1
        sc_job->set_num_output_segments(num_output_segments);
492
1
        sc_job->set_num_output_rowsets(_output_rowsets.size());
493
1
        sc_job->set_index_size_output_rowsets(index_size_output_rowsets);
494
1
        sc_job->set_segment_size_output_rowsets(segment_size_output_rowsets);
495
1
    }
496
1
    _output_cumulative_point = std::min(_output_cumulative_point, sc_job->alter_version() + 1);
497
1
    sc_job->set_output_cumulative_point(_output_cumulative_point);
498
499
1
    DBUG_EXECUTE_IF("CloudSchemaChangeJob.process_alter_tablet.sleep", DBUG_BLOCK);
500
    // process delete bitmap if the table is MOW
501
1
    bool has_stop_token {false};
502
1
    bool should_clear_stop_token {true};
503
1
    Defer defer {[&]() {
504
1
        if (has_stop_token) {
505
0
            static_cast<void>(_cloud_storage_engine.unregister_compaction_stop_token(
506
0
                    _new_tablet, should_clear_stop_token));
507
0
        }
508
1
    }};
509
1
    if (_new_tablet->enable_unique_key_merge_on_write()) {
510
0
        has_stop_token = true;
511
        // If there are historical versions of rowsets, we need to recalculate their delete
512
        // bitmaps, otherwise we will miss the delete bitmaps of incremental rowsets
513
0
        int64_t start_calc_delete_bitmap_version =
514
                // [0-1] is a placeholder rowset, start from 2.
515
0
                already_exist_any_version ? 2 : sc_job->alter_version() + 1;
516
0
        RETURN_IF_ERROR(_process_delete_bitmap(sc_job->alter_version(),
517
0
                                               start_calc_delete_bitmap_version, _initiator,
518
0
                                               sc_params.vault_id));
519
0
        sc_job->set_delete_bitmap_lock_initiator(_initiator);
520
0
    }
521
522
1
    cloud::FinishTabletJobResponse finish_resp;
523
1
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::_convert_historical_rowsets.test_conflict", {
524
1
        std::srand(static_cast<unsigned int>(std::time(nullptr)));
525
1
        int random_value = std::rand() % 100;
526
1
        if (random_value < 20) {
527
1
            return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR>("test txn conflict");
528
1
        }
529
1
    });
530
1
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::_convert_historical_rowsets.fail.before.commit_job", {
531
1
        LOG_INFO("inject retryable error before commit sc job, tablet={}",
532
1
                 _new_tablet->tablet_id());
533
1
        return Status::Error<ErrorCode::DELETE_BITMAP_LOCK_ERROR>("injected retryable error");
534
1
    });
535
1
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::_convert_historical_rowsets.before.commit_job",
536
1
                    DBUG_BLOCK);
537
1
    auto st = _cloud_storage_engine.meta_mgr().commit_tablet_job(job, &finish_resp);
538
1
    if (!st.ok()) {
539
0
        if (finish_resp.status().code() == cloud::JOB_ALREADY_SUCCESS) {
540
0
            st = _new_tablet->sync_rowsets();
541
0
            if (!st.ok()) {
542
0
                LOG_WARNING("failed to sync new tablet")
543
0
                        .tag("tablet_id", _new_tablet->tablet_id())
544
0
                        .error(st);
545
0
            }
546
0
            return Status::OK();
547
0
        }
548
0
        return st;
549
1
    } else {
550
1
        should_clear_stop_token = false;
551
1
    }
552
1
    const auto& stats = finish_resp.stats();
553
1
    {
554
        // to prevent the converted historical rowsets be replaced by rowsets written on new tablet
555
        // during double write phase by `CloudMetaMgr::sync_tablet_rowsets` in another thread
556
1
        std::unique_lock lock {_new_tablet->get_sync_meta_lock()};
557
1
        std::unique_lock wlock(_new_tablet->get_header_lock());
558
1
        _new_tablet->replace_rowsets_with_schema_change_output(
559
1
                _output_rowsets, sc_job->alter_version(), wlock, "commit", true);
560
        // Ensure the real new tablet has a continuous local version graph before it becomes
561
        // visible. Later RUNNING-tablet delete bitmap sync depends on capturing all old versions.
562
1
        RETURN_IF_ERROR(_cloud_storage_engine.meta_mgr().fill_version_holes(
563
1
                _new_tablet.get(), _new_tablet->max_version_unlocked(), wlock));
564
1
        _new_tablet->set_cumulative_layer_point(_output_cumulative_point);
565
1
        _new_tablet->reset_approximate_stats(stats.num_rowsets(), stats.num_segments(),
566
1
                                             stats.num_rows(), stats.data_size());
567
1
        RETURN_IF_ERROR(_new_tablet->set_tablet_state(TABLET_RUNNING));
568
1
    }
569
1
    return Status::OK();
570
1
}
571
572
Status CloudSchemaChangeJob::_process_delete_bitmap(int64_t alter_version,
573
                                                    int64_t start_calc_delete_bitmap_version,
574
                                                    int64_t initiator,
575
0
                                                    const std::string& vault_id) {
576
0
    LOG_INFO("process mow table")
577
0
            .tag("new_tablet_id", _new_tablet->tablet_id())
578
0
            .tag("out_rowset_size", _output_rowsets.size())
579
0
            .tag("start_calc_delete_bitmap_version", start_calc_delete_bitmap_version)
580
0
            .tag("alter_version", alter_version);
581
0
    RETURN_IF_ERROR(_cloud_storage_engine.register_compaction_stop_token(_new_tablet, initiator));
582
0
    TabletMetaSharedPtr tmp_meta = std::make_shared<TabletMeta>(*(_new_tablet->tablet_meta()));
583
0
    tmp_meta->delete_bitmap().delete_bitmap.clear();
584
    // Keep only version [0-1] rowset, other rowsets will be added in _output_rowsets
585
0
    auto& rs_metas = tmp_meta->all_mutable_rs_metas();
586
0
    for (auto it = rs_metas.begin(); it != rs_metas.end();) {
587
0
        const auto& rs_meta = it->second;
588
0
        if (rs_meta->version().first == 0 && rs_meta->version().second == 1) {
589
0
            ++it;
590
0
        } else {
591
0
            it = rs_metas.erase(it);
592
0
        }
593
0
    }
594
595
0
    std::shared_ptr<CloudTablet> tmp_tablet =
596
0
            std::make_shared<CloudTablet>(_cloud_storage_engine, tmp_meta);
597
0
    {
598
0
        std::unique_lock wlock(tmp_tablet->get_header_lock());
599
0
        tmp_tablet->add_rowsets(_output_rowsets, true, wlock, false);
600
        // Set alter version to let the tmp_tablet can fill hole rowset greater than alter_version
601
0
        tmp_tablet->set_alter_version(alter_version);
602
0
    }
603
604
    // step 1, process incremental rowset without delete bitmap update lock
605
0
    RETURN_IF_ERROR(_cloud_storage_engine.meta_mgr().sync_tablet_rowsets(tmp_tablet.get()));
606
0
    {
607
0
        std::unique_lock wlock(tmp_tablet->get_header_lock());
608
0
        tmp_tablet->replace_rowsets_with_schema_change_output(_output_rowsets, alter_version, wlock,
609
0
                                                              "delete_bitmap_without_lock", false);
610
0
    }
611
0
    int64_t max_version = tmp_tablet->max_version().second;
612
0
    LOG(INFO) << "alter table for mow table, calculate delete bitmap of "
613
0
              << "incremental rowsets without lock, version: " << start_calc_delete_bitmap_version
614
0
              << "-" << max_version << " new_table_id: " << _new_tablet->tablet_id();
615
0
    if (max_version >= start_calc_delete_bitmap_version) {
616
0
        auto ret = DORIS_TRY(tmp_tablet->capture_consistent_rowsets_unlocked(
617
0
                {start_calc_delete_bitmap_version, max_version}, CaptureRowsetOps {}));
618
0
        DBUG_EXECUTE_IF("CloudSchemaChangeJob::_process_delete_bitmap.after.capture_without_lock",
619
0
                        DBUG_BLOCK);
620
0
        for (auto rowset : ret.rowsets) {
621
0
            RETURN_IF_ERROR(CloudTablet::update_delete_bitmap_without_lock(tmp_tablet, rowset));
622
0
        }
623
0
    }
624
625
0
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::_process_delete_bitmap.before_new_inc.block",
626
0
                    DBUG_BLOCK);
627
628
    // step 2, process incremental rowset with delete bitmap update lock
629
0
    RETURN_IF_ERROR(_cloud_storage_engine.meta_mgr().get_delete_bitmap_update_lock(
630
0
            *_new_tablet, SCHEMA_CHANGE_DELETE_BITMAP_LOCK_ID, initiator));
631
0
    RETURN_IF_ERROR(_cloud_storage_engine.meta_mgr().sync_tablet_rowsets(tmp_tablet.get()));
632
0
    {
633
0
        std::unique_lock wlock(tmp_tablet->get_header_lock());
634
0
        tmp_tablet->replace_rowsets_with_schema_change_output(_output_rowsets, alter_version, wlock,
635
0
                                                              "delete_bitmap_with_lock", false);
636
0
    }
637
0
    int64_t new_max_version = tmp_tablet->max_version().second;
638
0
    LOG(INFO) << "alter table for mow table, calculate delete bitmap of "
639
0
              << "incremental rowsets with lock, version: " << max_version + 1 << "-"
640
0
              << new_max_version << " new_tablet_id: " << _new_tablet->tablet_id();
641
0
    if (new_max_version > max_version) {
642
0
        auto ret = DORIS_TRY(tmp_tablet->capture_consistent_rowsets_unlocked(
643
0
                {max_version + 1, new_max_version}, CaptureRowsetOps {}));
644
0
        for (auto rowset : ret.rowsets) {
645
0
            RETURN_IF_ERROR(CloudTablet::update_delete_bitmap_without_lock(tmp_tablet, rowset));
646
0
        }
647
0
    }
648
649
0
    DBUG_EXECUTE_IF("CloudSchemaChangeJob::_process_delete_bitmap.inject_sleep", {
650
0
        auto p = dp->param("percent", 0.01);
651
0
        auto sleep_time = dp->param("sleep", 100);
652
0
        std::mt19937 gen {std::random_device {}()};
653
0
        std::bernoulli_distribution inject_fault {p};
654
0
        if (inject_fault(gen)) {
655
0
            LOG_INFO("injection sleep for {} seconds, tablet_id={}, sc job_id={}", sleep_time,
656
0
                     _new_tablet->tablet_id(), _job_id);
657
0
            std::this_thread::sleep_for(std::chrono::seconds(sleep_time));
658
0
        }
659
0
    });
660
661
0
    auto& delete_bitmap = tmp_tablet->tablet_meta()->delete_bitmap();
662
0
    auto storage_resource = _cloud_storage_engine.get_storage_resource(vault_id);
663
    // step4, store delete bitmap
664
0
    RETURN_IF_ERROR(_cloud_storage_engine.meta_mgr().update_delete_bitmap(
665
0
            *_new_tablet, SCHEMA_CHANGE_DELETE_BITMAP_LOCK_ID, initiator, &delete_bitmap,
666
0
            &delete_bitmap, "", storage_resource, config::delete_bitmap_store_write_version,
667
0
            _new_tablet->table_id()));
668
669
0
    _new_tablet->tablet_meta()->delete_bitmap() = delete_bitmap;
670
0
    return Status::OK();
671
0
}
672
673
0
void CloudSchemaChangeJob::clean_up_on_failure() {
674
0
    if (_new_tablet == nullptr) {
675
0
        return;
676
0
    }
677
0
    if (_new_tablet->keys_type() == KeysType::UNIQUE_KEYS &&
678
0
        _new_tablet->enable_unique_key_merge_on_write()) {
679
0
        _cloud_storage_engine.meta_mgr().remove_delete_bitmap_update_lock(
680
0
                _new_tablet->table_id(), SCHEMA_CHANGE_DELETE_BITMAP_LOCK_ID, _initiator,
681
0
                _new_tablet->tablet_id());
682
0
    }
683
0
    for (const auto& output_rs : _output_rowsets) {
684
0
        if (output_rs.use_count() > 2) {
685
0
            LOG(WARNING) << "Rowset " << output_rs->rowset_id().to_string() << " has "
686
0
                         << output_rs.use_count()
687
0
                         << " references. File Cache won't be recycled when query is using it.";
688
0
            return;
689
0
        }
690
0
        output_rs->clear_cache();
691
0
    }
692
0
}
693
694
bool CloudSchemaChangeJob::_should_cache_sc_output(
695
1
        const std::vector<RowsetSharedPtr>& input_rowsets) {
696
1
    int64_t total_size = 0;
697
1
    int64_t cached_index_size = 0;
698
1
    int64_t cached_data_size = 0;
699
700
1
    for (const auto& rs : input_rowsets) {
701
1
        const RowsetMetaSharedPtr& rs_meta = rs->rowset_meta();
702
1
        total_size += rs_meta->total_disk_size();
703
1
        cached_index_size += rs->approximate_cache_index_size();
704
1
        cached_data_size += rs->approximate_cached_data_size();
705
1
    }
706
707
1
    double input_hit_rate = static_cast<double>(cached_index_size + cached_data_size) / total_size;
708
709
1
    LOG(INFO) << "CloudSchemaChangeJob check cache sc output strategy. "
710
1
              << "job_id=" << _job_id << ", input_rowsets_count=" << input_rowsets.size()
711
1
              << ", total_size=" << total_size << ", cached_index_size=" << cached_index_size
712
1
              << ", cached_data_size=" << cached_data_size << ", input_hit_rate=" << input_hit_rate
713
1
              << ", min_hit_ratio_threshold="
714
1
              << config::file_cache_keep_schema_change_output_min_hit_ratio << ", should_cache="
715
1
              << (input_hit_rate > config::file_cache_keep_schema_change_output_min_hit_ratio);
716
717
1
    if (input_hit_rate > config::file_cache_keep_schema_change_output_min_hit_ratio) {
718
0
        return true;
719
0
    }
720
721
1
    return false;
722
1
}
723
724
} // namespace doris