Skip to content

Do not charge per-thread accounting state to a Storage memory check scenario - #121364

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:storage-memory-check-exclude-thread-accounting
Sep 23, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:storage-memory-check-exclude-thread-accounting

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 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):

Exclude allocations made while a pool thread starts, joins or leaves a thread group from the Storage memory check comparison, so a scenario is not charged for the per-thread accounting state of whichever background threads served it.

Description

Storage memory check still fails unrelated PRs with a byte-constant
change=+1,056. Since #120487 merged, 9 heads had +1,056 as their only
failing scenario, on 03_add_secondary_indexes.sql and 04_add_projection.sql.

A pooled thread that runs a mutation step attaches to the task's ThreadGroup,
and that attach constructs thread-local counter state (TasksStatsCounters, a
ProcfsMetricsProvider, two __cxa_thread_atexit_impl registrations) that lives
until the thread exits. GlobalThreadPool keeps its threads, so what gets
measured is how many pool threads have ever served the scenario, which is a
scheduling draw. It is one cluster of 7 stacks costing exactly 528 bytes per
participating thread
: one unit is under the 1,024-byte threshold, two clear it
by 32. #120702 at b48703670359 has rows for 04_add_projection.sql at both
528 and 1,056, the same commit measured twice with different answers.

Add the three ThreadStatus attach, detach and constructor frames to the
analyzer's existing EXCLUDED_STACK_FRAME_PREFIXES. Job-side, so it applies to
both arms of one run
(the master arm binary comes from the merge base, so a C++ fix would be
asymmetric until it reached master); keyed on the allocation site, so it is
pool-agnostic.

On the production reports for #118967, #120960, #121251 and #120702, removing
this cluster takes every failing scenario's change to exactly 0, largest
residual 64 B. Locally, 20 repeated runs reproduce the 528-byte unit with its
multiplicity varying, an injected 64 KiB-per-table allocation is still reported
in full, and reverting only these prefixes restores the old numbers exactly.

Those rows also leave the HTML report, as dumpProfile overhead already does.
STORAGE_CHANGE_THRESHOLD_BYTES is untouched: removing this noise is what would
allow lowering it toward the parser lane's 100, but that calibration deserves its
own change.


Workflow [PR]
Sync PR [sync-upstream/pr/121364]

Version info

  • Merged into: 26.10.1.539-master (included in 26.10 and later)

…cenario

`Storage memory check` fails unrelated PRs with a byte-constant
`change=+1,056`. Since ClickHouse#120487 removed the one-time initialization offset,
9 heads had `+1,056` as their only failing scenario, on
`03_add_secondary_indexes.sql` and `04_add_projection.sql`.

A pooled thread that runs a mutation step attaches to the task's
`ThreadGroup` through `ThreadGroupSwitcher`, and that attach constructs
thread-local performance-counter state: `TasksStatsCounters`, a
`ProcfsMetricsProvider`, and two `__cxa_thread_atexit_impl` registrations
which by construction live until the thread exits. `GlobalThreadPool` keeps
its threads, so those bytes stay live once a thread has participated, and
the quantity the checkpoint diff measures is how many distinct pool threads
have ever served the scenario. Which window a thread's first participation
lands in is a scheduling draw.

It is one cluster of 7 stacks costing exactly 528 bytes per participating
thread: +384 `TasksStatsCounters::create`, -64
`ThreadGroup::SharedData::SharedData`, +64 `detachFromGroup`, +48
`make_shared<ProcfsMetricsProvider>`, +32 and +32 for the two
`__cxa_thread_atexit_impl` registrations, +32 for the query-id string copy
in `applyQuerySettings`. The gate is `absolute_change > 1024 AND
percent_change > 1.0`, so one unit passes and two clear it by 32 bytes: the
threshold sits inside the noise quantum. PR ClickHouse#120702 at `b48703670359` has
rows for `04_add_projection.sql` at both 528 and 1,056, the same commit
measured twice with different answers, so no threshold value could measure
this quantity.

Raising the threshold is the move that already failed: `150d1f2d0290b`
raised this lane from the parser lane's 100 to 1,024 for this exact
mechanism, and two units cleared it three days later. Waiting for
background tasks to quiesce cannot work either, because this state is
registered with `__cxa_thread_atexit_impl` and is not a teardown tail.
Pinning the pools to one thread would be C++-side, and the master arm
binary is downloaded from the merge base, so such a fix is asymmetric until
it reaches master.

Instead add the three thread attach/detach frames to the analyzer's
existing `EXCLUDED_STACK_FRAME_PREFIXES`, which `compute_diff` already
consults before a stack reaches the gated total. Both arms of a run are
analysed by the same script from the same checkout, so the change applies
symmetrically from the first run, and keying on the allocation site covers
every pool at once rather than enumerating pools or settings.

On the production reports for ClickHouse#118967, ClickHouse#120960, ClickHouse#121251 and ClickHouse#120702,
removing this cluster takes every failing scenario's change to exactly 0,
with the largest residual anywhere 64 bytes against the 1,024-byte
threshold. Locally, 20 repeated two-pass runs of one binary reproduce the
528-byte unit with the same 7-row composition and a multiplicity that
varies run to run; an injected 64 KiB-per-table allocation is still
reported at full size; and reverting only these three prefixes restores the
pre-fix numbers byte-for-byte.

Two consequences are deliberate. The cluster rows also leave the HTML
report, exactly as `dumpProfile` overhead already does, because a row the
check must not gate on should not be presented as a finding. And
thread-accounting regressions are no longer measured here, which the
same-commit pair above shows was never possible anyway.

`STORAGE_CHANGE_THRESHOLD_BYTES` is left at 1,024. Removing this noise is
what would make lowering it toward the parser lane's 100 possible, but that
is a calibration decision with its own data.

Related: ClickHouse#120487
Related: ClickHouse#119480

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 21, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex, 0 gate findings, plus 3 from my own cold
review of the resulting code; 1 full pass, 0 fix rounds needed).

I re-derived the premise from the four production Storage memory check reports with my own extractor
rather than taking the proposal's word for it, and the two measurements agree row for row: applying the
three prefixes takes every failing scenario (#118967 04, #120960 03, #121251 03, all +1,056) to
change = +0, and the largest residual in any of the 36 scenario windows is -64 B, which is
improvement-direction and can never FAIL. The rendered stack is truncated to 6 frames while the shipped
predicate sees the whole frame list, so that is a lower bound on the excision. CIDB agrees on volume: 38
FAIL rows since #120487 merged, of which exactly 9 heads fail only on +1,056.

# Sev Finding Verdict Evidence / action
1 💡 The README says the exclusion is "made while a thread joins or leaves a thread group", which covers 2 of the 3 prefixes: DB::ThreadStatus::ThreadStatus fires on a newly created pool thread, before any group join (carrier row DB::ThreadGroup::SharedData::SharedData() > DB::ThreadStatus::ThreadStatus(unsigned long) > startThreadFromGlobalPool > ThreadPoolImpl<std::thread>::ThreadFromThreadPool::worker()) Noted, not blocking Its operative clause ("per-thread accounting state that lives until the pool thread exits") does cover all three, so it understates the mechanism rather than misstating it, and the in-code comment beside the list is exact. The changelog entry was corrected here to "while a pool thread starts, joins or leaves a thread group". Happy to tighten the README line if preferred.
2 💡 ci/jobs/storage_memory_check.py:32-34 justifies STORAGE_CHANGE_THRESHOLD_BYTES = 1024 with exactly the noise this change now excludes, so that rationale no longer describes what the constant absorbs Noted, not blocking, deliberately out of scope The constant is a calibration decision with its own data (150d1f2d0290b), so it is left untouched and the description says so in one clause. Stated here rather than silently, so the omission is not read as an oversight.
3 💡 Over-broad exclusion: contains_excluded_stack_frame matches any frame of a stack, so everything allocated under thread attach, detach or the ThreadStatus constructor is now dropped DISAGREE that it is over-broad, blast radius measured Bounded from source, not by sampling: every allocation of this state is reached from initPerformanceCounters(), whose only caller is attachToGroupImpl (ThreadStatusExt.cpp:416), or from finalizePerformanceCounters() under detachFromGroup (:443); the thread_local ProcfsMetricsProvider is built on the first stats_getter() call inside TasksStatsCounters::reset(), always under the attach path. finalizePerformanceCounters() is also reachable from executeQuery.cpp:740/936/1072 with no attach frame, but early-returns unless last_rusage->thread_id != 0, which only initPerformanceCounters sets. Magnitude: largest excluded row 1,536 B, worst per-scenario excluded total 2,624 B against a 30,776 B baseline, on scenarios whose baselines span 96 B to 11.6 MB. An injected 64 KiB-per-table allocation is still reported at full size, and 0 of its stacks match the new prefixes.

Two consequences accepted and stated rather than left to be discovered:

  • The cluster's rows leave the HTML report too, one continue feeding both the verdict and stack_diffs.
    That is how the profiler's own dumpProfile overhead is already handled.
  • A regression in per-thread accounting state itself is no longer measured here, and no threshold could
    have measured it: Read an opaque Variant alternative back from Arrow #120702 at b48703670359 has rows for 04_add_projection.sql at both 528 and 1,056,
    the same commit measured twice with different answers. Its size tracks pool scheduling, not storage code.

Controls verified rather than read off their summaries: the negative-control sweep is md5-identical to the
unpatched sweep and differs from the patched one; the parser-lane digests are byte-identical over 100
queries (total heap_diff 205,064 both ways) with a sensitivity arm proving that oracle can see an
exclusion; and the two local numbers that cut against the change (05_multiple_tables pairwise FAILs 110
to 118, on a debug build whose own noise floor is 62 KB there) are reported in the evidence rather than
dropped.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per
finding.

@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One set of heap dumps analysed by the shipped code twice, with and without the 3 prefixes: the difference is a whole multiple of 528 B in all 40 03/04 windows of 20 runs. Liveness asserted first (4.22e4-4.50e4 sampled stacks per dump, 380 dumps all md5-distinct), so an empty-profile false zero is excluded.
b Root cause explained? Yes. ThreadGroupSwitcher attach constructs thread-local counter state (TasksStatsCounters, ProcfsMetricsProvider, 2x __cxa_thread_atexit_impl) that lives until the thread exits; GlobalThreadPool keeps its threads, so the measurement is how many pool threads have ever served the scenario. 7 stacks, 528 B per thread; #120702@b48703670359 shows 528 and 1,056 for the same commit.
c Fix matches root cause? Yes, at the author's own seam: compute_diff already drops an excluded stack before total += diff. No threshold moved (STORAGE_CHANGE_THRESHOLD_BYTES untouched: the 10x bump 150d1f2d0290b made for this mechanism was cleared by two units in three days), no pass count changed, no scenario weakened, no C++.
d Test intent preserved / new tests added? Yes. With the fix in place an injected 64 KiB-per-MergeTree-table allocation is still reported at full size: +65,632 on 01 and +131,072 on 05 both FAIL 9/9 arm pairs, 07 reads exactly +65,536. No tests/queries file applies; the substitute run is 20x9x3 = 540 measured windows.
e Both directions demonstrated? Yes, three ways. Reverting only the 3 prefixes reproduces the pre-fix sweep byte-for-byte and differs from the post-fix one; excluded rows leak 0 with the fix vs 3/57/102 without, across cross-version rows, stack rows and flamegraph inputs; and a prefix that does occur in the parser lane takes its total 205,064 -> 0, proving that lane's no-op result is not a dead oracle.
f Fix is general across code paths? Yes. The prefixes key on the allocation site, not on a pool, setting or scenario, so all four affected scenarios and every pool go at once. All 9 carriers enumerated: the gated total, the report rows, the cross-version diff and both flamegraph inputs inherit the same continue; the pr-async-no-cache run is never diffed; the C++ alternatives (quiesce-wait, pin the pools) are refuted by the stack evidence, since this state is registered with __cxa_thread_atexit_impl and no task-completion wait frees it.
g Fix generalizes across inputs? Type wrappers N/A, no engine code changed. Measured over the input space that exists: 9 scenarios x 20 runs x 3 analyzer states, the 36 scenario measurements of 4 production reports, 100 parser-lane queries, 9 probe-arm pairs. The four scenarios with no thread attach excise exactly +0 in all 20 runs.
h Backward compatible? Yes, vacuously: no setting, no SettingsChangesHistory.cpp, no serialization format, no product code path, no release-branch exposure. Both arms of one run are analysed by the same script from this checkout, so there is no transition window (the master arm binary is downloaded from the merge base, which is why a C++-side fix would be asymmetric).
i Invariants and contracts preserved? Yes. Same matcher, longer list; contains_excluded_stack_frame's docstring widened to match what the list now holds. compute_diff still returns total as the sum of exactly the kept rows, so verdict and report stay consistent by construction rather than by a second filter. No concurrency, lock or error path is touched.

Session id: cron:clickhouse-impl-slot-5:20260921-105900

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Sep 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e3acd7f]

Summary: ✅


AI Review

Summary

This PR narrows the shared heap-profile exclusion logic used by the Storage memory check so thread attach/detach/startup bookkeeping is not charged to whichever storage scenario happened to touch a pooled worker first, and it updates the storage-profiler README to describe that behavior. I did not find a remaining correctness, safety, or evidence gap in the current patch.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 21, 2026
@groeneai
groeneai requested a review from qoega September 21, 2026 13:52
@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 23, 2026
Merged via the queue into ClickHouse:master with commit 482d2dd Sep 23, 2026
176 of 349 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 23, 2026
aparajita31pandey pushed a commit to aparajita31pandey/ClickHouse that referenced this pull request Sep 27, 2026
…scenario

Every MergeTree table's BackgroundJobsAssignee keeps running
StorageMergeTree::scheduleDataProcessingJob on the schedule pool, and a pass
with nothing to merge still builds a merge predicate, a parts collector and
ranges (~1.3 KB in the release profiler binary) that it frees on return. The
storage profiler dumps the heap as soon as a scenario file returns, so a pass
running at that dump on one arm is charged to that scenario and credited back
at the next one: a conserved adjacent pair. `06_dictionary.sql` has an 80 KB
baseline, so one pass clears both the 1,024-byte and the 1 % bar. Production
reports on trees that already contain ClickHouse#120487 and ClickHouse#121364: ClickHouse#122127 `06`
+1,296 and ClickHouse#120444 `06` +1,184, each exactly the rows of one selection pass,
with `07` the same rows negated.

Stop merges on each scenario table once nothing merges or mutates it any
more, as ClickHouse#119706 did for `test_many_parts`: on `test_mt` after its last
mutation at the end of `04`, and on `test_mt_2` / `test_mt_3` right after
their CREATE in `05`. With the blocker set, scheduleDataProcessingJob returns
before selectPartsToMerge. After `mutations_sync = 2` returns, the mutation
task is in NEED_FINISH, which has no cancellation check, so the STOP in `04`
aborts nothing. Both arms of a run read this checkout's scenario files, so the
change is symmetric from the first run. `test_mt` stays exposed in `01`..`03`,
where it must merge and mutate.

Validated locally with one Debug build (no C++ in the diff): a clickhouse
local probe of `01`..`05` counts 26-30 selection ranges in a 6 s idle window
without the change, 0 with it, and 9-10 with any one STOP removed; with a
1,000-partition probe table, profiler dumps catch a selection pass in flight
in 10 of 20 dumps without its STOP and 0 of 20 with it; a real +64 KiB
allocation in `06` still FAILs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding manual approve Manual approve required to run CI 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