Skip to content

Do not charge one-time process initialization to a Storage memory check scenario - #120487

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:storage-memory-check-unmeasured-warmup-pass
Sep 19, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:storage-memory-check-unmeasured-warmup-pass

Conversation

@groeneai

@groeneai groeneai commented Sep 16, 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

On 2026-09-16, its first day at PR-CI volume, Storage memory check failed on
8 of 140 PR heads, 9 rows. Six are the same 1,280 byte block, on
five unrelated PRs and three scenarios, none touching ci/, reported as +1,216 to
+1,392 with the job's documented jitter.

The job runs the sequence once per binary with no warmup, so a one-time
initialization first touched in window k is charged to k. It is a libc
calloc below a function-local static's first touch: glibc keeps __cxa_atexit
registrations in 32-entry blocks, and crossing a boundary allocates a 1,040 byte
struct exit_function_list, which jemalloc rounds to its 1,280 byte class. The two
binaries cross that boundary in different scenarios, so one window reports +1,280
and another -1,280; on the 8 KB 08_parts_analysis baseline that is 15.8%.

Fix: pass the scenario list twice to the existing --file option and measure only
the second pass. Same mechanism as #115739, which fixed this class in
Parser memory check. No threshold change, no stack filtering. In the job script,
not the profiler: the master arm binary comes from master, so a C++ change would
reach one arm only.

Validated locally, the change being Python only: the class is present unfixed, absent
with the fix, present again on revert. It does not blind the check, an injected
64 KiB-per-table regression still fails at +65,080. Cost, from the first run below:
scenario runs are 627 s of a 1,871 s job; symbolization, unchanged, 1,180 s.

The other 3 rows are a different magnitude (+4,208, +47,344, +528), out of
scope. A regression visible only on a path's first touch is now unmeasured,
the tradeoff #115739 accepted. No test is added, nothing runs a Python suite over
ci/; glad to add a shell-test assertion instead.

Failing runs:
03_add_secondary_indexes,
08_parts_analysis


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

Version info

  • Merged into: 26.10.1.163 (included in 26.10 and later)

…ck scenario

The job ran the 9-scenario sequence once per binary and diffed each
checkpoint-to-checkpoint window between the master and PR clickhouse-examples
builds. With no warmup, a one-time process initialization first touched inside
window k is charged entirely to window k, and two different binaries reach those
first touches after a different cumulative number of events, so the same
one-time cost lands in different windows on the two sides. One window then
reports a fixed positive offset and an adjacent one the same negative offset,
which is silently accepted as an improvement.

In the last 36 hours this failed 7 of 113 PR heads across five mutually
unrelated PRs, none of which touches ci/. On four of them the reported
regression was the identical constant +1,280 bytes on four different scenarios.

Identified at the frame level: the allocation is a calloc whose two unresolved
frames sit at libc addresses, outside the binary's own text, below the first
touch of a function-local static. glibc keeps __cxa_atexit registrations in
32-entry blocks, so the 33rd, 65th, ... registration callocs a fresh
struct exit_function_list of next(8) + idx(8) + 32 * sizeof(struct
exit_function)(32) = 1,040 bytes, which jemalloc rounds up to its 1,280-byte
size class and never frees. Against the 8 KB baseline of 08_parts_analysis that
offset is 15.8%, so it clears both the absolute (1,024 B) and the percentage
(1.0%) threshold and fails the job.

Run the sequence once unmeasured before the measured pass, by passing the
scenario list twice to the existing --file option and measuring only the second
pass, using the previous pass's final checkpoint as the baseline. By then every
path the scenarios exercise has initialized its statics and grown its pools, so
no first touch is left inside a measured window. This is the mechanism of
PR ClickHouse#115739, which fixed the same class in Parser memory check with a warmup
parse, adapted to a stateful profiler.

The change is in the job script rather than in the profiler because the master
arm binary is downloaded from S3 built from master: a new flag would make the
old master binary exit with Unknown option, and an unconditional C++ warmup
would give the PR arm a warm baseline while master stayed cold. A job-side
change applies to both arms in the same run from the same script, so it is
symmetric from the first execution and needs no transition window.

Deliberately not done: STORAGE_CHANGE_THRESHOLD_BYTES is untouched, no stack is
filtered, and the symbolized file count per arm stays at 10 so the dominant cost
of the job does not grow. Stack exclusion was rejected because the frames are
unsymbolized, leaving only "leading frames are ??" (which would blind the check
to every allocation inside any non-ClickHouse library) or "the delta is exactly
1,280" as keys. The latter is unsound beyond being a magic number: the same
window contains three further +1,280 rows that are ordinary operator new[] from
ThreadPoolImpl::scheduleImpl, so such a filter would hide real thread-pool
regressions.

Validated against three local clickhouse-examples builds. The class is present
without the fix (2 rows), absent with it (0), and present again on a fresh
unfixed run. It does not blind the check: with the fix in place, an injected
real 64 KiB-per-table allocation still fails at +65,080 bytes on
01_create_table, +132,016 on 05_multiple_tables and shows exactly +65,536 on
07_many_parts. Cross-arm, an antisymmetric +12,192 / -12,192 pair that was the
entire reported change of two adjacent windows collapses to +40 / -40, and five
windows go to exactly zero.

The sequence is re-runnable, which the second pass depends on: 09_cleanup.sql
drops all five objects the other eight scenarios create, and all six two-pass
runs across the three binaries exited 0. If a future scenario leaves an object
behind, 01_create_table.sql's plain CREATE TABLE makes the profiler exit
non-zero and the job report ERROR rather than mis-measure. The README records
that contract for the next scenario author.

Cost: the master and PR scenario runs are doubled while the download, the
single-scenario pr-async-no-cache run and all symbolization are unchanged.
Sized from CI data, where the download plus all three profiler runs occupy
10m27s of a 1,807 s job, the estimate is roughly +8 minutes.

A regression that manifests only on the first touch of a code path is now
charged to the unmeasured pass and no longer reported. This is the same
tradeoff PR ClickHouse#115739 accepted and the correct one for a check whose subject is
per-scenario storage memory.

Related: ClickHouse#119480
Related: ClickHouse#115739

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 16, 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; 2 gate findings + 5 from my own cold
review; bounded: 1 full pass, 0 fix rounds needed).

# Sev Finding Verdict Evidence / action
1 ⚠️ No discriminating proof that the unmeasured pass suppresses the reported allocation while preserving second-pass detection; no test covers the duplication and slicing (ci/jobs/storage_memory_check.py:205-221) DISAGREE on the proof, DECLINE the in-tree test Measured on one binary through the real analyze_heap_profiles, liveness asserted first (42,155-44,667 sampled stacks/dump): unfixed 2 class rows / fixed 0 across all 9 windows / fresh unfixed run 2 again, same callers and windows. Detection preserved, measured with the fix in place: an injected +64 KiB per MergeTree table still FAILs at +65,080 (01, one table), +132,016 (05, two) and reads exactly +65,536 (07). Test declined as disproportionate: a faithful oracle needs a profiling build, a downloaded master artifact, 18 scenario runs and symbolization, i.e. a second job duplicating this one. The shell-test offer stands in the description.
2 ⚠️ The description's incidence counts did not match CIDB and did not add up ("7 of 113 heads", "four ... the same constant +1,280", "2 of the 7 ... a different class") AGREE, fixed in the description Re-measured: for check_start_time >= 2026-09-16 00:00:00, 140 heads, 8 failing heads, 9 failing rows. Six rows are one 1,280 byte block plus the jitter the job documents (+1,216..+1,392), on five unrelated PRs and three scenarios; three are a different magnitude.
3 💡 Incidence stated as a relative window ("in the last 36 hours") rather than a date AGREE, fixed in the description Replaced with the dated window above. Code content unchanged, so no re-gate.
4 💡 Cost given as an estimate where the carrier job log measures it AGREE, fixed in the description From that log: 627 s of scenario runs and 1,180 s of symbolization in a 1,871 s job.
5 💡 This PR's own Storage memory check run is not evidence the class is fixed AGREE, recorded With no C++ in the diff both arms are the same code and cross the __cxa_atexit boundary identically, so the pair cancels either way; measured directly, unfixed same-binary and unfixed one-extra-static comparisons both report 0 class rows. The run does prove the doubled sequence resolves all 19 labels, stays inside the 1800 s subprocess timeout and still renders the report, and it tests the duration claim.
6 💡 Both passes share the process-wide, path-keyed mark and index caches, and a recreated table reuses the previous path and part names while holding different bytes DISAGREE, carrier verified safe DatabaseMemory::dropTable is synchronous and part removal calls IMergeTreeDataPart::clearCaches(), evicting marks, index marks and the primary index for every removed part; no pass-2 read can hit a pass-1 entry. This is the invariant that makes running the stateful sequence twice in one process legal.
7 💡 Residual run-to-run noise is not removed, only reduced Noted, not blocking Local debug floor drops from 12,208 B to 3,824 B and four windows go to exactly 0; in CI the non-1,280 residual never exceeds 176 B across the 27 measured windows, well under the 1,024 byte bar. No determinism is claimed.

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

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Sep 16, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 16, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. analyze_windows.py over one local clickhouse-examples reports CLASS_ROWS_TOTAL=2 on demand (+1,280 in 01_create_table and in 03_add_secondary_indexes, both ??-topped) on two independent runs, liveness asserted first at 42,155-44,667 sampled stacks per dump.
b Root cause explained? Yes. With no warmup, a one-time initialization first touched in checkpoint window k is charged entirely to k: the 1,280 bytes are a calloc at libc addresses below a function-local static's first touch, where glibc's 32-entry __cxa_atexit block allocates struct exit_function_list = 1,040 B, rounded by jemalloc to its 1,280 B class and never freed; the two arms are different binaries, so they cross that boundary in different scenarios and storage_memory_check.py:308-318 fails any window whose baseline is small enough for pct > 1.0.
c Fix matches root cause? Yes, at its source: the first touch is moved out of every measured window. No bound widened (STORAGE_CHANGE_THRESHOLD_BYTES untouched), no stack filtered, no opt-out, no dataset shrunk; a delta == 1280 filter was rejected because window 01 also has three ordinary operator new[] rows of that size from ThreadPoolImpl::scheduleImpl.
d Test intent preserved / new tests added? Yes, measured with the fix in place: an injected 64 KiB per MergeTree table still FAILs at +65,080 (01, one table), +132,016 (05, two) and reads exactly +65,536 (07). No test file is added because nothing in the repo runs a Python suite over ci/; glad to add a tests/queries/0_stateless/*.sh assertion instead.
e Both directions demonstrated? Yes, same command each way: unfixed CLASS_ROWS_TOTAL=2, fixed 0, then a fresh unfixed run 2 again as a negative control.
f Fix is general across code paths? Yes, all six carriers of the invariant enumerated: the sibling Parser memory check already carries the remedy (#115739, verified present on this HEAD), the pr-async-no-cache run is excluded because it is PR-binary only and never diffed against master, and no other job diffs two clickhouse-examples binaries.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers N/A, no engine code changed. The fix doubles whatever SCENARIOS_DIR.glob returns and the label formula stays unique for any list, verified for the current 9 scenarios (18 unique labels, measured slice after_09_09_cleanup..after_18_09_cleanup mapping 1:1) and by arithmetic for general n; both first-touch sub-mechanisms seen in the dumps are covered.
h Backward compatible? Yes. No setting, no SettingsChangesHistory.cpp, no serialization format, no new CLI flag, no artifact contract change, and the downloaded master binary needs no new option, which is precisely why the change is in the job script; the job digest (ci/defs/job_configs.py:2026-2037) already covers both changed paths.
i Invariants and contracts preserved? Yes. find_heap_profile's single-match assertion still holds (18 unique labels, verified against the real run_scenarios formula), the measured slice is exactly baseline + 9 files, cleanup_heap_profiles still removes both passes' dumps, timeout=1800 is unchanged and a doubled release pass stays well inside it, and the error paths short-circuit before any slice is used.

Session id: cron:clickhouse-impl-slot-40:20260916-202504

@groeneai
groeneai requested review from maxknv and qoega September 16, 2026 23:22
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [53ee9e9]

Summary: ✅


AI Review

Summary

This PR changes ci/jobs/storage_memory_check.py to run the storage scenario sequence twice and analyze only the second pass, so one-time process initialization does not get charged to an arbitrary scenario window. I traced the new heap_files[len(scenarios):] slice against the profiler's checkpoint naming in src/Examples/storage_memory_profiler.cpp, checked the current scenario cleanup contract in utils/storage-memory-profiler/scenarios, and did not find a correctness or CI-contract regression in the current code. The PR metadata is also consistent with the actual change, and the PR's Storage memory check CI job is green.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-ci comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). labels Sep 16, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 5ffb141 Sep 19, 2026
177 of 350 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 19, 2026
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Sep 23, 2026
…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]>
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.

3 participants