Skip to content

Avoid spawning too many idle threads - #72920

Merged
nickitat merged 12 commits into
ClickHouse:masterfrom
guowangy:limit-idle-threads
Dec 23, 2024
Merged

nickitat merged 12 commits into
ClickHouse:masterfrom
guowangy:limit-idle-threads

Conversation

@guowangy

@guowangy guowangy commented Dec 9, 2024 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

Avoid spawn too many idle threads

Documentation entry for user-facing changes

For short running queries (like ClickBench Q0), spawning too many threads is the performance bottleneck, most of the time wasted in launching threads, then waiting for all threads to finished. Based on these observations, 2 code changes introduced:

  1. Only allow one to spawn threads since most of the code is serialized. This try to fix the problem that in serialized pipeline, the thread has been assigned the key task for next loop but stuck in spawning threads, the task can only be executed after all spawning done.
  2. Stop spawning threads if idle number exceeds the threshold, this can help to finish the pipeline in time and avoid spawning too much unused threads.

In Xeon 8380 (2 socket, 160 vCPU in total), it can improve QPS of ClickBench Q0 by 99%, for Q6, Q7, Q41 and Q42, also have 5%~7% performance gain.

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

CI Settings (Only check the boxes if you know what you are doing):

  • Allow: All Required Checks
  • Allow: Stateless tests
  • Allow: Stateful tests
  • Allow: Integration Tests
  • Allow: Performance tests
  • Allow: All Builds
  • Allow: batch 1, 2 for multi-batch jobs
  • Allow: batch 3, 4, 5, 6 for multi-batch jobs

  • Exclude: Style check
  • Exclude: Fast test
  • Exclude: All with ASAN
  • Exclude: All with TSAN, MSAN, UBSAN, Coverage
  • Exclude: All with aarch64, release, debug

  • Run only fuzzers related jobs (libFuzzer fuzzers, AST fuzzers, etc.)
  • Exclude: AST fuzzers

  • Do not test
  • Woolen Wolfdog
  • Upload binaries for special builds
  • Disable merge-commit
  • Disable CI cache

Only allow one to spawn threads since most of the code is serialized.
This try to fix the problem that in serialized pipeline, the thread has
been assigned the key task for next loop but stuck in spawning threads,
the task can only be executed after all spawning done.
This can help to finish the pipeline in time and avoid spawning too much
unused threads.
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Dec 9, 2024
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-performance Pull request with some performance improvements label Dec 9, 2024
@robot-ch-test-poll2

robot-ch-test-poll2 commented Dec 9, 2024 •

Copy link
Copy Markdown
Contributor

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

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

Check nameDescriptionStatus
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests❌ failure
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
BuildsThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
ClickBenchRuns [ClickBench](https://github.com/ClickHouse/ClickBench/) with instant-attach table✅ 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. Integration 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
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
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✅ 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

@nickitat nickitat self-assigned this Dec 9, 2024
graph->initializeExecution(queue, async_queue);

tasks.init(num_threads, use_threads, profile_processors, trace_processors, read_progress_callback.get());
tasks.init(num_threads, 1, profile_processors, trace_processors, read_progress_callback.get());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

maybe

Suggested change
tasks.init(num_threads, 1, profile_processors, trace_processors, read_progress_callback.get());
tasks.init(num_threads, TOO_MANY_IDLE_THRESHOLD, profile_processors, trace_processors, read_progress_callback.get());

?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Do you mean making the threashold adjustable by parameter?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

no, i propose to start from TOO_MANY_IDLE_THRESHOLD instead of 1

@guowangy guowangy Dec 19, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

use_threads is used to determine the tasks finished condition (whether all use_threads are into idle). It should reflect the number of threads spawned. Making it to TOO_MANY_IDLE_THRESHOLD does not have positive performance impact. Furthermore, it might greater than num_threads (e.g number_threads = 2), which will make tasks finished condition unmet forever.

@guowangy

Copy link
Copy Markdown
Contributor Author

For test_concurrent_threads_soft_limit_defined_50 failure, it is not related to this PR. But I would like to make it more robust.

For assert, it requires ConcurrencyControlSlotsDelayed to equals 50, but 51 found.

=================================== FAILURES ===================================
______________ test_concurrent_threads_soft_limit_defined_50[1-5] ______________
....
>       assert_profile_event(
            node2,
            "test_concurrent_threads_soft_limit_2",
            "ConcurrencyControlSlotsDelayed",
            lambda x: x == 50,
        )
test_concurrent_threads_soft_limit/test.py:134: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
E       assert False
E        +  where False = <function test_concurrent_threads_soft_limit_defined_50.<locals>.<lambda> at 0x7fec6d023520>(51)

ConcurrencyControlSlotsDelayed is updated by max - granted and looks like max is assumed to 100 in CI environment, while granted is determined by available(lock) in this case.

[[nodiscard]] SlotAllocationPtr ConcurrencyControl::allocate(SlotCount min, SlotCount max)
{
    ...
    SlotCount granted = std::max(min, std::min(max, available(lock)));
    cur_concurrency += granted;
    ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsGranted, min);

    // Create allocation and start waiting if more slots are required
    if (granted < max)
    {
        ProfileEvents::increment(ProfileEvents::ConcurrencyControlSlotsDelayed, max - granted);
        ProfileEvents::increment(ProfileEvents::ConcurrencyControlQueriesDelayed);
        return SlotAllocationPtr(new Allocation(*this, max, granted,
            waiters.insert(cur_waiter, nullptr /* pointer is set by Allocation ctor */)));
    }

For available(lock), here max_concurrency is equals to concurrent_threads_soft_limit (= 50 in this case), but cur_concurrency is vary according to system loading (e.g. background tasks). So, the granted = available(lock) <= 50, thus ConcurrencyControlSlotsDelayed = (100 - granted) >= 50.

SlotCount ConcurrencyControl::available(std::unique_lock<std::mutex> &) const
{
    if (cur_concurrency < max_concurrency)
        return max_concurrency - cur_concurrency;
    return 0;
}

@guowangy

Copy link
Copy Markdown
Contributor Author

The failure of Build-binary_tidy is not related to this PR.

Dec 13 05:58:38 /build/src/Databases/Iceberg/RestCatalog.cpp:56:5: error: multiple declarations in a single statement reduces readability [readability-isolate-declaration,-warnings-as-errors]
Dec 13 05:58:38    56 |     std::string client_id, client_secret;
Dec 13 05:58:38       |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dec 13 05:58:38 /build/src/Databases/Iceberg/RestCatalog.cpp:626:17: error: multiple declarations in a single statement reduces readability [readability-isolate-declaration,-warnings-as-errors]
Dec 13 05:58:38   626 |                 std::string access_key_id, secret_access_key, session_token;
Dec 13 05:58:38       |                 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dec 13 05:58:38 268669 warnings generated.
Dec 13 05:58:38 Suppressed 269317 warnings (268667 in non-user code, 650 NOLINT).
Dec 13 05:58:38 Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
Dec 13 05:58:38 2 warnings treated as errors

@guowangy

Copy link
Copy Markdown
Contributor Author

Hi @nickitat

Can you help to review?
The CI failures about thread count assumption have been fixed. Now we have only the build-binary-tidy error and it's not related to this PR.


void processAsyncTasks();

bool shouldSpawn() const { return idle_threads <= TOO_MANY_IDLE_THRESHOLD; }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe I miss something but I find the name "idle" in "idle_threads" weird. These describe spawned threads which are doing work and they are not idling, right? Why not call the variable "spawned_threads" and the constant "TOO_MANY_SPAWNED_THREADS".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

spawned_threads should roughly equal to use_threads.

The "spawned" threads are not idle unless placed into threads_queue. This is why idle_threads is introduced, to dynamically tracked number of idle threads.

graph->initializeExecution(queue, async_queue);

tasks.init(num_threads, use_threads, profile_processors, trace_processors, read_progress_callback.get());
tasks.init(num_threads, 1, profile_processors, trace_processors, read_progress_callback.get());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't know where exactly (maybe here) but please document somewhere the purpose of the optimization, i.e. why the thread count is initially 1 and incremented incrementally afterwards. Otherwise, readers of this code will need to do Git archeology.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Because one of the key conditions to determine whether tasks are finished is num of use_threads threads all going into idle (placed into threads_queue). I think this variable should somewhat reflect number of spawned threads, otherwise, we need to wait for all threads spawned even if these is no job to do.

Setting to 1 instead of 0 is to tackle the problem in single thread.

Will add the doc.

@guowangy
guowangy force-pushed the limit-idle-threads branch 2 times, most recently from 4700dbb to 38f5d47 Compare December 19, 2024 03:20
@nickitat

Copy link
Copy Markdown
Member

Integration tests (aarch64) [4/6] - #73639
Integration tests (asan, old analyzer) [6/6] - #73639
Integration tests (tsan) [6/6] - #73639

@nickitat
nickitat enabled auto-merge December 23, 2024 22:15
@nickitat
nickitat added this pull request to the merge queue Dec 23, 2024
Merged via the queue into ClickHouse:master with commit ed012de Dec 23, 2024

@BranchSun BranchSun left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review 摘要

This PR makes thread spawning in the pipeline executor lazy/gated (start with use_threads = 1, serialize spawning via spawn_lock, stop spawning once idle_threads exceeds TOO_MANY_IDLE_THRESHOLD) and, as a consequence, relaxes a set of assertions that previously pinned exact thread counts. The new idle-thread counter itself looks consistent (all mutations happen under ExecutorTasks::mutex), but two things deserve attention: several tests are relaxed until they no longer validate the behavior they were written for, and the new spawn gate can silently skip spawning with no retry. No security issues were found.

决策(policy): COMMENT

发现问题

  • 🟡 medium: 2
  • 🟢 low: 3

行内评论未提交(API: 422: Unprocessable Entity | Line could not be resolved and Line could not be resolved)。

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-performance Pull request with some performance 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.

8 participants