Skip to content

Bound a performance comparison profile run by the profiling budget it was given - #117447

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:bound-perf-profile-run-by-profiling-budget
Sep 3, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:bound-perf-profile-run-by-profiling-budget

Conversation

@groeneai

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

Not required (CI only).

Description

Performance Comparison shards go red although no query regressed: in the three days to
2026-09-01, 17 reds over 7 shards and both architectures, spanning 10 unrelated pull requests,
this one, and master, every one reporting 10 errors (that plural is a separate
miscount, #116491). The check hides the regressions it exists to report.

The failure is in the profile run after a query's measured runs, whose only product is
flame-graph stacks. perf.py declares a per-query profiling budget (--profile-seconds, 10 in CI)
but checks it only between runs, and its profile settings set no max_execution_time. Profile
runs are not measured, but they are budgeted: allocation sampling makes such a query orders
of magnitude slower, so the only bound left is the server's 300 s cap, and reaching it raises
TIMEOUT_EXCEEDED out of the script. One group_by_dynamic_keys query spent 417 s against that
budget.

This enforces the budget per run and treats reaching it as the end of profiling, not an error. The
catch is narrowed to that error code, so every other failure still aborts. Both servers
truncate at the same bound and still report a profile row, which joins their trace_log samples
into the report; today those samples are dropped and the differential flame graph is a stub.

On a two-server rig that profile run costs 20x its measured time, matching CI's 22x on the master
arm. Before, it exits with Code: 159; after, clean, reporting every query. Removing either half
alone still fails. Nothing is truncated across five other fixtures; the job's 749 runs have
p99 = 1.18 s and one over 10 s.

Two other conditions share this signature, out of scope: release_base shards failing in the
setup thread pool, and the default.checks row collapse since 2026-08-30 (observability only).

Related: #116057 (no open issue).
Failing report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116057&sha=f44965677e97c8f207eef1685f9c42484dc65c75&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29


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

groeneai and others added 3 commits September 1, 2026 01:05
… was given

Performance Comparison shards go red with "N errors" although no query
regressed: about 15 reds over 13 unrelated pull requests in three days,
across 7 shards and both arches. A red on an unrelated pull request is a
check hiding the regressions it exists to report.

The failure is in the profile run that follows a query's measured runs,
whose only product is flame-graph stacks, so it cannot regress anything.
perf.py declares a per-query profiling budget (--profile-seconds, 10 in
CI, ci/jobs/scripts/perf/compare.sh) but tests it only between runs, and
the settings dict for those runs sets no max_execution_time, under a
comment asserting that dedicated profile runs are not timed. That premise
is the defect: the runs are not measured, but they are budgeted. Sampling
one allocation in ten (memory_profiler_sample_probability, plus
jemalloc_enable_profiler) multiplies an allocation-bound query by one to
two orders of magnitude, so the only bound left is the server profile's
300 s max_execution_time, and reaching it raises TIMEOUT_EXCEEDED out of
the script. One group_by_dynamic_keys query spent 417 s of profile time
against a declared 10 s budget and ended the run; the measured runs of
that same query were healthy and 5.6% faster on the tested arm.

Enforce the declared budget on each profile run, and treat reaching it as
the end of profiling for that query instead of an error. The catch is
narrowed to TIMEOUT_EXCEEDED, so every other failure still aborts as
before. The conn loop is deliberately not broken out of, so both servers
truncate at the same bound; both still emit a profile row, which is what
joins their trace_log samples into the report. Those samples are real (a
truncated run left 2.77M MemorySample entries under its query_id) and are
dropped today only because the row was never printed, which is why the
shard's differential flame graphs are degenerate 579-byte stubs. Emitting
profile-total again also lets compare.sh debit the global profile budget
for time that is actually spent.

Measured on a local two-server rig, one binary, arms made unequal so the
profile block is actually entered: the profile run of that query costs
20x its measured time (5.45 s -> 109.18 s), matching the 22x observed in
CI on the master arm, so the amplification is not caused by any pull
request. Before, the run exits non-zero with Code 159 at the same frame
as the CI artifact and loses two of three queries; after, it exits clean,
reports all three, and truncates at the bound. Removing either half of
the change alone still fails: without the bound the runs stretch past the
server cap (profile-total 32.3 s -> 70.06 s), and without the catch the
check stays red, only sooner. Across five other fixtures nothing is
truncated, matching the failing job's own distribution of 749 profile
runs with p99 = 1.18 s and exactly one run over 10 s.

Truncated runs overshoot the bound by 58-65% rather than a few percent,
because max_execution_time is checked between processing steps and one
step is expensive under allocation sampling; the same granularity gave CI
a 9.8% overshoot at 300 s. The worst case is still bounded per query
instead of 2 x 300 s.

Co-Authored-By: Claude Opus 5 <[email protected]>
The sentence added by the previous commit reads as if `--profile-seconds`
bounded a whole profile run, but it bounds each statement:
`execute_query_group` issues one `connection.execute` per statement with the
same settings dict. A query item made of several statements can therefore take
a multiple of the budget, as TPC-DS Q14 in `tests/performance/tpcds.xml` would,
its `query_14.sql` splitting into two statements. This is the granularity
`--max-query-seconds` and `--prewarm-max-query-seconds` already have, so only
the wording changes.

Co-Authored-By: Claude Opus 5 <[email protected]>
The profiling budget (`--profile-seconds`) reaches the server as
`max_execution_time` on every `connection.execute`, and `execute_query_group`
issues one such call per statement, so the bound applies to each statement and a
query item made of several statements can take a multiple of it. The comment
above the setting still promised the budget for the whole query, contradicting
the README sentence added in the previous commit.

A reviewer raised this twice, once against the README and once against the
comment, so both now carry the same wording. The literals in the two other
comments this branch adds are backticked to follow the repository style rule.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

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

Pre-publication review over three rounds by an independent model (engine: codex; 4 findings in
round 1, 2 in round 2, 0 in round 3 on the full scope), plus 7 from my own cold reviews of the
resulting code, each done before reading the author's evidence.

# Sev Finding Verdict Evidence / action
1 ⚠️ Code 159 also covers lock, dictionary-loading and other timeouts, so the handler could absorb a foreign error and let the test continue DISAGREE The claim needs a foreign 159 raised before the budget expires. Its own primary cited site cannot: getLockTimeout (src/Storages/StorageFile.cpp:1484-1491) clamps the lock wait to max_execution_time, so under this change that throw can only fire at the budget. The other site reads load_timeout from a dictionary's own config, and no performance test sets it. A profile run is also reached only after the measured runs of the same query have all succeeded on that server, and those re-raise. Answered by measurement rather than a guard: finding 3
2 ⚠️ A multi-statement profile run gets a fresh full budget per statement, so the run is not bounded by the promised budget AGREE (fact), remedy substituted True, and tpcds.xml Q14 is a real two-statement item. I did not thread a deadline through execute_query_group: --max-query-seconds and --prewarm-max-query-seconds have identical per-statement semantics, so changing it for one of three callers would leave the other two inconsistent. Fixed where it was actually wrong, in the prose
3 ⚠️ No reviewable proof that the timeout path stays live end to end while non-budget failures stay fatal AGREE in part Five of six sub-asks were already measured and the reviewing model could not see them: both arms emit a profile row for a truncated run, profile-timeout appears, later query indexes still report, and both halves of the change redden separately when removed. The sixth was a real gap: the e.code != TIMEOUT_EXCEEDED re-raise had never been executed. Now exercised, with a positive control in the same session
4 ⚠️ Suppressing 159 also covers state-changing timed queries, so a partially completed INSERT or a scheduled mutation can leave the two servers with different data for the rest of the test file DISAGREE The mechanism is real and reachable: 48 of 588 files under tests/performance/ have state-changing timed items, and over 14 days sparse_grams_index_build measures p50 1137 ms, polymorphic_parts_l 1383 ms, codecs_float_insert 514 ms, so at the measured 20x amplification their profile runs do exceed a 10 s budget. That is what refutes the proposed remedy: re-raising for non-read-only groups restores the shard abort for exactly those files, re-creating the failure this change fixes for the class it is meant to protect. Either such groups can exceed the bound, and the remedy re-reds them, or they cannot, and the finding is unreachable. The skew also does not materialize in the worst-shaped fixture: sparse_grams_index_build.xml's timed INSERTs write sg_bloom_3_8 / sg_bloom_3_100 / sg_text_3_8 while its later timed SELECTs read sg_src, filled once by fill_query and written by no timed query. And profiling state-changing queries is pre-existing: the loop already re-executes such a query repeatedly until the budget elapses, on both servers; this change alters only whether one of those runs is truncated, and it is strictly more symmetric than before, since the old abort skipped the second server of that iteration entirely. Disclosed as a bounded residual, not fixed here
5 💡 The comment on the new setting still described a whole-query bound after the prose was corrected to per-statement (raised in both rounds) AGREE, fixed The comment now states the per-statement bound in the same words as the prose
6 💡 The related-pull-request reference used shorthand instead of a full URL on its own line AGREE, fixed Description updated
7 💡 The commit message leaves setting names and log literals unbackticked, against the repository rule that names commit messages AGREE, fixed forward The rule binds; the repository also forbids amending, so it is applied to the follow-up commit rather than by rewriting the first
8 💡 Three invariant carriers were verified but missing from the record AGREE, fixed Added, including the one that mattered most: a <constraints> entry on max_execution_time would have made every profile run abort, and there is none
9 💡 The added comments named classes and literals outside inline code blocks, against AGENTS.md AGREE, fixed Backticked
10 💡 For --profile-seconds above 300 the per-run cap is raised rather than lowered, because the query-level setting overrides the server profile DISAGREE Unreachable in every production invocation: compare.sh computes 10 or 0, the profile collector passes 0, the confirmation rerun passes 0 and the default is 0. The declared budget overriding the server default is also this file's own established semantics for prewarm and measured runs

| 11 | 💡 | The description said allocation sampling costs such a query "two orders of magnitude", after the README sentence had been corrected to "orders of magnitude slower" | AGREE, fixed | The measured arms are 22.2x (completed) and 88.1x or more (killed at the server cap, so a lower bound only), i.e. one to two orders, and the upper arm is not a number one may round. The description now carries the same phrase as the README |
| 12 | 💡 | The README's "on both servers alike" reads as "both truncate identically" rather than "the same bound applies to both" | DISAGREE | The clause immediately before it states the bound, which makes the intended reading the natural one; a third wording pass on one sentence is churn |

The breadth claim in the description was re-measured from scratch in each round rather than carried
forward: 17 reds, 7 shards, both architectures, 10 unrelated pull requests, this one, and one true
master run, every context beginning 10 errors. The distribution behind the last paragraph was
recomputed from the failing job's own archived raw output (749 profile runs, p99 1.18 s, exactly one
over 10 s), and the linked report was confirmed to resolve.

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

Session id: cron:clickhouse-review-slot-9:20260901-030900

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d6b78a]

Summary: ✅


AI Review

Summary

This PR bounds performance-comparison profile runs with max_execution_time and keeps the shard alive when profiling reaches that bound. That looks reasonable for read-only flamegraph collection, but the new timeout-as-nonfatal path also applies to state-changing benchmarks, so a timed-out profile run can leave the two servers in different partial states before later queries in the same test file execute. I do not think the change is ready to merge in its current form.

Missing context / blind spots
  • ⚠️ The current PR CI does not exercise Performance Comparison shards (gh pr checks shows them skipped without pr-performance), so the new timeout path is backed here by static review plus the author’s manual repro, not by current automation on this branch.
Findings
❌ Blockers
  • [tests/performance/scripts/perf.py:1167] TIMEOUT_EXCEEDED is now swallowed for every profiled SQL item, but the suite includes stateful benchmarks such as tests/performance/merge_tree_insert.xml (sequential INSERTs into the same table) and tests/performance/hashed_dictionary_load_factor.xml (SYSTEM RELOAD DICTIONARY before later dictHas queries). If one profile run times out, the harness keeps going with whatever rows, parts, or reload state each server managed to produce before the timeout. Because profiling only starts after a measurable left/right difference, the shared 10 s cap can leave different partial state on the two servers, so later queries in the same file are no longer measuring the same starting state.
    Suggested fix: apply the non-fatal timeout path only to read-only query groups, or skip profiling for mutating/stateful groups and keep the old abort behavior there.
Tests
  • ⚠️ Add the smallest harness-level repro you can keep around for this contract: one stateful benchmark with a later dependent query, and prove that a timed-out profile run does not let later measurements continue on partially mutated state. If an automated test here is impractical, document why and keep the timeout handling read-only-only.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Gate Answer
a Deterministic repro? Yes. Two servers from one binary, max_execution_time 30 s (a scaled stand-in for CI's 300 s), the right arm made systematically slower with max_untracked_memory=1 so the profile block is actually entered (it needs abs(relative_diff) >= 0.05 and pvalue <= 0.05; achieved +1.862 and 1.22e-06). Pristine perf.py fails on every attempt with ServerException: Code: 159 ... group_by_dynamic_keys.query0.profile0: Timeout exceeded: elapsed 32475.739 ms, maximum: 30000.000 ms at perf.py:1141 in execute_query_group - the same exception, frame and line as the CI artifact. Never "~1%".
b Root cause explained? The profile loop declares a per-query budget (--profile-seconds, 10 in CI, compare.sh:519/547) but tests it only between runs, and its settings dict sets no max_execution_time under a comment asserting profile runs "are not timed". They are not measured, but they are budgeted: memory_profiler_sample_probability = 0.1 plus jemalloc_enable_profiler multiply an allocation-bound query by one to two orders of magnitude, so the only bound left is the server profile's 300 s max_execution_time, and perf.py:1164-1168 re-raises the resulting TIMEOUT_EXCEEDED. A diagnostic step whose only product is flame-graph stacks therefore ends the run, and "errors" in the message fails the check at performance_tests.py:2374.
c Fix matches root cause? Yes: it enforces the budget the loop already declares, at the site that declares it, using that budget as the value so no new constant is introduced. Not a widened bound, not a no-random tag, not a shrunk fixture, not a defensive check - and the catch is narrowed to one error code, so every other failure still aborts.
d Test intent preserved / tests added? No test weakened and no fixture shrunk; group_by_dynamic_keys.xml is untouched because it guards the has_cheap_key_holder prefetch decision. There is no in-tree harness for perf.py, and the last five commits to it added zero test files, two updating a README instead; this follows that precedent with a README sentence plus the local two-server rig above.
e Both directions? Same command, both arms. Pristine: RC 1, 5537-byte -err.log, no profile row, no profile-total, and only query index 0 measured (1 and 2 never ran). Patched: RC 0, 0-byte -err.log, 44 profile rows, 4 profile-timeout rows, profile-total 64.74 s, and median/diff for all three query indexes.
f General across code paths? All nine invariant carriers enumerated, four settled by execution rather than citation: both servers of a run truncate at the same bound and both emit a profile row (the conn_index loop is deliberately not broken out of); shell items return before the block; multi-statement items are bounded per connection.execute; prewarm and measured runs keep re-raising on purpose, since a measured run that cannot complete invalidates the comparison; profile-total is emitted again so compare.sh:559-561 debits the global budget; the new profile-timeout key is inert against the real sed/awk programs; report.py never reads *-raw.tsv.
g Generalizes across inputs? The bound applies to every query kind that reaches the block. Boundary value --profile-seconds 0 measured: 0 profile rows, 0 profile-timeout rows, profile-total 4.8e-06, RC 0 - no degenerate zero cap, and the same mechanism makes the analyze-confirm rerun (--profile-seconds 0, compare.sh:1035) inert by construction. Truncation exercised on three fixtures and both arms.
h Backward compatible? Nothing engaged. No server-setting default changes, so no SettingsChangesHistory.cpp entry; no serialization or format change; no new experimental surface; no user-facing behaviour outside the CI performance harness. --profile-seconds keeps its meaning and default.
i Invariants and contracts preserved? The loop's post-state is unchanged on the normal path. On truncation profile_elapsed is client-measured and was confirmed faithful (within 20 ms of the server's own query_duration_ms), profile_budget_reached is local and read nowhere else, and every non-timeout exception keeps the original annotate-and-re-raise, so no failure class is newly swallowed. That last branch is executed, not merely read: forcing a Code: 115 Unknown setting inside a profile run aborts with the run id in the message and emits no profile row, against a same-command control that reaches the block and exits clean. No concurrency or durability contract is touched.

Also measured, because printing profile for a truncated run is load-bearing rather than cosmetic: the truncated run leaves real samples under its query_id in system.trace_log (left arm 2,766,633 MemorySample, 9201 Real, 4394 CPU; right arm 918,539 / 3151 / 1499). compare.sh:652 folds ^profile rows into analyze/query-profiles.tsv and compare.sh:1683 joins trace_log by query_id, so without the row those samples are orphaned - which is why the shard's .diff.svg files are degenerate 579-byte stubs today.

Mutation controls, one per half of the fix, both reddening: dropping the bound but keeping the catch leaves RC 0 while the runs stretch to 32.8 s and 37.2 s and profile-total goes 32.3 s -> 70.06 s; keeping the bound but restoring the bare raise returns RC 1 with maximum: 10000.000 ms, i.e. the bound in effect and the check still red. Neither half is sufficient alone.

One honest deviation from expectation: truncated runs overshoot the bound by 58-65% (15.8-16.5 s against 10 s), not the ~15% predicted. It is server-side, not client overhead (query_log reports 15.814 s where the client measured 15.819 s): max_execution_time is checked between processing steps and under allocation sampling one step is expensive, so the relative overshoot grows as the bound shrinks - the same mechanism gave CI a 9.8% overshoot at 300 s. The worst case is still bounded at roughly 1.6 * 2 * profile_seconds per query instead of 2 * 300 s.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @leshikus, could you review this? The performance comparison profile runs declare a 10 s budget (--profile-seconds) but set no max_execution_time, so under allocation sampling one query ran to the server 300 s cap and ended the shard as 10 errors; this bounds each profile run by the budget already declared and treats reaching it as the end of profiling rather than an error.

},
)
except clickhouse_driver.errors.ServerException as e:
if e.code != TIMEOUT_EXCEEDED:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This handles TIMEOUT_EXCEEDED as non-fatal for every profiled SQL item, not just read-only ones. The suite already profiles stateful benchmarks such as tests/performance/merge_tree_insert.xml (later INSERTs into the same table depend on the table state created by earlier ones) and tests/performance/hashed_dictionary_load_factor.xml (SYSTEM RELOAD DICTIONARY before later dictHas reads). If one of those profile runs times out here, the harness keeps going with whatever rows, parts, or reload state each side managed to produce before the timeout. Because profiling only starts after a measurable left/right difference, the shared --profile-seconds cap can leave different partial state on the two servers, so the later queries in the same file stop being comparable. I think this path needs a read-only guard (you already have first_keyword), or profiling should be skipped for mutating/stateful query groups instead of continuing after a partial run.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked the two fixtures you name and then the whole suite. The mechanism is real, but neither cited fixture carries it, so I am not adding the guard.

merge_tree_insert.xml is not a carrier. All 9 timed <query> items (27 after substitution) are INSERTs and none reads the tables back, so accumulated row count is never an input to a measurement in that file.

hashed_dictionary_load_factor.xml does have the read-back shape, and SYSTEM RELOAD DICTIONARY does honour max_execution_time (Code: 159 ... maximum: 10.000 ms). But the reload is atomic. Measured on a 3,000,000 element HASHED dictionary immediately after the cap cut a reload: system.dictionaries gives status = LOADED, element_count = 3000000, empty last_exception, and dictHas still answers 1. A truncated reload leaves the previously loaded dictionary rather than a partial one, and the source tables are written only by <fill_query>, so the content a later dictHas sees is invariant either way.

Suite-wide, of 588 fixtures 48 have a mutating timed query, and exactly 2 of those also read the mutated object in a later timed query: hashed_dictionary_load_factor.xml and hashed_dictionary_sharded.xml, both the reload plus dictHas shape above. Reachability is separately out of range: allocation sampling amplifies an INSERT by x1.31 and this reload by x1.20 (0.285 s to 0.341 s, median of 3, settings confirmed in system.query_log), against x22 for the allocation bound aggregation that motivated this PR. Reaching a 10 s budget needs a base runtime above 7.6 s, and --max-query-seconds already caps a measured run at 15 s.

I did reproduce the divergence, with a fixture written for it (timed parallel INSERT, then a timed SELECT over the same table): the truncated arm ends at 174,455,389 rows against 180,000,000, while the same run on unpatched perf.py ends symmetric at 180,000,000. So it is a real behaviour change, with no carrier in the current suite.

On the remedy, first_keyword is not a lever here: it runs only on file= items (perf.py:503-509), so inline items would need a new statement classifier. Re-raising for non read-only groups restores the Code: 159 abort this PR removes, across those same 48 files, and skipping profiling for them instead drops flame graphs master produces today for exactly the queries that regressed.

@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 3, 2026
Merged via the queue into ClickHouse:master with commit ff6e119 Sep 3, 2026
174 of 175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 3, 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 groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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