This is an automated email from the ASF dual-hosted git repository.
Yukang-Lian pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new 3a29606ed56 [fix](cloud) Remove intermediate rowsets of sorting schema
change from file cache path (#69134)
3a29606ed56 is described below
commit 3a29606ed564d61714cb0f2dbe5dc8ea8d8a8102
Author: Jamie <[email protected]>
AuthorDate: Thu Nov 26 11:50:10 2026 +0800
[fix](cloud) Remove intermediate rowsets of sorting schema change from file
cache path (#69134)
### What problem does this PR solve?
Issue Number: None
Related PR: None
Problem Summary:
In cloud mode, a schema change that has to sort data (e.g. adding a
rollup or a sync materialized view whose key columns are in a different
order) writes the intermediate rowsets of internal sorting to a local
path. These rowsets have no storage resource, so
`CloudRowsetWriter::init` puts them in the root of a file cache path as
`<rowset_id>_<segment_id>.dat`. Every input rowset with data produces at
least one intermediate rowset, so each such schema change writes a full
copy of the converted data there.
Only the local mode subclass `VLocalSchemaChangeWithSorting` removes the
intermediate rowsets. Cloud mode uses `VBaseSchemaChangeWithSorting`
directly, which never removes them, whether the schema change succeeds
or fails. These files are not part of the file cache: cache eviction and
`clear_file_cache` API do not see them, and the cache loader skips
regular files in the cache root on restart. They pile up on the cache
disk until it is full, the file cache then evicts its own data and
cannot admit new blocks, and reads fall back to remote storage. We
observed hundreds of GB of such files on a cluster which created sync
materialized views repeatedly.
This PR:
- Adds `VCloudSchemaChangeWithSorting`, used by cloud schema change,
which removes the intermediate rowsets after each input rowset is
processed, whether it succeeds or fails (like
`VLocalSchemaChangeWithSorting` does in local mode).
- Removes the local rowset files left in file cache paths by previous BE
processes (e.g. BE crashed during schema change) when
`CloudStorageEngine` opens. A rowset id embeds the backend uid of the
process that generated it, which is regenerated on every start, so only
files from previous processes are removed and files written by the
current process are never touched. Only regular files whose names match
the local rowset file format are considered.
- Adds a debug point
`VBaseSchemaChangeWithSorting._inner_process.before_external_sorting` to
inject a failure in tests.
### Release note
Fix the intermediate rowsets of schema change with sorting being left in
the file cache path in cloud mode, which could fill up the cache disk.
### Check List (For Author)
- Test <!-- At least one of them must be included. -->
- [x] Regression test
- [x] Unit Test
- [ ] Manual test (add detailed scripts or steps below)
- [ ] No need to test or manual test. Explain why:
- [ ] This is a refactor/code format and no logic has been changed.
- [ ] Previous test can cover this change.
- [ ] No code files have been changed.
- [ ] Other reason <!-- Add your reason? -->
Unit tests (`CloudSchemaChangeSortingTest`) run a real sorting schema
change in cloud mode and check the file cache root after success and
after an injected failure, and cover the startup cleanup of stale rowset
files. Without the cleanup, the success and failure cases fail with the
intermediate rowsets left in the cache root.
The docker regression test `test_cloud_sc_sorting_tmp_rowset_cleanup`
covers a rollup that reorders keys, a failed rollup, and BE restart with
stale rowset files in the cache root. On the code before this PR it
fails at the first step (`expected: <0> but was: <5>`, one leftover
intermediate rowset per loaded rowset).
- Behavior changed:
- [ ] No.
- [x] Yes. <!-- Explain the behavior change -->
In cloud mode, intermediate rowsets of schema change with sorting are
removed after use, and stale ones in file cache paths are removed when
BE starts.
---
be/src/cloud/cloud_rowset_writer.cpp | 60 ++++
be/src/cloud/cloud_rowset_writer.h | 7 +
be/src/cloud/cloud_schema_change_job.cpp | 20 +-
be/src/cloud/cloud_schema_change_job.h | 14 +
be/src/cloud/cloud_storage_engine.cpp | 7 +
be/src/storage/schema_change/schema_change.cpp | 3 +
be/test/cloud/cloud_schema_change_sorting_test.cpp | 370 +++++++++++++++++++++
...test_cloud_sc_sorting_tmp_rowset_cleanup.groovy | 125 +++++++
8 files changed, 605 insertions(+), 1 deletion(-)
diff --git a/be/src/cloud/cloud_rowset_writer.cpp
b/be/src/cloud/cloud_rowset_writer.cpp
index af447147b36..576a433e429 100644
--- a/be/src/cloud/cloud_rowset_writer.cpp
+++ b/be/src/cloud/cloud_rowset_writer.cpp
@@ -17,6 +17,11 @@
#include "cloud/cloud_rowset_writer.h"
+#include <algorithm>
+#include <cctype>
+#include <filesystem>
+#include <string_view>
+
#include "common/logging.h"
#include "common/status.h"
#include "io/cache/block_file_cache_factory.h"
@@ -233,4 +238,59 @@ Status
CloudRowsetWriter::_collect_packed_slice_location(io::FileWriter* file_wr
return Status::OK();
}
+// Files of a local rowset are `<rowset_id>_<segment_id>.dat` and inverted
index files
+// `<rowset_id>_<segment_id>.idx` (V2) or
`<rowset_id>_<segment_id>_<index_id>[@suffix].idx` (V1),
+// where `rowset_id` is a 48 hex string starting with version "02".
+static bool is_local_rowset_file(std::string_view name) {
+ constexpr size_t rowset_id_len = 48;
+ if (name.size() <= rowset_id_len + 1 || name[rowset_id_len] != '_' ||
!name.starts_with("02")) {
+ return false;
+ }
+ if (!name.ends_with(".dat") && !name.ends_with(".idx")) {
+ return false;
+ }
+ return std::all_of(name.begin(), name.begin() + rowset_id_len,
+ [](char c) { return std::isxdigit(static_cast<unsigned
char>(c)); });
+}
+
+size_t CloudRowsetWriter::remove_stale_local_rowset_files(const std::string&
dir,
+ const UniqueId&
backend_uid) {
+ // The last 32 hex characters of a rowset id come from the backend uid of
the BE process
+ // which generated it, see `UniqueRowsetIdGenerator::next_id`.
+ RowsetId current_rowset_id;
+ current_rowset_id.init(2, 0, backend_uid.hi, backend_uid.lo);
+ const std::string current_uid = current_rowset_id.to_string().substr(16);
+
+ size_t num_removed = 0;
+ uint64_t removed_bytes = 0;
+ std::error_code ec;
+ std::filesystem::directory_iterator it {dir, ec};
+ for (; !ec && it != std::filesystem::directory_iterator();
it.increment(ec)) {
+ const std::string name = it->path().filename().native();
+ std::error_code file_ec;
+ if (!it->is_regular_file(file_ec) || !is_local_rowset_file(name) ||
+ name.compare(16, 32, current_uid) == 0) {
+ continue;
+ }
+ auto size = it->file_size(file_ec);
+ if (file_ec) {
+ size = 0;
+ }
+ if (std::filesystem::remove(it->path(), file_ec)) {
+ ++num_removed;
+ removed_bytes += size;
+ } else {
+ LOG(WARNING) << "failed to remove stale local rowset file " <<
it->path().native()
+ << ", err=" << file_ec.message();
+ }
+ }
+ if (ec) {
+ LOG(WARNING) << "failed to list stale local rowset files in " << dir
+ << ", err=" << ec.message();
+ }
+ LOG(INFO) << "removed " << num_removed << " stale local rowset files in "
<< dir
+ << ", bytes=" << removed_bytes;
+ return num_removed;
+}
+
} // namespace doris
diff --git a/be/src/cloud/cloud_rowset_writer.h
b/be/src/cloud/cloud_rowset_writer.h
index 4841fbf6cf7..f736bd50623 100644
--- a/be/src/cloud/cloud_rowset_writer.h
+++ b/be/src/cloud/cloud_rowset_writer.h
@@ -32,6 +32,13 @@ public:
Status build(RowsetSharedPtr& rowset) override;
+ // Local rowsets (intermediate rowsets of sorting schema change) are
written to the root of
+ // file cache paths. Remove the files of local rowsets left in `dir` by
previous BE processes,
+ // i.e. whose rowset ids are not generated with `backend_uid`. Returns the
number of removed
+ // files.
+ static size_t remove_stale_local_rowset_files(const std::string& dir,
+ const UniqueId& backend_uid);
+
private:
Status _build_rowset_meta(RowsetMeta* rowset_meta, bool check_segment_num
= false,
std::vector<int64_t>* completed_segment_ids =
nullptr) override;
diff --git a/be/src/cloud/cloud_schema_change_job.cpp
b/be/src/cloud/cloud_schema_change_job.cpp
index a926d60b40c..d35ef7ed1f2 100644
--- a/be/src/cloud/cloud_schema_change_job.cpp
+++ b/be/src/cloud/cloud_schema_change_job.cpp
@@ -54,12 +54,30 @@ static constexpr int SCHEMA_CHANGE_DELETE_BITMAP_LOCK_ID =
-2;
std::unique_ptr<SchemaChange> get_sc_procedure(const BlockChanger& changer,
bool sc_sorting,
int64_t mem_limit) {
if (sc_sorting) {
- return std::make_unique<VBaseSchemaChangeWithSorting>(changer,
mem_limit);
+ return std::make_unique<VCloudSchemaChangeWithSorting>(changer,
mem_limit);
}
// else sc_directly
return std::make_unique<VSchemaChangeDirectly>(changer);
}
+Status VCloudSchemaChangeWithSorting::_inner_process(RowsetReaderSharedPtr
rowset_reader,
+ RowsetWriter*
rowset_writer,
+ BaseTabletSPtr new_tablet,
+ TabletSchemaSPtr
base_tablet_schema,
+ TabletSchemaSPtr
new_tablet_schema) {
+ Defer defer {[&]() {
+ // remove the intermediate rowsets generated by internal sorting
+ for (auto& rowset : _src_rowsets) {
+ WARN_IF_ERROR(rowset->remove(),
+ fmt::format("failed to remove intermediate rowset {}
of schema change",
+ rowset->rowset_id().to_string()));
+ }
+ _src_rowsets.clear();
+ }};
+ return VBaseSchemaChangeWithSorting::_inner_process(rowset_reader,
rowset_writer, new_tablet,
+ base_tablet_schema,
new_tablet_schema);
+}
+
CloudSchemaChangeJob::CloudSchemaChangeJob(CloudStorageEngine&
cloud_storage_engine,
std::string job_id, int64_t
expiration)
: _cloud_storage_engine(cloud_storage_engine),
diff --git a/be/src/cloud/cloud_schema_change_job.h
b/be/src/cloud/cloud_schema_change_job.h
index 0f5b039c83b..5685fba360f 100644
--- a/be/src/cloud/cloud_schema_change_job.h
+++ b/be/src/cloud/cloud_schema_change_job.h
@@ -31,6 +31,20 @@ namespace cloud {
class TabletJobInfoPB;
}
+// Schema change with sorting in cloud mode. The intermediate rowsets
generated by internal
+// sorting are written to a local file cache path (see
`CloudRowsetWriter::init`) and nothing
+// else tracks them, so they are removed once each input rowset is processed,
whether it
+// succeeds or fails.
+class VCloudSchemaChangeWithSorting final : public
VBaseSchemaChangeWithSorting {
+public:
+ using VBaseSchemaChangeWithSorting::VBaseSchemaChangeWithSorting;
+ ~VCloudSchemaChangeWithSorting() override = default;
+
+ Status _inner_process(RowsetReaderSharedPtr rowset_reader, RowsetWriter*
rowset_writer,
+ BaseTabletSPtr new_tablet, TabletSchemaSPtr
base_tablet_schema,
+ TabletSchemaSPtr new_tablet_schema) override;
+};
+
class CloudSchemaChangeJob {
public:
CloudSchemaChangeJob(CloudStorageEngine& cloud_storage_engine, std::string
job_id,
diff --git a/be/src/cloud/cloud_storage_engine.cpp
b/be/src/cloud/cloud_storage_engine.cpp
index 63143b05d77..8d911037989 100644
--- a/be/src/cloud/cloud_storage_engine.cpp
+++ b/be/src/cloud/cloud_storage_engine.cpp
@@ -39,6 +39,7 @@
#include "cloud/cloud_full_compaction.h"
#include "cloud/cloud_index_change_compaction.h"
#include "cloud/cloud_meta_mgr.h"
+#include "cloud/cloud_rowset_writer.h"
#include "cloud/cloud_snapshot_mgr.h"
#include "cloud/cloud_tablet_hotspot.h"
#include "cloud/cloud_tablet_mgr.h"
@@ -204,6 +205,12 @@ struct RefreshFSVaultVisitor {
Status CloudStorageEngine::open() {
sync_storage_vault();
+ // Intermediate rowsets of sorting schema change are written to file cache
paths, remove the
+ // ones left by previous BE processes, e.g. BE crashed during schema
change.
+ for (const auto& path :
io::FileCacheFactory::instance()->get_base_paths()) {
+ CloudRowsetWriter::remove_stale_local_rowset_files(path,
_options.backend_uid);
+ }
+
// TODO(plat1ko): DeleteBitmapTxnManager
_memtable_flush_executor = std::make_unique<MemTableFlushExecutor>();
diff --git a/be/src/storage/schema_change/schema_change.cpp
b/be/src/storage/schema_change/schema_change.cpp
index 90f83baf76d..69fcdd63aca 100644
--- a/be/src/storage/schema_change/schema_change.cpp
+++ b/be/src/storage/schema_change/schema_change.cpp
@@ -744,6 +744,9 @@ Status
VBaseSchemaChangeWithSorting::_inner_process(RowsetReaderSharedPtr rowset
RETURN_IF_ERROR(create_rowset());
+
DBUG_EXECUTE_IF("VBaseSchemaChangeWithSorting._inner_process.before_external_sorting",
+ { return Status::InternalError("debug point: fail before
external sorting"); });
+
if (_src_rowsets.empty()) {
RETURN_IF_ERROR(rowset_writer->flush());
} else {
diff --git a/be/test/cloud/cloud_schema_change_sorting_test.cpp
b/be/test/cloud/cloud_schema_change_sorting_test.cpp
new file mode 100644
index 00000000000..2ba00e607ed
--- /dev/null
+++ b/be/test/cloud/cloud_schema_change_sorting_test.cpp
@@ -0,0 +1,370 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include <gen_cpp/Descriptors_types.h>
+#include <gen_cpp/olap_file.pb.h>
+#include <gtest/gtest.h>
+
+#include <filesystem>
+#include <memory>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "agent/be_exec_version_manager.h"
+#include "cloud/cloud_rowset_writer.h"
+#include "cloud/cloud_schema_change_job.h"
+#include "cloud/cloud_storage_engine.h"
+#include "cloud/cloud_tablet.h"
+#include "common/config.h"
+#include "common/object_pool.h"
+#include "io/cache/block_file_cache_factory.h"
+#include "io/fs/local_file_system.h"
+#include "runtime/descriptors.h"
+#include "runtime/exec_env.h"
+#include "runtime/runtime_state.h"
+#include "storage/delete/delete_handler.h"
+#include "storage/rowset/rowset_reader.h"
+#include "storage/rowset/rowset_writer_context.h"
+#include "storage/schema.h"
+#include "storage/tablet/tablet_meta.h"
+#include "util/debug_points.h"
+#include "util/time.h"
+#include "util/uid_util.h"
+
+namespace doris {
+
+namespace {
+
+constexpr std::string_view kTestDir =
"./ut_dir/cloud_schema_change_sorting_test";
+constexpr int kNumRows = 200;
+
+void add_int_column(TabletSchemaPB* schema, int32_t unique_id, const
std::string& name,
+ bool is_key) {
+ auto* column = schema->add_column();
+ column->set_unique_id(unique_id);
+ column->set_name(name);
+ column->set_type("INT");
+ column->set_is_key(is_key);
+ column->set_length(4);
+ column->set_index_length(4);
+ column->set_is_nullable(false);
+ column->set_is_bf_column(false);
+ column->set_aggregation("NONE");
+}
+
+// Base schema is (k1, k2, v), the new schema reorders the keys to (k2, k1,
v), so the schema
+// change has to sort the data.
+TabletSchemaSPtr create_schema(bool reorder_keys) {
+ TabletSchemaPB schema_pb;
+ schema_pb.set_keys_type(KeysType::DUP_KEYS);
+ schema_pb.set_num_short_key_columns(2);
+ schema_pb.set_num_rows_per_row_block(1024);
+ schema_pb.set_compress_kind(COMPRESS_NONE);
+ schema_pb.set_next_column_unique_id(4);
+ if (reorder_keys) {
+ add_int_column(&schema_pb, 2, "k2", true);
+ add_int_column(&schema_pb, 1, "k1", true);
+ } else {
+ add_int_column(&schema_pb, 1, "k1", true);
+ add_int_column(&schema_pb, 2, "k2", true);
+ }
+ add_int_column(&schema_pb, 3, "v", false);
+ auto schema = std::make_shared<TabletSchema>();
+ schema->init_from_pb(schema_pb);
+ return schema;
+}
+
+// Rowset files in `dir`, grouped by rowset id.
+std::set<std::string> rowset_ids_of_files(const std::string& dir) {
+ std::set<std::string> rowset_ids;
+ for (const auto& entry : std::filesystem::directory_iterator(dir)) {
+ auto name = entry.path().filename().native();
+ if (entry.is_regular_file() && name != "version") {
+ rowset_ids.insert(name.substr(0, 48));
+ }
+ }
+ return rowset_ids;
+}
+
+} // namespace
+
+class CloudSchemaChangeSortingTest : public testing::Test {
+protected:
+ void SetUp() override {
+ _origin_enable_debug_points = config::enable_debug_points;
+ config::enable_debug_points = true;
+ // The TTL manager of file cache sleeps for these intervals, shorten
them so that the
+ // file cache can be destroyed quickly in TearDown.
+ _origin_ttl_gc_interval_ms =
config::file_cache_background_ttl_gc_interval_ms;
+ _origin_ttl_info_update_interval_ms =
+ config::file_cache_background_ttl_info_update_interval_ms;
+ config::file_cache_background_ttl_gc_interval_ms = 100;
+ config::file_cache_background_ttl_info_update_interval_ms = 100;
+
+ auto fs = io::global_local_filesystem();
+ ASSERT_TRUE(fs->delete_directory(std::string(kTestDir)).ok());
+ ASSERT_TRUE(fs->create_directory(std::string(kTestDir)).ok());
+ _cache_dir = std::filesystem::absolute(std::string(kTestDir) +
"/file_cache").string();
+
+ _origin_file_cache_factory =
ExecEnv::GetInstance()->file_cache_factory();
+ _file_cache_factory = std::make_unique<io::FileCacheFactory>();
+
ExecEnv::GetInstance()->set_file_cache_factory(_file_cache_factory.get());
+ io::FileCacheSettings settings;
+ settings.query_queue_size = 16 * 1024 * 1024;
+ settings.query_queue_elements = 16;
+ settings.index_queue_size = 16 * 1024 * 1024;
+ settings.index_queue_elements = 16;
+ settings.disposable_queue_size = 16 * 1024 * 1024;
+ settings.disposable_queue_elements = 16;
+ settings.capacity = 64 * 1024 * 1024;
+ settings.max_file_block_size = 1024 * 1024;
+ settings.max_query_cache_size = 0;
+
ASSERT_TRUE(io::FileCacheFactory::instance()->create_file_cache(_cache_dir,
settings).ok());
+
+ EngineOptions options;
+ options.backend_uid = UniqueId::gen_uid();
+ auto engine = std::make_unique<CloudStorageEngine>(options);
+ _engine = engine.get();
+ ExecEnv::GetInstance()->set_storage_engine(std::move(engine));
+
+ _base_schema = create_schema(false);
+ _new_schema = create_schema(true);
+ _base_tablet =
+ std::make_shared<CloudTablet>(*_engine,
std::make_shared<TabletMeta>(_base_schema));
+ _new_tablet =
+ std::make_shared<CloudTablet>(*_engine,
std::make_shared<TabletMeta>(_new_schema));
+
+ TDescriptorTable t_desc_tbl;
+ TTupleDescriptor t_tuple_desc;
+ t_tuple_desc.id = 0;
+ t_tuple_desc.byteSize = 0;
+ t_tuple_desc.numNullBytes = 0;
+ t_desc_tbl.tupleDescriptors.push_back(t_tuple_desc);
+ ASSERT_TRUE(DescriptorTbl::create(&_pool, t_desc_tbl,
&_desc_tbl).ok());
+ }
+
+ void TearDown() override {
+ DebugPoints::instance()->clear();
+ config::enable_debug_points = _origin_enable_debug_points;
+
+ _base_tablet.reset();
+ _new_tablet.reset();
+ _engine = nullptr;
+ ExecEnv::GetInstance()->set_storage_engine(nullptr);
+ _file_cache_factory.reset();
+
ExecEnv::GetInstance()->set_file_cache_factory(_origin_file_cache_factory);
+
static_cast<void>(io::global_local_filesystem()->delete_directory(std::string(kTestDir)));
+ config::file_cache_background_ttl_gc_interval_ms =
_origin_ttl_gc_interval_ms;
+ config::file_cache_background_ttl_info_update_interval_ms =
+ _origin_ttl_info_update_interval_ms;
+ }
+
+ // Writes a base rowset sorted by (k1, k2). As a local rowset it is
written to the root of
+ // the file cache path, like the intermediate rowsets.
+ RowsetSharedPtr write_base_rowset() {
+ RowsetWriterContext context;
+ context.version = Version(2, 2);
+ context.rowset_state = VISIBLE;
+ context.segments_overlap = NONOVERLAPPING;
+ context.tablet_schema = _base_schema;
+ context.newest_write_timestamp = UnixSeconds();
+ context.allow_packed_file = false;
+ auto writer_result = _base_tablet->create_rowset_writer(context,
false);
+ if (!writer_result.has_value()) {
+ ADD_FAILURE() << "failed to create rowset writer: " <<
writer_result.error();
+ return nullptr;
+ }
+ auto writer = std::move(writer_result).value();
+ auto block = _base_schema->create_storage_block();
+ auto columns = std::move(block).mutate_columns();
+ for (int32_t i = 0; i < kNumRows; ++i) {
+ int32_t k1 = i / 10;
+ int32_t k2 = i % 10;
+ columns[0]->insert_data(reinterpret_cast<const char*>(&k1),
sizeof(k1));
+ columns[1]->insert_data(reinterpret_cast<const char*>(&k2),
sizeof(k2));
+ columns[2]->insert_data(reinterpret_cast<const char*>(&i),
sizeof(i));
+ }
+ block.set_columns(std::move(columns));
+ RowsetSharedPtr rowset;
+ if (!writer->add_block(&block).ok() || !writer->flush().ok() ||
+ !writer->build(rowset).ok()) {
+ ADD_FAILURE() << "failed to write base rowset";
+ return nullptr;
+ }
+ return rowset;
+ }
+
+ // Runs schema change with sorting on `base_rowset`. Every block read is
turned into an
+ // intermediate rowset, so that there are many intermediate rowsets.
+ Status run_sorting_schema_change(SchemaChange* sc_procedure, const
RowsetSharedPtr& base_rowset,
+ RowsetSharedPtr* output_rowset) {
+ auto read_schema =
std::make_shared<ReadSchema>(_base_schema->columns());
+ RETURN_IF_ERROR(read_schema->init_from_tablet_schema(*_base_schema,
false, false));
+ DeleteHandler delete_handler;
+ std::vector<TabletColumn> dropped_columns;
+ RETURN_IF_ERROR(delete_handler.init({}, 2, read_schema,
&dropped_columns));
+
+ RowsetReaderContext reader_context;
+ reader_context.reader_type = ReaderType::READER_ALTER_TABLE;
+ reader_context.need_ordered_result = true;
+ reader_context.delete_handler = &delete_handler;
+ reader_context.read_schema = read_schema;
+ reader_context.batch_size = 16;
+ reader_context.version = Version(0, 2);
+ RowsetReaderSharedPtr reader;
+ RETURN_IF_ERROR(base_rowset->create_reader(&reader));
+ RETURN_IF_ERROR(reader->init(&reader_context));
+
+ RowsetWriterContext context;
+ context.version = Version(2, 2);
+ context.rowset_state = VISIBLE;
+ context.segments_overlap = OVERLAPPING;
+ context.tablet_schema = _new_schema;
+ context.newest_write_timestamp = UnixSeconds();
+ context.write_type = DataWriteType::TYPE_SCHEMA_CHANGE;
+ context.allow_packed_file = false;
+ auto writer = DORIS_TRY(_new_tablet->create_rowset_writer(context,
false));
+
+
DebugPoints::instance()->add("VBaseSchemaChangeWithSorting._inner_process.create_rowset");
+ RETURN_IF_ERROR(sc_procedure->process(reader, writer.get(),
_new_tablet, _base_tablet,
+ _base_schema, _new_schema));
+ return writer->build(*output_rowset);
+ }
+
+ std::unique_ptr<BlockChanger> create_changer() {
+ auto changer = std::make_unique<BlockChanger>(_new_schema, *_desc_tbl,
+
std::make_shared<RuntimeState>());
+ changer->set_type(AlterTabletType::SCHEMA_CHANGE);
+
changer->set_compatible_version(BeExecVersionManager::get_newest_version());
+ // new (k2, k1, v) <- base (k1, k2, v)
+ const int32_t ref_column_idx[] = {1, 0, 2};
+ for (size_t i = 0; i < 3; ++i) {
+ auto* mapping = changer->get_mutable_column_mapping(i);
+ mapping->ref_column_idx = ref_column_idx[i];
+ mapping->new_column = &_new_schema->column(i);
+ }
+ return changer;
+ }
+
+ bool _origin_enable_debug_points = false;
+ int64_t _origin_ttl_gc_interval_ms = 0;
+ int64_t _origin_ttl_info_update_interval_ms = 0;
+ std::string _cache_dir;
+ io::FileCacheFactory* _origin_file_cache_factory = nullptr;
+ std::unique_ptr<io::FileCacheFactory> _file_cache_factory;
+ CloudStorageEngine* _engine = nullptr;
+ TabletSchemaSPtr _base_schema;
+ TabletSchemaSPtr _new_schema;
+ CloudTabletSPtr _base_tablet;
+ CloudTabletSPtr _new_tablet;
+ ObjectPool _pool;
+ DescriptorTbl* _desc_tbl = nullptr;
+};
+
+TEST_F(CloudSchemaChangeSortingTest, SortingGeneratesIntermediateRowsets) {
+ // Make sure the scenario does generate intermediate rowsets in the file
cache path, which
+ // `VBaseSchemaChangeWithSorting` itself never removes.
+ auto base_rowset = write_base_rowset();
+ ASSERT_NE(base_rowset, nullptr);
+ auto changer = create_changer();
+ VBaseSchemaChangeWithSorting sc_procedure(*changer, 1024 * 1024 * 1024);
+ RowsetSharedPtr output_rowset;
+ auto st = run_sorting_schema_change(&sc_procedure, base_rowset,
&output_rowset);
+ ASSERT_TRUE(st.ok()) << st;
+
+ auto rowset_ids = rowset_ids_of_files(_cache_dir);
+ rowset_ids.erase(base_rowset->rowset_id().to_string());
+ rowset_ids.erase(output_rowset->rowset_id().to_string());
+ ASSERT_GT(rowset_ids.size(), 1);
+}
+
+TEST_F(CloudSchemaChangeSortingTest, RemoveIntermediateRowsetsOnSuccess) {
+ auto base_rowset = write_base_rowset();
+ ASSERT_NE(base_rowset, nullptr);
+ auto changer = create_changer();
+ VCloudSchemaChangeWithSorting sc_procedure(*changer, 1024 * 1024 * 1024);
+ RowsetSharedPtr output_rowset;
+ auto st = run_sorting_schema_change(&sc_procedure, base_rowset,
&output_rowset);
+ ASSERT_TRUE(st.ok()) << st;
+ ASSERT_EQ(output_rowset->num_rows(), kNumRows);
+
+ std::set<std::string> expected {base_rowset->rowset_id().to_string(),
+ output_rowset->rowset_id().to_string()};
+ ASSERT_EQ(rowset_ids_of_files(_cache_dir), expected);
+}
+
+TEST_F(CloudSchemaChangeSortingTest, RemoveIntermediateRowsetsOnFailure) {
+ auto base_rowset = write_base_rowset();
+ ASSERT_NE(base_rowset, nullptr);
+ auto changer = create_changer();
+ VCloudSchemaChangeWithSorting sc_procedure(*changer, 1024 * 1024 * 1024);
+ DebugPoints::instance()->add(
+
"VBaseSchemaChangeWithSorting._inner_process.before_external_sorting");
+ RowsetSharedPtr output_rowset;
+ auto st = run_sorting_schema_change(&sc_procedure, base_rowset,
&output_rowset);
+ ASSERT_FALSE(st.ok());
+ ASSERT_NE(st.to_string().find("fail before external sorting"),
std::string::npos) << st;
+
+ std::set<std::string> expected {base_rowset->rowset_id().to_string()};
+ ASSERT_EQ(rowset_ids_of_files(_cache_dir), expected);
+}
+
+TEST_F(CloudSchemaChangeSortingTest, RemoveStaleLocalRowsetFiles) {
+ auto dir = std::string(kTestDir) + "/stale";
+ ASSERT_TRUE(io::global_local_filesystem()->create_directory(dir).ok());
+
+ auto current_uid = UniqueId::gen_uid();
+ auto previous_uid = UniqueId::gen_uid();
+ auto rowset_id = [](int64_t inc_id, const UniqueId& uid) {
+ RowsetId id;
+ id.init(2, inc_id, uid.hi, uid.lo);
+ return id.to_string();
+ };
+ auto touch = [&](const std::string& name) {
+ io::FileWriterPtr writer;
+ ASSERT_TRUE(io::global_local_filesystem()->create_file(dir + "/" +
name, &writer).ok());
+ ASSERT_TRUE(writer->append("data").ok());
+ ASSERT_TRUE(writer->close().ok());
+ };
+
+ auto stale = rowset_id(10, previous_uid);
+ auto current = rowset_id(10, current_uid);
+ std::vector<std::string> removed {stale + "_0.dat", stale + "_1.dat",
stale + "_0.idx",
+ stale + "[email protected]"};
+ std::vector<std::string> kept {current + "_0.dat", current + "_0.idx",
"version",
+ "not_a_rowset_0.dat", stale + "_0.tmp"};
+ for (const auto& name : removed) {
+ touch(name);
+ }
+ for (const auto& name : kept) {
+ touch(name);
+ }
+ // directories are never removed, even if the name looks like a rowset file
+ ASSERT_TRUE(io::global_local_filesystem()->create_directory(dir + "/" +
stale + "_2.dat").ok());
+ kept.push_back(stale + "_2.dat");
+
+ ASSERT_EQ(CloudRowsetWriter::remove_stale_local_rowset_files(dir,
current_uid), removed.size());
+ for (const auto& name : removed) {
+ EXPECT_FALSE(std::filesystem::exists(dir + "/" + name)) << name;
+ }
+ for (const auto& name : kept) {
+ EXPECT_TRUE(std::filesystem::exists(dir + "/" + name)) << name;
+ }
+}
+
+} // namespace doris
diff --git
a/regression-test/suites/schema_change/test_cloud_sc_sorting_tmp_rowset_cleanup.groovy
b/regression-test/suites/schema_change/test_cloud_sc_sorting_tmp_rowset_cleanup.groovy
new file mode 100644
index 00000000000..6d6bbfdf7bf
--- /dev/null
+++
b/regression-test/suites/schema_change/test_cloud_sc_sorting_tmp_rowset_cleanup.groovy
@@ -0,0 +1,125 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+import org.apache.doris.regression.suite.ClusterOptions
+
+// In cloud mode, schema change with sorting writes intermediate rowsets to
the root of the file
+// cache path. They must be removed whether the schema change succeeds or
fails, and the ones left
+// by a crashed BE process must be removed when BE restarts.
+suite("test_cloud_sc_sorting_tmp_rowset_cleanup", "docker") {
+ def options = new ClusterOptions()
+ options.cloudMode = true
+ options.setFeNum(1)
+ options.setBeNum(1)
+ options.enableDebugPoints()
+
+ def tableName = "test_cloud_sc_sorting_tmp_rowset_cleanup"
+ // <rowset_id>_<segment_id>.dat or .idx, rowset_id is a 48 hex string with
version "02"
+ def rowsetFilePattern = ~/^02[0-9a-f]{46}_.*\.(dat|idx)$/
+
+ def rowsetFilesInCacheRoot = { String cacheRoot ->
+ def files = new File(cacheRoot).listFiles()
+ .findAll { it.isFile() && it.name ==~ rowsetFilePattern }
+ .collect { it.name }
+ logger.info("rowset files in ${cacheRoot}: ${files}")
+ return files
+ }
+
+ def waitRollupJob = { String expectedState ->
+ def state = null
+ awaitUntil(300) {
+ def jobs = sql_return_maparray """
+ SHOW ALTER TABLE ROLLUP WHERE TableName = "${tableName}" ORDER
BY CreateTime DESC LIMIT 1
+ """
+ state = jobs[0].State
+ logger.info("rollup job: ${jobs[0]}")
+ return state == "FINISHED" || state == "CANCELLED"
+ }
+ assertEquals(expectedState, state)
+ }
+
+ def countLogLines = { String logFile, String keyword ->
+ return new File(logFile).readLines().count { it.contains(keyword) }
+ }
+
+ docker(options) {
+ def be = cluster.getBeByIndex(1)
+ def cacheRoot = be.getBasePath() + "/storage/file_cache"
+
+ sql """ DROP TABLE IF EXISTS ${tableName} """
+ sql """
+ CREATE TABLE ${tableName} (
+ k1 INT NOT NULL,
+ k2 INT NOT NULL,
+ v INT NOT NULL
+ )
+ DUPLICATE KEY(k1, k2)
+ DISTRIBUTED BY HASH(k1) BUCKETS 1
+ PROPERTIES ("disable_auto_compaction" = "true")
+ """
+ for (int i = 0; i < 5; i++) {
+ sql """
+ INSERT INTO ${tableName}
+ SELECT number % 100, 100 - number % 100, number FROM
numbers("number" = "1000")
+ """
+ }
+ assertEquals(0, rowsetFilesInCacheRoot(cacheRoot).size())
+
+ // 1. The rollup reorders the keys, so the schema change sorts the
data and generates
+ // intermediate rowsets, which must be removed after the job finishes.
+ def sortingLogsBefore = countLogLines(be.getLogFilePath(),
"sc_sorting: 1")
+ sql """ ALTER TABLE ${tableName} ADD ROLLUP r_sorted(k2, k1, v) """
+ waitRollupJob("FINISHED")
+ assertTrue(countLogLines(be.getLogFilePath(), "sc_sorting: 1") >
sortingLogsBefore)
+ assertEquals(0, rowsetFilesInCacheRoot(cacheRoot).size())
+ def rows = sql """ SELECT count(*) FROM ${tableName} INDEX r_sorted """
+ assertEquals(5000L, rows[0][0] as long)
+
+ // 2. Intermediate rowsets must also be removed when the schema change
fails.
+ try {
+ GetDebugPoint().enableDebugPointForAllBEs(
+
"VBaseSchemaChangeWithSorting._inner_process.before_external_sorting")
+ sql """ ALTER TABLE ${tableName} ADD ROLLUP r_failed(k2, v) """
+ waitRollupJob("CANCELLED")
+ } finally {
+ GetDebugPoint().disableDebugPointForAllBEs(
+
"VBaseSchemaChangeWithSorting._inner_process.before_external_sorting")
+ }
+ assertEquals(0, rowsetFilesInCacheRoot(cacheRoot).size())
+
+ // 3. Rowset files left by a previous BE process, e.g. BE crashed
during schema change,
+ // are removed when BE starts. Other files in the cache root are kept.
+ cluster.stopBackends(1)
+ def random = new Random()
+ def randomHex = { int len -> (1..len).collect {
Integer.toHexString(random.nextInt(16)) }.join() }
+ def staleRowsetId = "02" + randomHex(46)
+ def staleFiles = ["${staleRowsetId}_0.dat", "${staleRowsetId}_0.idx"]
+ def keptFile = "not_a_rowset_file.dat"
+ (staleFiles + [keptFile]).each { new File("${cacheRoot}/${it}").text =
"data" }
+ assertEquals(staleFiles.size(),
rowsetFilesInCacheRoot(cacheRoot).size())
+
+ cluster.startBackends(1)
+ awaitUntil(60) {
+ def backends = sql_return_maparray "SHOW BACKENDS"
+ return backends[0].Alive.toString() == "true"
+ }
+ assertEquals(0, rowsetFilesInCacheRoot(cacheRoot).size())
+ assertTrue(new File("${cacheRoot}/${keptFile}").exists())
+ rows = sql """ SELECT count(*) FROM ${tableName} INDEX r_sorted """
+ assertEquals(5000L, rows[0][0] as long)
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]