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

Make StorageSet::getSet() thread safe #52352

Closed
wants to merge 1 commit into from

Conversation

valbok
Copy link
Contributor

@valbok valbok commented Jul 20, 2023

Found by TSan.
Happened when CREATE TABLE ... ENGINE = Set()
and TRUNCATE TABLE is called

DB::StorageSet::truncate
DB::InterpreterDropQuery::executeToTableImpl
...
DB::InterpreterDropQuery::execute

and mutations are happening

DB::ExpressionAnalyzer::isPlainStorageSetInSubquery calls `return storage_set->getSet();`    
DB::ExpressionAnalyzer::tryMakeSetForIndexFromSubquery 
...
DB::MergeTreeDataMergerMutator::mutatePartToTemporaryPart DB::StorageMergeTree::mutateSelectedPart
DB::StorageMergeTree::scheduleDataProcessingJob

Changelog category (leave one):

  • Improvement

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 21, 2023
@robot-ch-test-poll robot-ch-test-poll added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 21, 2023
@robot-ch-test-poll
Copy link
Contributor

robot-ch-test-poll commented Jul 21, 2023

This is an automated comment for commit 59874af with description of existing statuses. It's updated for the latest CI running
The full report is available here
The overall status of the commit is 🔴 failure

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
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
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 image for serversThe check to build and optionally push the mentioned image to docker hub🟢 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
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests🟢 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
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc🔴 failure
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

@alexey-milovidov
Copy link
Member

Ok, but the code is difficult to understand because it does not explain why atomic_load is needed there.

We should:

  • add a test that has a chance to reproduce the issue more frequently under TSan, to ensure it will not be broken again;
  • add a comment before this method;
  • it's usually expected that every synchronization has two sides: add something into truncate method;
  • atomic_load, especially for shared_ptr, can be confusing - what about replacing everything with a mutex? We'll simply lock it inside getSet and truncate.

@alexey-milovidov alexey-milovidov self-assigned this Jul 21, 2023
@alexey-milovidov
Copy link
Member

All integration tests with Thread Sanitizer have failed. You can check the results of the integration tests. Download the archive, and you can probably find a TSan report there.

@alexey-milovidov
Copy link
Member

PS. I strongly advice replacing everything with a mutex to make the code easier to read.

@valbok valbok marked this pull request as draft July 25, 2023 08:34
@valbok
Copy link
Contributor Author

valbok commented Aug 11, 2023

Suddenly tsan integration tests passed =)

@valbok valbok marked this pull request as ready for review August 11, 2023 12:39
@valbok valbok marked this pull request as draft August 14, 2023 07:50
@valbok
Copy link
Contributor Author

valbok commented Aug 14, 2023

All integration tests with Thread Sanitizer have failed. You can check the results of the integration tests. Download the archive, and you can probably find a TSan report there.

Looks not related to PR

@valbok
Copy link
Contributor Author

valbok commented Aug 14, 2023

  • add a test that has a chance to reproduce the issue more frequently under TSan, to ensure it will not be broken again;

All tests will be flaky since it is DR and very hard to reproduce.

  • add a comment before this method;

Added const to the method to notify that it is read access.

  • it's usually expected that every synchronization has two sides: add something into truncate method;
  • atomic_load, especially for shared_ptr, can be confusing - what about replacing everything with a mutex? We'll simply lock it inside getSet and truncate.

Since it is protecting only accessing to the member (set), I would suggest to use atomic_load/atomic_store instead of mutex, where it points that setting/loading the var is atomic and thread safe, SetPtr itself is not thread safe and every callers to getSet() should use it only for read access. This is why suggesting to make it const. When write access will be needed, second method could be added.

And sorry for some delays and some mess-up in comments. First commit missed atomic_store and it was confusing, yes.

@valbok valbok marked this pull request as ready for review August 14, 2023 08:28
@valbok valbok force-pushed the storage-set branch 2 times, most recently from 0fb2f54 to 4ae91e7 Compare August 14, 2023 12:33
@alexey-milovidov
Copy link
Member

All tests will be flaky since it is DR and very hard to reproduce.

We have these tests, they are named *race. They are trying to run the suspected code more frequently. With Thread Fuzzer and Thread Sanitizer, it increases the chance of detecting failure. If we have a bug, these tests will usually succeed but fail, say, once a month. And if the test will ever fail again, I guarantee that all our engineers will scream, jump around, and investigate it.

@valbok
Copy link
Contributor Author

valbok commented Aug 17, 2023

All tests will be flaky since it is DR and very hard to reproduce.

We have these tests, they are named *race. They are trying to run the suspected code more frequently. With Thread Fuzzer and Thread Sanitizer, it increases the chance of detecting failure. If we have a bug, these tests will usually succeed but fail, say, once a month. And if the test will ever fail again, I guarantee that all our engineers will scream, jump around, and investigate it.

Added a functional test which reproduces DR issue quite often.

@valbok valbok force-pushed the storage-set branch 3 times, most recently from 319932a to 01aa5c7 Compare August 18, 2023 06:50
@valbok
Copy link
Contributor Author

valbok commented Aug 18, 2023

02845_storage_set_data_race | FAIL | 180.25
                    -- | -- | --
        2023-08-17 16:31:01 Settings used in the test: --max_insert_threads 16 --group_by_two_level_threshold 1000000 --group_by_two_level_threshold_bytes 50000000 --distributed_aggregation_memory_efficient 1 --fsync_metadata 0 --output_format_parallel_formatting 0 --input_format_parallel_parsing 1 --min_chunk_bytes_for_parallel_parsing 6154312 --max_read_buffer_size 734190 --prefer_localhost_replica 0 --max_block_size 77044 --max_threads 4 --optimize_or_like_chain 0 --optimize_read_in_order 0 --enable_multiple_prewhere_read_steps 1 --read_in_order_two_level_merge_threshold 65 --optimize_aggregation_in_order 1 --aggregation_in_order_max_block_bytes 18697544 --min_compress_block_size 2642615 --max_compress_block_size 2672198 --use_uncompressed_cache 0 --min_bytes_to_use_direct_io 10737418240 --min_bytes_to_use_mmap_io 1 --local_filesystem_read_method pread_threadpool --remote_filesystem_read_method read --local_filesystem_read_prefetch 0 --remote_filesystem_read_prefetch 1 --allow_prefetched_read_pool_for_remote_filesystem 0 --filesystem_prefetch_max_memory_usage 128Mi --filesystem_prefetches_limit 0 --filesystem_prefetch_min_bytes_for_single_read_task 8Mi --filesystem_prefetch_step_marks 0 --filesystem_prefetch_step_bytes 0 --compile_aggregate_expressions 1 --compile_sort_description 1 --merge_tree_coarse_index_granularity 8 --optimize_distinct_in_order 1 --optimize_sorting_by_input_stream_properties 0 --http_response_buffer_size 8321584 --http_wait_end_of_query False --enable_memory_bound_merging_of_aggregation_results 1 --min_count_to_compile_expression 3 --min_count_to_compile_aggregate_expression 0 --min_count_to_compile_sort_description 0 --session_timezone America/Mazatlan 2023-08-17 16:31:01  2023-08-17 16:31:01 MergeTree settings used in test: --ratio_of_defaults_for_sparse_serialization 1.0 --prefer_fetch_merged_part_size_threshold 10737418240 --vertical_merge_algorithm_min_rows_to_activate 1 --vertical_merge_algorithm_min_columns_to_activate 100 --allow_vertical_merges_from_compact_to_wide_parts 1 --min_merge_bytes_to_use_direct_io 10737418240 --index_granularity_bytes 14119326 --merge_max_block_size 5915 --index_granularity 34477 --min_bytes_for_wide_part 396064249 --marks_compress_block_size 75549 --primary_key_compress_block_size 51545 2023-08-17 16:31:01  2023-08-17 16:31:01 Database: test_46nis5vk

@valbok
Copy link
Contributor Author

valbok commented Aug 18, 2023

@valbok valbok force-pushed the storage-set branch 3 times, most recently from 759a565 to 19d0f43 Compare August 30, 2023 11:27
Found by TSan.
Happened when CREATE TABLE ... ENGINE = Set()
and TRUNCATE TABLE is called

DB::StorageSet::truncate
DB::InterpreterDropQuery::executeToTableImpl
...
DB::InterpreterDropQuery::execute

and mutations are happening

DB::ExpressionAnalyzer::isPlainStorageSetInSubquery calls `return storage_set->getSet();`
DB::ExpressionAnalyzer::tryMakeSetForIndexFromSubquery
...
DB::MergeTreeDataMergerMutator::mutatePartToTemporaryPart
DB::StorageMergeTree::mutateSelectedPart
DB::StorageMergeTree::scheduleDataProcessingJob
@valbok
Copy link
Contributor Author

valbok commented Sep 11, 2023

00002_log_and_exception_messages_formatting FAIL

@valbok
Copy link
Contributor Author

valbok commented Sep 11, 2023

@kssenii

@alexey-milovidov
Copy link
Member

I remember (maybe I'm wrong) that atomic shared_ptrs in C++ are "fake", and while reading the diff, I'm thinking - maybe there is a mutex already inside this class, so we can just use it to make it obvious. But I didn't read the surrounding code.

@alexey-milovidov
Copy link
Member

Nevertheless, the requirement to have a comment in the code is not fulfilled...

@alexey-milovidov
Copy link
Member

Ok, I checked - we use atomic ops on shared_ptr in some other places.
I don't understand - if we use atomic ops on the set object, then we should use them everywhere.
Also, we should hold the previous SetPtr, otherwise if any of these methods:

void StorageSet::insertBlock(const Block & block, ContextPtr) { set->insertFromBlock(block.getColumnsWithTypeAndName()); }
void StorageSet::finishInsert() { set->finishInsert(); }

size_t StorageSet::getSize(ContextPtr) const { return set->getTotalRowCount(); }
std::optional<UInt64> StorageSet::totalRows(const Settings &) const { return set->getTotalRowCount(); }
std::optional<UInt64> StorageSet::totalBytes(const Settings &) const { return set->getTotalByteCount(); }

are called concurrently with truncate it will lead to use-after-free.

@alexey-milovidov
Copy link
Member

Is there a link to TSan report?

alexey-milovidov added a commit that referenced this pull request Oct 14, 2023
@alexey-milovidov
Copy link
Member

Continued in #55621.

@valbok valbok deleted the storage-set branch October 16, 2023 08:20
davenger added a commit that referenced this pull request Oct 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
can be tested Allows running workflows for external contributors pr-not-for-changelog This PR should not be mentioned in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants