Skip to content

Warm up the parser before measuring AST allocations in the parser memory profiler - #115739

Merged
qoega merged 1 commit into
ClickHouse:masterfrom
groeneai:warmup-parser-memory-profiler
Aug 21, 2026
Merged

qoega merged 1 commit into
ClickHouse:masterfrom
groeneai:warmup-parser-memory-profiler

Conversation

@groeneai

@groeneai groeneai commented Aug 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):

...

Description

Since 2026-08-20 Parser memory check has failed 5 PRs across 154 test rows, every row reporting
exactly +1,280 bytes: #115301 (37 queries), #114577 (37), #110180, #115630 and #100371 (2 each).
None touches the parser. The same window credits 8 further PRs with the mirror-image -1,280 B
improvement, so the check can both fail innocent PRs and pass one adding a genuine 1,280 byte
regression.

The cause is in the instrument. parser_memory_profiler parses one query per process with no
warm-up, so lazy one-time initialization reachable from parseQuery is charged to that query:
2,400 bytes over five allocations on Query 64. The largest is one 1,280 byte calloc during
the first call into the expression parser (ParserExpressionImpl::tryParseOperand), whose two leaf
frames sit in a shared object absent from the executable's symbol table, so the profiler leaves them
unresolved. Whether these land inside the window is a property of the binary, not the SQL, so the two
arms, being different builds, can differ by the whole amount with identical parser source, which
clears both thresholds (1,280 B, 34.7%).

Parsing once before the window opens leaves only this parse's allocations. With the job's own
analyzer on Query 64: 4,968 -> 2,568 bytes, the 1,280 byte stack present to absent, reverting
restores it. Over all 100 queries it appears on exactly 64 and 99 before, none after; an injected
per-parse 4,096 byte allocation still reports +4,112 B, so the check is not blind.

@ qoega, two consequences to rule on. Reported values drop for 37 of 100 queries, and for about one
master build a warmed PR arm is scored against an unwarmed baseline, inflating apparent
improvements; that self-heals and I added no compensating logic. New expensive lazy initialization
is also no longer visible here, which fits a per-query AST check.

Related: #113491
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115630&sha=042aecf702d2050e274706aa20011eabedb78542&name_0=PR&name_1=Parser%20memory%20check

Query 64: the 2,400 bytes of one-time initialization, by allocating frame

Multiset of per-stack byte diffs removed by the warm-up, attributed to the allocator frame that
actually appears in the symbolized heap (not to an inlined neighbour):

bytes allocator initialization
1,280 je_calloc / __libc_calloc, two unresolved shared-object frames during the first call into ParserExpressionImpl::tryParseOperand
608 operator new / unordered_set::insert isIntegerTypeName static set (ParserDataType.cpp)
224 operator new / unordered_set::insert isArrayQuantifierPredicate static set (ExpressionListParsers.cpp)
192 operator new / unordered_set::insert isIntegerTypeName, second allocation
96 operator new / unordered_set::insert isArrayQuantifierPredicate, second allocation

The 7 element isArrayQuantifierPredicate set and the 19 element isIntegerTypeName set match
sizeof(__hash_node<string_view, void*>) = 32 bytes per element (224 and 608), which is why the
1,280 byte calloc is not attributed to either of them.

The two unresolved frames do resolve against the profile's own MAPPED_LIBRARIES, and on this host
they are glibc's atexit registration: libc.so.6 is mapped at 0x74e6aae00000, and the offsets
0x470bd / 0x47231 land in __new_exitfn and __cxa_atexit+65. The callee at 0x470b8 is
calloc(1, 0x410), i.e. one 1,040 byte struct exit_function_list, which jemalloc rounds up to its
1,280 byte size class. That is allocated once, when the first function-local static with a
non-trivial destructor inside the parser registers it. The same two frames below main in that stack
resolve to __libc_start_main, which is how the offsets were checked. The exact figure is a property
of this glibc, so the profiler is right to leave it unnamed; the point that matters here is only that
it is one-time.


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

Version info

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

…ory profiler

parser_memory_profiler parses exactly one query per process with no warm-up, so
every lazy one-time initialization reachable from parseQuery is charged to that
query's AST allocation. On Query 64 of test_queries.txt that is 2,400 bytes over
five allocations. The largest is a single one-time 1,280 byte calloc made during
the first call into the expression parser
(DB::ParserExpressionImpl::tryParseOperand); its two leaf frames are in a shared
object and absent from the executable's symbol table, so the profiler reports
them unresolved. The other four are the function-local static sets in
isIntegerTypeName (src/Parsers/ParserDataType.cpp, 608 and 192 bytes) and
isArrayQuantifierPredicate (src/Parsers/ExpressionListParsers.cpp, 224 and 96
bytes), which allocate through operator new and unordered_set::insert.

Whether that initialization lands inside the measured window is a property of the
binary rather than of the SQL, and Parser memory check compares two different
binaries (a downloaded master build against the PR build), so the two arms can
differ by that whole amount while the parser source is identical.
parser_memory_check.py then scores the difference as a per-query regression:
1,280 > 100 bytes and 34.7% > 1%, which always fails. Since 2026-08-19 this has
failed 5 PRs across 117 test rows, every one of them reporting exactly +1,280
bytes and none of them touching the parser, while 8 other PRs in the same window
were credited with the mirror-image improvement.

Parsing the query once before the window opens restores the property the check
rests on, namely that the window contains only allocations of the parse itself.
Measured with the job's own analyze_heap_profiles on Query 64: 4,968 to 2,568
bytes, the 1,280 byte stack present to absent, and reverting restores it exactly.
Over the full 100 query corpus the stack appears on exactly queries 64 and 99
before the change and on none after, with no errors on either arm. An injected
per-parse 4,096 byte allocation is still reported as +4,112 bytes, so the check
still catches a real regression.

The warm-up deliberately does not catch exceptions: it parses the same text as the
measured parse, so an invalid query throws here first and the existing handler
still renders it as an error result. Reported values legitimately drop where
one-time initialization leaves the window; both arms are measured the same way, so
comparisons are unaffected.

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 Aug 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 open blockers)

Reviewed cold against the resulting code by an independent model, then adjudicated. Round 1 bounced
1 blocker and 2 majors; round 2 is clean. No behaviour change was requested in either round: the
9-line diff is byte-for-byte what round 0 produced, and I verified the code is token-identical.

❌ Blocker (round 1, fixed): the named carrier was the wrong allocation. The first draft said
the 1,280 bytes came from the function-local static in isArrayQuantifierPredicate. It does not.
The allocating frames are je_calloc / __libc_calloc, while both static sets allocate via
operator new -> unordered_set::insert, and node arithmetic settles it independently:
sizeof(__hash_node<string_view, void*>) is 32 bytes, so the 7-element set is 224 bytes (observed
224) and the 19-element isIntegerTypeName set is 608 (observed 608). The symbolizer joins an
inlined group onto one address, so tryParseOperand--isArrayQuantifierPredicate reads as if the
latter allocated. The published text now names no ClickHouse symbol as the allocating frame.

⚠️ Major (round 1, fixed): undercounted breadth. The draft said 3 PRs; CIDB gave 4 that day and
5 to date. Corrected, and re-run at publish time: 154 rows / 5 PRs, every row exactly +1,280 bytes.

⚠️ Major (round 1, fixed): provenance not rendered. The only Related: line sat inside the
template's HTML comment. Now visible, with a canonical report URL.

💡 Nit (round 2, folded in): the two unresolved frames are identifiable. They resolve against
the profile's own MAPPED_LIBRARIES to glibc's atexit registration: calloc(1, 0x410) for one
struct exit_function_list, which jemalloc rounds to its 1,280-byte size class. Offsets were checked
against a control (the frames below main resolve to __libc_start_main). Added to the collapsed
block; the figure is a property of this glibc, so the description keeps the profiler-truthful
wording.

Two nits were disagreed with, on evidence. The sample stdout numbers in the profiler's header doc
are stale, but that block documents the 4-field output format, which is unchanged, and those
absolutes were always build-specific. The other concerned fleet-internal scratch files, not the diff.

I re-derived the numbers rather than accepting them: re-ran the job's own analyze_heap_profiles on
the raw heaps (base 4,968 with the carrier stack, warm 2,568 without, revert restores 4,968), and
confirmed the 2,400-byte removal decomposes as 1,280 + 608 + 224 + 192 + 96, all one-time, with
ParserStorage's per-parse 96 bytes surviving. The blindness arm still reports an injected per-parse
4,096-byte allocation as +4,112, so the check is not made blind.

Gate: 2 rounds, findings 1 then 0, $28.10 total.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-examples parser_memory_profiler --profile=... on Query 64 with the job's MALLOC_CONF (prof:true,prof_active:true,prof_thread_active_init:true,lg_prof_sample:0), diffed by importing the job's own analyze_heap_profiles. Fixed value, not a rate: heap_diff = 4,968 with exactly one 1,280 byte stack, identical on 5 of 5 runs.
b Root cause explained? Yes. parser_memory_profiler parses one query per process with no warm-up, so lazy one-time initialization reachable from parseQuery falls inside the measured window: 2,400 B over five allocations on Query 64. The largest is a single one-time 1,280 byte calloc made during the first call into the expression parser (ParserExpressionImpl::tryParseOperand); its two leaf frames are in a shared object and absent from the executable's symbol table, so the profiler reports them unresolved. The other four are the static sets in isIntegerTypeName (608 + 192 B) and isArrayQuantifierPredicate (224 + 96 B), each allocating through operator new / unordered_set::insert. That is a property of the binary, not of the SQL, and the check compares a downloaded master build against the PR build, so the arms can differ by the whole amount with identical parser source. parser_memory_check.py:1322 then scores it: 1,280 B > 100 B and 34.7% > 1%, so always FAIL.
c Fix matches root cause? Yes, at the instrument's own claim: the profiler advertises this query's AST allocation and measured process initialization too. Not a widened bound, not a threshold change, not a per-symbol suppression list, not a defensive mask.
d Test intent preserved / new tests added? Preserved and strengthened: with the warm-up in place an injected per-parse 4,096 byte allocation is still reported as +4,112 B (+160%), which the thresholds flag. Nothing is removed or weakened. No new automated test: the change is to a CI-only example binary with no test harness, and the meaningful assertion is the CIDB observation that the +/-1,280 cohorts go to zero.
e Both directions demonstrated? Yes, each on a Build ID verified binary. Pristine heap_diff = 4,968 with 1 carrier stack; with the fix 2,568 with 0; negative control (reverted and rebuilt) back to 4,968 with 1. The control rebuilt to the pristine Build ID bit for bit.
f Fix is general across code paths? Yes. The fix is at the single point where the measurement window opens, so it covers every lazy initialization reachable from parseQuery generically rather than by name. Measured: it removes five distinct one-time-init stacks totalling 2,400 B across three parser subsystems, not only the one that was hunted. Both arms of the comparison are covered because the warm-up lives in the profiler source, so each arm's own binary warms itself.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured over the whole 100 query corpus of test_queries.txt (DDL, SELECT, joins, subqueries, TTL, MATERIALIZED/ALIAS/DEFAULT columns): 100 of 100 succeed on both arms, no errors, no negative values, minimum heap_diff 440, and 100 of 100 identical on a repeat run. Empty input is rejected before the warm-up; an unparsable query throws in the warm-up exactly as in the measured parse.
h Backward compatible? (maintainer-approved exception only) Yes, nothing to break. src/Parsers/examples/ is a CI-only example binary: no server code, no settings, no formats, no serialization, so no SettingsChangesHistory.cpp entry applies. The stdout contract (query_length, before, after, diff) and the --profile / --symbolize / --symbolize-batch file layout are untouched, so parse_symbolized_heap, analyze_heap_profiles, compute_diff, compute_cross_version_diff and the report builders parse unchanged, exercised 100 times per arm.
i Invariants and contracts preserved? The invariant is that the measured window holds only allocations attributable to this parse. The warm-up sits before resetProfiler(), so it perturbs neither the profiler reset, nor the before/after dumps, nor the flushJemallocThreadCache() / refreshJemallocEpoch() pair, and its AST is destroyed before the window opens. Exceptions deliberately propagate: run_profiler_collect_heap turns a nonzero exit into an error that main renders as Result.Status.ERROR, so a failing query is still reported. Swallowing would have hidden a real failure and allowed a partially initialized state to be measured.

Session id: cron:clickhouse-impl-slot-7:20260820-192200

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6b3f31b]

Summary: ✅


AI Review

Summary

This PR adds a warm-up parse ahead of the measured window in parser_memory_profiler, so the parser-memory CI check stops charging one-time parseQuery initialization to the query under test. I reviewed the nine-line change against the current implementation, the CI consumer in ci/jobs/parser_memory_check.py, and the linked failing parser-memory report; I did not find a correctness, safety, or rollout problem that merits a code change.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @qoega @leshikus, could you review this? parser_memory_profiler parses one query per process with no warm-up, so lazy one-time initialization reachable from parseQuery lands inside the measured window and is charged to that query; since the check compares two different builds, the two arms can differ by the whole amount with identical parser source, which is the constant +1,280 bytes currently failing 5 PRs that do not touch the parser. Parsing once before the window opens leaves only this parse's allocations, and an injected per-parse allocation is still reported, so the check does not go blind.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6b3f31bee with master 590a91de6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 577afb433; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.54 MiB 701.49 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

8 translation units recompiled, 40 s compile time in total, 8 of them have a recent master baseline.

Job report

@qoega
qoega added this pull request to the merge queue Aug 21, 2026
@qoega qoega self-assigned this Aug 21, 2026
Merged via the queue into ClickHouse:master with commit b4fb542 Aug 21, 2026
184 of 186 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 19, 2026
…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]>
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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