Skip to content

Tune max_threads_min_free_memory_per_thread/max_insert_threads_min_free_memory_per_thread and add logs - #105542

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
azat:max_threads_min_free_memory_per_thread-fixes
Jun 11, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
azat:max_threads_min_free_memory_per_thread-fixes

Conversation

@azat

@azat azat commented May 21, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Tune max_threads_min_free_memory_per_thread/max_insert_threads_min_free_memory_per_thread and add logs

Version info

  • Merged into: 26.6.1.617

@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a0c9de7]

Summary: ✅


AI Review

Summary
  • This PR now only adds a debug log when getMaxThreadsForAvailableMemory lowers the requested thread count because of global memory pressure. The earlier default-tuning changes are no longer present in the cumulative diff. I did not find a correctness, safety, performance, or metadata issue that warrants an inline review comment.
Missing context / blind spots
  • ⚠️ Required CI is not fully complete yet: Style check is passing, while Build (arm_tidy), Fast test, Code Review, and the aggregate PR check are still pending. Passing CI would close compile and regression validation.
Final Verdict
  • Status: ✅ Approve
  • No code-review action required.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label May 21, 2026
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved

@alexey-milovidov alexey-milovidov left a comment

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 understand this.

@alexey-milovidov alexey-milovidov self-assigned this May 21, 2026
@azat

azat commented May 21, 2026

Copy link
Copy Markdown
Member Author

I have a server with 16 GiB of RAM and 64 cores (16GiB limit is manually passed for reproducing another issue)
I was debugging one query (from clickbench) and noticed that newer version works slower
And the reason was this

If you still think that 1GiB/4GiB limit is a way to go - let's keep it, but at least let's add some logs

@azat

azat commented May 21, 2026

Copy link
Copy Markdown
Member Author

Also if I understand the formula correctly, it uses available memory to make judgement, but, not all queries uses at least 1GiB/thread

@alexey-milovidov

Copy link
Copy Markdown
Member

I have a server with 16 GiB of RAM and 64 cores (16GiB limit is manually passed for reproducing another issue)
I was debugging one query (from clickbench) and noticed that newer version works slower
And the reason was this

If you still think that 1GiB/4GiB limit is a way to go - let's keep it, but at least let's add some logs

Tbh I think it's okay...

Maybe we can set the limits a little bit smaller. But the current values are realistic; they are set from two observations:

  • they don't make it worse on any existing AWS/GCP/Azure instance types (where the minimum is 2GB RAM per 1 vCPU) (keeping in mind that max_insert_threads is still 1 in self-managed setups by default);
  • with object storage, INSERTs are memory hungry, so taming them down will be very useful.

But maybe we should lower the thresholds twice? Anyway, worth collecting more data first.

@azat

azat commented May 22, 2026

Copy link
Copy Markdown
Member Author

they don't make it worse on any existing AWS/GCP/Azure instance types (where the minimum is 2GB RAM per 1 vCPU) (keeping in mind that max_insert_threads is still 1 in self-managed setups by default);

I think for "fast" queries that do not require a lot of RAM they will make queries slower, and it may be hard to understand why.

But anyway, let's at least add logging for now.

Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
@azat
azat requested a review from alexey-milovidov May 24, 2026 09:41
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, investigate the CI failure on this PR: a Segmentation fault (STID: 2280-2571) in Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential) (test 03393_max_merge_delayed_streams_for_parallel_write, reported as Server died):

The crash is in the new system.background_schedule_pool_log SystemLog flush, unrelated to this PR (which only adds a DEBUG log in getMaxThreadsForAvailableMemory):

src/Columns/ColumnString.h:138: DB::ColumnString::insert(DB::Field const&)
src/Interpreters/BackgroundSchedulePoolLog.cpp:55: DB::BackgroundSchedulePoolLogElement::appendToBlock(...)
src/Interpreters/SystemLog.cpp:696: DB::SystemLog<DB::BackgroundSchedulePoolLogElement>::flushImpl(...)
src/Interpreters/SystemLog.cpp:636: DB::SystemLog<DB::BackgroundSchedulePoolLogElement>::savingThreadFunction()

SystemLog::flushImpl segfaults are a recurring flaky class on master (14 occurrences across 11 distinct PRs in the last 90 days). BackgroundSchedulePoolLog itself was introduced recently (commit a3a9a15e939), so the crash may point to a latent bug in that subsystem. There is no open issue for it yet. Please investigate and provide a fix in a separate PR; if a fix is already in progress, link it here.

I have merged the latest master into this branch (it was 859 commits behind).

@groeneai

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Thanks, investigated. No existing issue or fix PR.

STID 2280-2571 is a singleton: 1 hit in 90 days, only this PR run (2026-05-29 20:28, sha 25c6101). Not caused by this PR.

Crash signature (raw SIGSEGV, not an ASan report): write fault at an unmapped address inside memcpy:

__memmove_sse2_unaligned_erms
__asan_memcpy
ColumnString.h:138  DB::ColumnString::insert(Field const&)
BackgroundSchedulePoolLog.cpp:55  appendToBlock   // columns[4]->insert(query_id)
SystemLog.cpp:696   flushImpl
SystemLog.cpp:636   savingThreadFunction

BaseDaemon reports Access: write. Address not mapped to object. ColumnString::insert does chars.resize(old + s.size()); memcpy(dst, s.data(), s.size()). A write fault here means s.size() was garbage: old + size overflowed, resize undersized the destination, and the memcpy overran it. So the source String (elem.query_id) already had a corrupted size before the flush touched it.

BackgroundSchedulePoolLog itself looks correct:

  • appendToBlock column order and types match getColumnsDescription() exactly, no misaligned insert.
  • The producer (BackgroundSchedulePoolTaskInfo::execute) builds query_id under schedule_mutex, copies it by value into the element, then add(std::move(elem)). No string_view/StringRef into a freed buffer, no moved-from source. query_id is also the member read by getTasks() under the same mutex, so no race on it.

So this is not a structural bug in the new subsystem; it is heap corruption whose origin is upstream (a wild write or data race from another component clobbering the queued element). The broader SystemLog::flushImpl segfault class spans many different SystemLog types and STIDs, which is consistent with external corruption rather than a defect in any one log. This config also wraps every system log in a Distributed sender to a remote cluster, and the server was degraded for ~40 min before the fault (continuous TOO_MANY_PARTS, DNS failures), a plausible window for such corruption.

Next step / ask: per our no-speculative-fix policy I will not push a defensive guard into appendToBlock, since that would only mask the symptom. To pin the actual corrupting writer I need the symbolized core dump. The only dump on the report is core.RuntimeData.2089-6365.zst.enc, which is encrypted and not decryptable outside CI. Could you point me at a decrypted/symbolized version (or enable that artifact)? With it I can identify the thread that corrupted the element and fix at the source in a separate PR. I am also watching CIDB for recurrences.

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 8/8 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov update: I decrypted and symbolized the core dump (core.RuntimeData.2089-6365) from the failing run with the matching amd_asan_ubsan binary. The earlier "oversized memcpy" guess was wrong; the real signature is allocator-level heap corruption.

Symbolized crash:

#0  __GI___libc_malloc                              malloc/malloc.c:3354
#1  ColumnString::insert(Field const&)              ColumnString.h:138
#2  BackgroundSchedulePoolLogElement::appendToBlock BackgroundSchedulePoolLog.cpp:55
#3  SystemLog<...>::flushImpl  (to_flush_end=8948)  SystemLog.cpp:696
#4  SystemLog<...>::savingThreadFunction            SystemLog.cpp:636

Registers: rip=__libc_malloc+267, rax=rdi=0x7b76c5944fc9 (unaligned, low nibble 0x9), si_addr=0x829 (near-null). The fault is INSIDE the allocator while it walks a free list, dereferencing a corrupted chunk forward pointer. So ColumnString::insert only triggered the crash by calling malloc; the heap was already corrupted by another thread. The BackgroundSchedulePoolLog flush is the victim, not the cause.

I scanned all 1905 threads in the core: no ASan error-report thread, no thread in a memcpy/memmove/memset interceptor, no active heap writer. The corrupting write had already completed and the bad pointer lands in unmapped memory, so the core cannot pin the culprit thread.

Other findings:

  • BackgroundSchedulePoolLog itself is structurally correct: appendToBlock column order and types match getColumnsDescription() (all 12 columns), and every inserted string is owned by value (no string_view/StringRef into a freed buffer, no moved-from source, no race on query_id).
  • STID 2280-2571 is a singleton: 1 occurrence in 90 days, only on this PR's sha 25c6101 (2026-05-29), never recurred and never on master.
  • No existing issue and no competing fix PR.
  • The run was degraded for ~40 min before the fault (continuous TOO_MANY_PARTS plus DNS failures), and this config wraps all system logs in a Distributed sender to a remote cluster.

Conclusion: this is a one-off, environment-specific heap corruption with no visible corrupting writer and no reproduction. There is no defect to fix in BackgroundSchedulePoolLog, and I will not push a speculative defensive guard (it would only mask the symptom). I will keep watching CIDB for STID 2280-2571 and the broader flushImpl segfault class; if it recurs, especially on master, I will reopen with a concrete repro. If you have a way to get an ASan/UBSan report (not just a raw SIGSEGV core) for a recurrence, that would let us pin the corrupting thread directly.

@alexey-milovidov alexey-milovidov left a comment

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.

The earlier CHANGES_REQUESTED was about the threshold tuning, which has since been reverted — the remaining diff only adds a DEBUG log in getMaxThreadsForAvailableMemory when the number of threads is lowered, which is what we agreed on ("let's at least add logging for now"). Approving.

CI status: the failed CH Inc sync was two flaky integration jobs (both failed tests passed on in-job retry; the other shard hit a session timeout at 99% with 0 failures) — I have rerun the failed jobs. The Report messages failure only reported transient CI DB insert timeouts (play.clickhouse.com read timeout) from build jobs, unrelated to this PR.

@alexey-milovidov
alexey-milovidov merged commit 09b722a into ClickHouse:master Jun 11, 2026
166 of 167 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

4 participants