Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backoff policy for failed mutation. #58036

Merged

Conversation

MikhailBurdukov
Copy link
Contributor

@MikhailBurdukov MikhailBurdukov commented Dec 19, 2023

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Enabled a backoff logic (e.g. exponential). Will provide an ability for reduced CPU usage, memory usage and log file sizes.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

If mutation query is incorrect or can't be performed right now then it will hang in infinite loop with high resources usage:
Example (from #55946):

CREATE TABLE main (id Int8) ENGINE=MergeTree() ORDER BY id;
INSERT INTO main SELECT * FROM system.numbers LIMIT 2;

ALTER TABLE main DELETE WHERE id IN (SELECT id FROM nonexistent);

Have a backoff logic (e.g. exponential) will provide an ability for reduced CPU usage, memory usage and log file sizes.

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-feature Pull request with new product feature label Dec 19, 2023
@robot-clickhouse-ci-1
Copy link
Contributor

robot-clickhouse-ci-1 commented Dec 19, 2023

This is an automated comment for commit fa5747a with description of existing statuses. It's updated for the latest CI running

❌ Click here to open a full report in a separate page

Successful checks
Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help✅ success
ClickBenchRuns [ClickBench](https://github.com/ClickHouse/ClickBench/) with instant-attach table✅ success
ClickHouse build checkBuilds ClickHouse in various configurations for use in further steps. You have to fix the builds that fail. Build logs often has enough information to fix the error, but you might have to reproduce the failure locally. The cmake options can be found in the build log, grepping for cmake. Use these options and follow the general build process✅ success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help✅ success
Docker keeper imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docker server imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docs checkBuilds and tests the documentation✅ success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here✅ success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integrational tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc✅ success
Install packagesChecks that the built packages are installable in a clear environment✅ success
Mergeable CheckChecks if all other necessary checks are successful✅ success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests✅ success
Push to DockerhubThe check for building and pushing the CI related docker images to docker hub✅ success
SQLTestThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
SQLancerFuzzing tests that detect logical bugs with SQLancer tool✅ success
SqllogicRun clickhouse on the sqllogic test set against sqlite and checks that all statements are passed✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors✅ success
Style checkRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report✅ success
Unit testsRuns the unit tests for different release types✅ success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts✅ success
Check nameDescriptionStatus
A SyncThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS❌ failure
CI runningA meta-check that indicates the running CI. Normally, it's in success or pending state. The failed status indicates some problems with the PR⏳ pending
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests❌ failure
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc❌ failure

@robot-ch-test-poll robot-ch-test-poll added pr-improvement Pull request with some product improvements and removed pr-feature Pull request with new product feature labels Dec 19, 2023
@MikhailBurdukov MikhailBurdukov marked this pull request as ready for review December 20, 2023 07:35
@@ -516,6 +516,7 @@ void StorageMergeTree::updateMutationEntriesErrors(FutureMergedMutatedPartPtr re
for (auto it = mutations_begin_it; it != mutations_end_it; ++it)
{
MergeTreeMutationEntry & entry = it->second;
auto failed_part = result_part->parts.at(0);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
auto failed_part = result_part->parts.at(0);
auto & failed_part = result_part->parts.at(0);

Comment on lines 1299 to 1325
if (exist_posponed_failed_part)
mutation_wait_event.notify_all();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All other usages of mutation_wait_event notify it under
std::lock_guard lock(mutation_wait_mutex). Generally you should not notify a condition variable while holding a mutex (as waiting threads will be notified just to sleep again) but maybe there is some other semantics here you could investigate

@myrrc
Copy link
Contributor

myrrc commented Jan 21, 2024

Resolves: #57089

Comment on lines 2908 to 2909
return config.getUInt("max_postpone_time_for_failed_mutations", 0ull);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can add this setting here
and query it like getSettingsRef().max_postpone_time...

explicit PartMutationBackoffPolicy(ContextPtr global_context_)
: WithContext(global_context_)
{
size_t max_pospone_time_ms = global_context_->getMaxPostponeTimeForFailedMutations();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could store context.getSettings() instead of storing the context ptr itself? Except for the setting, we don't use the context

Comment on lines 1375 to 1376
if (max_pospone_time_ms == 0)
max_pospone_power = 0;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo: posTpone

Comment on lines +76 to +78
# Executing incorrect mutation.
node.query(
"ALTER TABLE test_mutations DELETE WHERE x IN (SELECT x FROM notexist_table) SETTINGS allow_nondeterministic_mutations=1"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this setting will be present in Settings.h, we could change the setting in runtime via SETTINGS max_postpone_time=12345.
Please consider adding a test case changing the setting in runtime

)

time.sleep(5)
assert node_no_backoff.contains_in_log(REPLICATED_POSPONE_MUTATION_LOG) == False
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
assert node_no_backoff.contains_in_log(REPLICATED_POSPONE_MUTATION_LOG) == False
assert not node_no_backoff.contains_in_log(REPLICATED_POSPONE_MUTATION_LOG)


time.sleep(5)
assert node_no_backoff.contains_in_log(REPLICATED_POSPONE_MUTATION_LOG) == False
assert node_with_backoff.contains_in_log(REPLICATED_POSPONE_MUTATION_LOG) == True
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
assert node_with_backoff.contains_in_log(REPLICATED_POSPONE_MUTATION_LOG) == True
assert node_with_backoff.contains_in_log(REPLICATED_POSPONE_MUTATION_LOG)

@tavplubix tavplubix self-assigned this Feb 12, 2024
Comment on lines 1372 to 1374
Poco::Timestamp latest_fail_time;
UInt64 mutation_failure_version;
size_t max_postpone_time_ms;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we have time both in Poco::Timestamp and size_t?


PartMutationInfo(UInt64 mutation_failure_version_, size_t max_postpone_time_ms_)
: retry_count(0ull)
, latest_fail_time(std::move(Poco::Timestamp()))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't Poco::Timestamp a POD type? What's the point of moving it, then?

{
if (max_postpone_time_ms == 0)
return Poco::Timestamp();
return latest_fail_time + (1 << retry_count) * 1000ul;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Double whitespace after "return" and after "+"
  2. It's unclear what the precision of latest_fail_time is when it's implicitly converted to an integer (milliseconds? microseconds? nanoseconds?). Having * 1000ul doesn't make it more clear (although it's clear that it's not seconds). I would prefer having everything in integers with the same precision and a clear suffix like _ms. Poco::Timestamp (as well as Poco::Timespan) with implicit conversions are error-prone

}
}

void removePartFromFailed(const String& part_name)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
void removePartFromFailed(const String& part_name)
void removePartFromFailed(const String & part_name)

And in other places as well
(it's interesting why the Style Check did not fail)

@@ -1364,6 +1364,100 @@ class MergeTreeData : public IStorage, public WithMutableContext
const MergeListEntry * merge_entry,
std::shared_ptr<ProfileEvents::Counters::Snapshot> profile_counters);

class PartMutationBackoffPolicy : public WithContext
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like the context is never used

Comment on lines +1357 to +1360
constexpr auto fmt_string = "Not executing log entry {} of type {} for part {} "
"because recently it has failed. According to exponential backoff policy, put aside this log entry.";

LOG_DEBUG(LogToStr(out_postpone_reason, log), fmt_string, entry.znode_name, entry.typeToString(), entry.new_part_name);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to also print the number of (milli)seconds til the next attempt, but it's not necessary

Comment on lines 1348 to 1352
if (exist_postponed_failed_part)
{
std::lock_guard lock(mutation_wait_mutex);
mutation_wait_event.notify_all();
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unexpected, could you please add a comment explaining why we need to notify here? Introducing a backoff affects only timings and should not affect any synchronization

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you are right. Removed it.

@@ -835,6 +845,8 @@ CancellationCode StorageMergeTree::killMutation(const String & mutation_id)
}
}

mutation_backoff_policy.removeFromFailedByVersion(mutation_version);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Do we need the same for ReplicatedMergeTree?
  2. Feels like it will not work because multiple mutations may be merged together and executed at once. For example, if there's a faulty mutation with version 42 and another mutation with version 137, then a part all_1_2_3 can be mutated directly to all_1_2_3_137 (and this will fail due to the mutation 42). So according to the if (static_cast<UInt64>(result_part->part_info.mutation) == it->first) condition, addPartMutationFailure will be called for the version 137, and killing the faulty mutation 42 will not reset the backoff. Please add the corresponding test. Consider removing all the logic around the mutation version for simplicity and resetting all backoffs when killing any mutation

assert node.contains_in_log(POSPONE_MUTATION_LOG) == found_in_log
node.rotate_logs()

time.sleep(5)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests with sleep are flaky and unreliable

REPLICATED_POSPONE_MUTATION_LOG if replicated_table else POSPONE_MUTATION_LOG
)

node.restart_clickhouse()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use functional tests whenever possible: #39359 (comment)

In this case, restart_clickhouse can be replaced with DETACH/ATTACH TABLE, and wait_for_log_line with reading from system.text_log.

It's just FYI, it's not necessary to rewrite the test.

@MikhailBurdukov
Copy link
Contributor Author

MikhailBurdukov commented Feb 19, 2024

@tavplubix
Hi! I have fixed the changes you requested. There are a lot of test failures, but I'm not sure if my changes caused them. Сould you check it please?

Also there is one more thing to discuss:

In general, the change is good and it makes sense to enable it by default. What will be a good default value in your opinion?

For sure it depends on the usage scenario, but I think in general 5s-10s is totally okey. Can I set 5s as default value?

@tavplubix
Copy link
Member

The CI is completely broken by #60013
Although, Upgrade check failures are related to the changes: <Error> Application: Code: 115. DB::Exception: Unknown setting max_postpone_time_for_failed_mutations_ms: in MergeTree config. (UNKNOWN_SETTING)
You can fix it by removing the new config here:

# it contains some new settings, but we can safely remove it

5s-10s is totally okey

Isn't it too small? Imagine we have a mutation that converts a String column to UInt64, and it fails because it cannot parse some number in the middle. If the part is quite big, the mutation may work for a few minutes before failing. So it will wait for 5 seconds and then work again for a few minutes, so it will not reduce CPU usage. Maybe we can set it to 5 minutes.

@MikhailBurdukov
Copy link
Contributor Author

Set 5 minutes as default. Thanks for the help!

@tavplubix
Copy link
Member

Integration tests:

Stateless tests - 00984_parser_stack_overflow is broken in master (not clear why)

@tavplubix tavplubix merged commit ef3b191 into ClickHouse:master Feb 23, 2024
245 of 272 checks passed
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Feb 23, 2024
@@ -556,14 +559,21 @@ void StorageMergeTree::updateMutationEntriesErrors(FutureMergedMutatedPartPtr re
entry.latest_failed_part_info = MergeTreePartInfo();
entry.latest_fail_time = 0;
entry.latest_fail_reason.clear();
if (static_cast<UInt64>(result_part->part_info.mutation) == it->first)
mutation_backoff_policy.removePartFromFailed(failed_part->name);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be called from the killMutation as well? (so as for ReplicatedMergeTree)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, we call resetMutationFailures instead, see the review comments.

However, I've just realized that for RMT it will be only called on the initiator, and not on other replicas (I'm not sure what's the best way to fix it)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

8 participants