Coverage Report

Created: 2026-06-11 15:14

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