Skip to content

Pin max_insert_threads in 02354_distributed_with_external_aggregation_memory_usage - #112478

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-02354-external-aggr-insert-memory
Jul 30, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-02354-external-aggr-insert-memory

Conversation

@groeneai

@groeneai groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

02354_distributed_with_external_aggregation_memory_usage started failing on the INSERT, before it
reaches the external aggregation it exists to measure:

Code: 241. Query memory limit exceeded: would use 4.66 GiB
(attempt to allocate chunk of 105.54 MiB), maximum: 4.66 GiB.
(query: insert into t_2354_dist_with_external_aggr
        select number, toString(number) as s, toFixedString(s, 100) from numbers_mt(5e7);)

Master failure:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=86d92d6b4119f54ab6f5fad650502dd3531ef4d8&name_0=MasterCI&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

Root cause: #109006 changed the max_insert_threads default from 1 to auto (the number of CPU
cores). This INSERT had no SETTINGS clause, so it inherits the profile default, and the write
side's per-thread buffers now scale with the core count. The 5G budget in this test was measured
with single-threaded insert ("5G is just the actual value taken from the logs + delta"), so the
peak crosses the 4.66 GiB profile limit from tests/config/users.d/limits.yaml.

The fix pins max_insert_threads = 1 on that INSERT, restoring the execution shape the budget was
calibrated for. This is the same adaptation #109006 applied in the same commit to the tests it
identified, for example 03217_primary_index_memory_leak.sql, where max_insert_threads = 1 sits
directly beside max_memory_usage = '100M'. This test needed the identical change and did not get
it. No limit is raised, no data volume is reduced, and every assertion is unchanged.

I deliberately did not make getMaxThreadsForAvailableMemory query-limit aware. It already runs
here and reduced the request from 192 to 134 threads, but its budget is server free memory rather
than the query's max_memory_usage, so it cannot help. Teaching it getCurrentQueryHardLimit()
would change read-side parallelism for every query that sets a memory limit, across its 19 call
sites, which is a separate discussion for #109006 rather than a test fix.

Validation

Reproduced with the CI-built binary at the base commit, on a server carrying
tests/config/users.d/limits.yaml (max_memory_usage = 5000000000 asserted live,
max_insert_threads rendering auto(192)).

arm result duration
before the fix FAIL, Code: 241 at 4.66 GiB 0.35 - 0.47 s
with the fix OK 10.52 s
pin removed again (mutation) FAIL, Code: 241 0.34 s

The duration split matches CI, where the 12 observed failures took 500-1860 ms and passing runs
take 10-26 s: the INSERT dies almost immediately instead of running to completion.

Peak memory for the same INSERT, from system.query_log:

max_insert_threads peak share of the 5G budget
1 (this fix) 2.28 GiB 48.9 %
default (auto, reduced to 134) 4.65 GiB 100 %

So the pin leaves about 2.5 GiB of headroom rather than sitting just under the cap.

50 runs with randomization enabled: 50 OK, 0 FAIL. --long-test-runs-ratio 1.0 is needed for the
count to be real, since the long tag otherwise scales --test-runs by 0.1.

Scope: of the 62 stateless tests that combine INSERT ... SELECT with max_memory_usage, 12
already pinned max_insert_threads before this change. Querying the Query memory limit exceeded
signature across the #109006 merge boundary, this test is the only one that regressed, going from 0 failures to 12
across 12 distinct pull requests plus one master run, against 0 failures in the 90 days before
that merge (24181 passing runs). Every other candidate has no failures after the merge.

Version info

  • Merged into: 26.8.1.425 (included in 26.8 and later)

…_memory_usage

The test began failing on its INSERT with

  Code: 241. Query memory limit exceeded: would use 4.66 GiB, maximum: 4.66 GiB
  (query: insert into t_2354_dist_with_external_aggr select number, toString(number)
   as s, toFixedString(s, 100) from numbers_mt(5e7);)

so it never reached the external aggregation it exists to measure.

max_insert_threads changed default from 1 to auto (the number of CPU cores) in
ClickHouse#109006. This INSERT carried no SETTINGS clause, so it inherits the profile
default and the write side's per-thread buffers now scale with the core count.
The 5G budget in this test was measured with single-threaded insert ("5G is just
the actual value taken from the logs + delta"), so the peak crosses the 4.66 GiB
profile limit from tests/config/users.d/limits.yaml.

max_insert_threads_min_free_memory_per_thread does not prevent it: the guard runs
and reduced the request from 192 to 134 threads, but its budget is server free
memory rather than the query's max_memory_usage, so insert parallelism is never
tied to the limit the query is measured against.

Pinning max_insert_threads = 1 restores the execution shape the budget was
calibrated for. This is the same adaptation ClickHouse#109006 made in the same commit to
the tests it identified, for example 03217_primary_index_memory_leak.sql, where
max_insert_threads = 1 sits directly beside max_memory_usage = '100M'. This test
needed the identical change and did not get it.

Measured with the CI binary at this base commit, on a server carrying the CI
limits profile: before the fix the test fails in 0.35-0.47 s, with the fix it
passes in 10.52 s, and removing only the pin makes it fail again. Peak memory for
the INSERT is 2.28 GiB at one thread (48.9% of the budget) versus 4.65 GiB at the
default, so the pin leaves real headroom rather than sitting just under the cap.
50 runs with randomization enabled: 50 OK, 0 FAIL.

Of the 62 stateless tests combining INSERT ... SELECT with max_memory_usage, 13
already pin max_insert_threads. Across the ClickHouse#109006 merge boundary this test is
the only one that regressed, going from 0 failures to 12 across 12 distinct pull
requests plus one master run, against 0 failures in the preceding 90 days.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two independent reviews of this change: a cold read of the resulting code, and a separate
second-model pass. 5 items, all resolved before this pull request was opened. No blocker.

⚠️ Runtime proof of the memory headroom and of reversion sensitivity (major, second-model pass)

Raised as a verification ask: static inspection cannot show that the pin stays below the 5G profile
limit, nor that removing it reproduces the failure. Answered by the measurements already in the
description, each of which I re-checked against the raw artifacts rather than taking on trust:

  • 50 consecutive runs, 50 OK and 0 FAIL. The log header confirms the server is 26.8.1.361 @ 6cbe898976f61734, the base commit, and --long-test-runs-ratio 1.0 is present, so all 50 runs
    really executed instead of the 5 the long tag would otherwise scale to.
  • Peak memory_usage from system.query_log for the same INSERT: 2 443 569 965 B (2.28 GiB, 48.9 %
    of the budget) at max_insert_threads = 1, versus 4 997 920 386 B (4.65 GiB, 100 %) at the
    default. About 2.5 GiB of headroom, and Settings['max_insert_threads'] = 1 in the query log
    confirms the pinned value took effect.
  • Mutation: reverting only the settings clause, keeping the comment, makes the test fail again
    with Code: 241 in 0.34 s. The file was then restored and verified byte identical.

The "intermittent" premise is also weaker than the data. The CI runner's own same-settings rerun
loops reported 16/25, 17/25, 14/23 and 12/25 (64-68 %), and locally the unpinned arm failed 3 out of
3 once the 5G profile was installed, so this is load dependent rather than a rare flake. The
preconditions were asserted live before any verdict was trusted: max_memory_usage = 5000000000
and max_insert_threads rendering auto(192).

💡 Passing-run count could not be reproduced (nit, own review) - Fixed. The count now states the
window explicitly: 0 failures in the 90 days before the #109006 merge, 24181 passing runs. Eight
candidate windows land between 24156 and 24594, so the original bare figure would not have
reproduced for a reviewer. The 0-failure half holds at every window (all time since 2024-11-15: 10
failures against 59 979 passes).

💡 Off-by-one in the pinned-test count (nit, own review) - Fixed. On the merge base 12 of the 62
stateless tests combining INSERT ... SELECT with max_memory_usage pin max_insert_threads; the
13 in the first draft counted this test itself after the change, which reads wrong beside "already".

💡 Trivial-insert-select push-down is not part of the mechanism (nit, own review) - No change
needed, recorded so it is not reintroduced. An early rationale held that
applyTrivialInsertSelectOptimization also pushes the value into the SELECT as max_threads. That
path is inactive here: optimize_trivial_insert_select defaults to false, tests/config does not
enable it, and the randomizer that would flip it is suppressed by this test's no-random-settings
tag. The description attributes the peak solely to the write side's per-thread buffers, which is the
accurate account.

💡 Carrier set independently confirmed as exactly one test (nit, own review) - No action. Three
methods agree. Keyed on the Query memory limit exceeded signature across the merge boundary, this
test goes from 0 to 12 failures over 12 distinct pull requests plus one master run while
00084_external_aggregation moves the other way (73 to 3, already fixed separately). A wider sweep
with no failure-text filter at all, over every stateless test with zero failures before the merge
and at least three after, returns 41 rows in which this test is the only one with more than a single
distinct pull request; every other row is a single-pull-request own-test case. Re-querying 36
unpinned INSERT ... SELECT plus max_memory_usage candidates with the before filter removed
returns no failures after the merge. So the single-file scope is right and a speculative sweep of
the remaining 50 tests is not warranted.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/clickhouse-test 02354_distributed_with_external_aggregation_memory_usage --no-random-settings --no-random-merge-tree-settings against a server carrying tests/config/users.d/limits.yaml, using the CI-built binary at the base commit. Failed on every pristine run (3/3) in 0.34-0.47 s with Code: 241 ... would use 4.66 GiB ... maximum: 4.66 GiB. Not marginal: CI's own rerun loops reported 16/25, 17/25 and 14/23. The 5G cap was asserted live (max_memory_usage = 5000000000, max_insert_threads rendering auto(192)) before any result was trusted.
b Root cause explained? Yes. #109006 changed the max_insert_threads default from 1 to auto (core count). This INSERT has no SETTINGS clause, so it inherits the profile default and the write side's per-thread buffers scale with the core count, while the test's 5G budget was measured with single-threaded insert. max_insert_threads_min_free_memory_per_thread cannot save it: the guard did run and reduced 192 to 134 threads (MemoryTrackerUtils: Lower number of threads for query to 134 (192 requested)), but its budget is server free memory (537.75 GiB / 4 GiB), never the query's max_memory_usage.
c Fix matches root cause? Yes. It restores the execution shape the budget was calibrated for. No limit is raised, no data volume is reduced, no tag is added (the test already carries no-random-settings, which is part of why it was exposed). It is the same adaptation #109006 applied in the same commit to the tests it identified, e.g. 03217_primary_index_memory_leak.sql, where max_insert_threads = 1 sits directly beside max_memory_usage = '100M'. This test was a missed carrier of that set.
d Test intent preserved / new tests added? Yes, and strictly improved: before the fix the test died on its first data statement and never measured the external aggregation it exists for. The 5G budget, max_memory_usage = '5Gi', all aggregation settings and every assertion are untouched; the empty .reference is unchanged. No new test is needed since this test is the regression test, and #109006 already added 04492_max_insert_threads_auto_default.sql for the setting's own semantics.
e Both directions demonstrated? Yes. Pristine: FAIL, Code: 241, 0.35-0.47 s. With the fix: OK, 10.52 s. Mutation (pin removed again, comment kept): FAIL, Code: 241, 0.34 s, so the pin is load-bearing and the passing arm was not a void negative. The duration split matches CI, where the 12 failures took 500-1860 ms and passing runs take 10-26 s.
f Fix is general across code paths? Yes, decided by measurement. Of the 62 stateless tests combining INSERT ... SELECT with max_memory_usage, 12 already pinned max_insert_threads before this change. Querying the Query memory limit exceeded signature across the #109006 merge boundary, this test is the only one that regressed: 0 failures before, 12 after across 12 distinct pull requests plus 1 master run, against 0 failures in the 90 days before that merge (24181 passing runs). Every other candidate (00084, 00162, 00899, 03829) has 0 failures after the merge. Fixing this one test closes the class.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for type wrappers (no expression or type logic is involved). The relevant input axis is the host core count, and pinning an absolute 1 is inherently core-count independent, which is precisely why a machine-dependent default was the hazard. Verified the pinned value takes effect: Settings['max_insert_threads'] = 1 in system.query_log for the fixed run.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. Test-only change, no src/ change, so no SettingsChangesHistory.cpp entry, no serialization or versioning concern and no experimental gate. #109006 already carries its own history entry for the default change.
i Invariants and contracts preserved? Yes. A per-statement SETTINGS clause is scoped to that one INSERT and cannot leak into the later set block or the aggregation SELECT, which is also why a file-level SET was rejected (the file already uses set after the INSERT). Parse shape matches in-tree precedent for the identical spelling on a numbers_mt INSERT, 01119_optimize_trivial_insert_select.sql:9. Measured headroom rather than assumed: peak at one insert thread is 2.28 GiB, 48.9 % of the 5G budget, versus 4.65 GiB at the default.

Session id: cron:clickhouse-impl-slot-40:20260729-172438

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat, could you review this? The test was failing on its INSERT with Code 241 before reaching the external aggregation it measures: #109006 changed the max_insert_threads default from 1 to the core count, and this INSERT had no SETTINGS clause, so the write side per-thread buffers pushed the peak past the 5G profile limit the test was calibrated against.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fd8865a]

Summary: ✅


AI Review

Summary

This PR pins max_insert_threads = 1 on the setup INSERT in 02354_distributed_with_external_aggregation_memory_usage, restoring the single-threaded insert shape that the test's 5 GiB budget was calibrated against after max_insert_threads started defaulting to auto. The change is narrowly scoped, matches the failure mode described in the PR, and I did not find a correctness, contract, or coverage problem that warrants a new inline review comment.

Final Verdict

✅ No blocking issues found.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 30, 2026
@PedroTadim PedroTadim self-assigned this Jul 30, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 695cd64 Jul 30, 2026
179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
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-ci 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