Skip to content

Shard the clang-tidy build and lower the static analyzer budget for template-heavy directories - #123082

Merged
nickitat merged 9 commits into
masterfrom
tidy-shards
Oct 7, 2026
Merged

nickitat merged 9 commits into
masterfrom
tidy-shards

Conversation

@nickitat

@nickitat nickitat commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

A cold Build (arm_tidy) run (one where a widely included header changed, so the clang-tidy cache misses) took 35–50 minutes, and the regular builds wait for this job. This PR brings a cold run down to about 17 minutes of job time:

  1. Split the clang-tidy build into 4 shards. The clang-tidy build uses dummy compiler and linker launchers (cmake/clang_tidy.cmake), so every object file is an independent clang-tidy run and nothing is linked. The object files of our own code (everything outside contrib) are split by a stable hash of their path, and each shard is a separate job, Build (arm_tidy, i/4). Ninja still builds what each object file needs (generated headers, protoc, llvm-tblgen). check_submodules.sh runs in the first shard only.
  2. Lower the static analyzer's per-function budget (max-nodes, default 225000) to 25000 in src/Functions, src/Interpreters, src/AggregateFunctions, src/DataTypes and src/Processors.
  3. Upload the .ninja_log of each shard, which gives the duration of every file's clang-tidy run.

Why the analyzer budget

Sharding alone was limited by a few files: in a cold run, arrayElement.cpp took 38 minutes and Aggregator.cpp 26, while the typical file takes about 10 seconds. Nearly all of it is the static analyzer (without clang-analyzer-*, arrayElement.cpp takes 28 s instead of 32 minutes), and which checkers are enabled makes no difference. Type dispatch instantiates functions hundreds of times (ArrayElementArrayNumImpl::vector: 19 element types × 2 modes × 8 index types × 2 = 608; Aggregator::executeImplBatch: 934; MergingSortedAlgorithm::merge: 111), and the analyzer explores each instantiation with its callees inlined.

Alternatives that did not work:

  • Shallow mode (no inlining) was about as fast, but produced 9 false positives (core.CallAndMessage, core.NonNullParamChecker), because the analyzer can no longer see that e.g. shared_ptr::get returns a non-null pointer.
  • clang-analyzer-mode / clang-analyzer-max-nodes in CheckOptions have no effect on the analyzer, so the setting is passed as a compiler flag via ExtraArgs. ExtraArgs is part of --dump-config, which the clang-tidy cache hashes, so the cache keys of these directories change.

How much analysis it costs, from running the analyzer over all 5,103 checked files at both budgets: 11.1% of the 139,090 analyzed functions already reach the default limit. A budget of 25000 newly cuts 5.0% of functions short (60% of them template instantiations), and the five directories above hold most of those functions and all of the slowest files. The rest of the codebase keeps the full budget. Applying 25000 globally would save about 74% of analyzer time but cut short functions in many more places, so it is left out.

Why this change should be safe (comparison of lower max-nodes vs shallow mode):

┌───────────────────────────────────────────────┬───────────────────────────────┐
│                 Configuration                 │ Report at arrayReduce.cpp:162 │
├───────────────────────────────────────────────┼───────────────────────────────┤
│ Deep mode (defaults)                          │ no                            │
├───────────────────────────────────────────────┼───────────────────────────────┤
│ Shallow mode                                  │ yes                           │
├───────────────────────────────────────────────┼───────────────────────────────┤
│ Deep mode, max-nodes=25000                    │ no                            │
├───────────────────────────────────────────────┼───────────────────────────────┤
│ Deep mode, only max-inlinable-size=4          │ yes                           │
├───────────────────────────────────────────────┼───────────────────────────────┤
│ Deep mode, max-inlinable-size 8, 16, 32 or 64 │ no                            │
└───────────────────────────────────────────────┴───────────────────────────────┘

Why the two settings behave differently
- max-nodes is a stopping point. When the analysis of one function grows past the budget, the analyzer stops there. Whatever it did explore is modeled exactly as before. A lower budget can only make it miss problems on paths it never reaches; it can't create new reports.
- Shallow mode changes how calls are modeled. It lowers max-inlinable-size from 100 to 4, so the analyzer only steps into functions with at most 4 basic blocks. Any bigger function is treated as a black box: its return value could be anything, including null, and it's assumed to return normally. That's a different model of the program, so paths deep mode drops can now survive to a report. Shallow mode also lowers max-nodes to 75,000, but as the table shows, that isn't what causes the report.

The case in arrayReduce.cpp
- The reported path: offsets starts as nullptr and is set only inside the loop over argument columns, which runs arguments.size() - 1 times. The path assumes zero iterations, meaning a call with only one argument, and then reaches offsets->data() at line 162.
- Why it can't happen: the argument-type check at line 223 throws when there are fewer than 2 arguments. But that check is in a different function, and the analyzer never links the two.
- Why deep mode stays quiet: it doesn't see that guarantee either. Something on that path, a function of 5 to 8 basic blocks, keeps the report from appearing when the analyzer steps into it; the bisection puts the threshold between 4 and 8. The candidates are typeid_cast, Arena::alignedAlloc and the SCOPE_EXIT cleanup. I haven't narrowed it to the exact one.

Results (cold runs, build step of each shard)

Shard 1 Shard 2 Shard 3 Shard 4
Sharding only 14.3 min 12.2 min 39.2 min 20.2 min
With the lower budget 11.4 min 10.7 min 13.0 min 12.0 min

Each job adds about 5 minutes of checkout and cmake. The slowest files are now arrayElement.cpp (7.0 min) and Aggregator.cpp (6.6 min). Total clang-tidy CPU time of a cold run went from 27.6 to 21.7 hours. Runs where the cache hits pay the setup in each of the 4 jobs.

Changelog category (leave one):

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

🤖 Generated with Claude Code


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

Version info

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

The clang-tidy build uses dummy compiler and linker launchers, so every object
file is an independent clang-tidy invocation and nothing is linked. Split the
object files of our own code (everything outside `contrib`) into 4 shards by a
stable hash of their path and run each shard as a separate job,
`Build (arm_tidy, i/4)`. Ninja still builds what each object file needs
(generated headers, `protoc`, `llvm-tblgen`).

About 22% of `Build (arm_tidy)` runs in PRs miss the clang-tidy cache almost
entirely (a widely included header changed) and take 35-50 minutes; the rest
take under 20. A cold run is bound by throughput, not by one slow file: a
sample of 160 files averaged 17 s each with a maximum of 88 s. So the cold
runs should shrink roughly 4x, at the cost of repeating checkout, cmake and
code generation (about 2 minutes) in every shard.

`check_submodules.sh` runs in the first shard only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2bdd4ef]

Summary: ✅


AI Review

Summary

This PR usefully shortens cold Build (arm_tidy) runs by sharding the job, preserving inline diagnostics from the callable path, and lowering the analyzer budget in the worst template-heavy directories. I found one CI regression in how the new per-directory .clang-tidy files interact with Praktika digests: they now make analyzer-config-only edits look like product-code changes to the shared build/test caches and job filters.

Findings

⚠️ Majors

  • [src/Functions/.clang-tidy:8] The new per-directory .clang-tidy files live under ./src, which is hashed by the shared build_digest_config used by ordinary build caches and by build-change filters. That means a future analyzer-budget-only tweak will invalidate the cache for regular builds / Fast test-style jobs and mark the PR as binary-affecting even though only tidy jobs consume these files. Suggested fix: exclude the five new .clang-tidy files from the shared ./src digests and add them back only to the tidy-job digests, or move the configs out of ./src.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: keep the sharding/budget change, but stop the new per-directory .clang-tidy files from flowing into the shared non-tidy digests and build-change filters.

LLVM Coverage Report

Measured on commit 2bdd4ef.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.20% 92.10% -0.10%
Branches 79.70% 79.70% +0.00%

Changed lines: Uncovered code analysis did not run: No coverable C/C++ source files changed (contrib/ is excluded from coverage).

Newly covered: +140 lines in 45 files (-98 lines lost coverage) · Details

Full report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 30, 2026
@leshikus

leshikus commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

@groeneai how much time clang-tidy takes now? does it make sense to run clang-tidy if the file was not changed?

@nickitat

nickitat commented Sep 30, 2026 •

Copy link
Copy Markdown
Member Author

does it make sense to run clang-tidy if the file was not changed?

it shouldn't, but you need to somehow check all transitive dependencies to detect a change. and unchanged files should be served quickly from cache anyway

@groeneai

Copy link
Copy Markdown
Collaborator

Measured on CIDB, Build (arm_tidy), last 14 days (whole job):

runs p50 p90 max over 30 min
PR 6,631 10.6 min 44.9 min 62 min 27%
master 515 9.9 min 44.3 min 58 min 30%

A cold build stage takes about 40 minutes. A fully warm one takes about 3 minutes for ~5,140 files (example, 99.9% hits): the ctcache key (hash_inputs in clang_tidy_cache.py, pinned in ci/docker/binary-builder/Dockerfile:174-177) is the preprocessed translation unit, so it already covers all transitive includes, and a hit costs one preprocessor run instead of a clang-tidy run.

Where I see avoidable cold runs, both from results that are never stored:

  • PR runs cannot write the cache (CTCACHE_S3_READ_ONLY for pr_number > 0, ci/jobs/build_clickhouse.py:183-184), so a PR that touches a widely included header re-checks the same files on every push: 1,039 of the 1,839 cold PR runs (build stage over 25 min) directly followed a cold run of the same PR.
  • Only master writes, and a cold master run takes ~40 minutes. Until it has checked a new header change, every PR that merges that master is cold on the affected files. This PR is an example: it changes no C++, yet shards 1 and 2 missed 263/1,288 and 273/1,264 files, because its merge commit includes src/Columns/ColumnArray.h and other header changes merged after the last cached master run (cdacddff37).

@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 30, 2026
…tidy cache

Upload the `.ninja_log` of the clang-tidy build to get the duration of every
file's clang-tidy run in each shard.

Also add a no-op `static_assert` to `src/Core/Types.h` and
`src/Common/Exception.h`, which about 85% of our object files include, so that
the clang-tidy cache misses and the shards run cold. The cache key is computed
from preprocessed source without comments, so a comment change would not do.
This is for measurement only and will be reverted.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123082&sha=latest&name_0=PR
PR: #123082

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Common/Exception.h Resolved
@nickitat

Copy link
Copy Markdown
Member Author
┌───────┬────────────┬────────────────────────────────────────────────────────────────────────────────────────┐
│ Shard │ Build step │                        Slowest file (duration, when it started)                        │
├───────┼────────────┼────────────────────────────────────────────────────────────────────────────────────────┤
│ 1/4   │ 14.3 min   │ MergingSortedAlgorithm.cpp: 9.5 min, started at 1.1 min                                │
├───────┼────────────┼────────────────────────────────────────────────────────────────────────────────────────┤
│ 2/4   │ 12.2 min   │ SortingTransform.cpp: 6.3 min, started at 1.3 min                                      │
├───────┼────────────┼────────────────────────────────────────────────────────────────────────────────────────┤
│ 3/4   │ 39.2 min   │ arrayElement.cpp: 38.0 min, started at 1.2 min; Aggregator.cpp: 26.2 min               │
├───────┼────────────┼────────────────────────────────────────────────────────────────────────────────────────┤
│ 4/4   │ 20.2 min   │ AggregateFunctionAvgWeighted.cpp: 17.3 min; dateDiff.cpp: 15.0 min, started at 5.2 min │
└───────┴────────────┴────────────────────────────────────────────────────────────────────────────────────────┘

nickitat and others added 2 commits September 30, 2026 18:35
… and `src/Interpreters`

In a cold clang-tidy run, `arrayElement.cpp` took 38 minutes and `Aggregator.cpp`
26, while the typical file takes about 10 seconds. The static analyzer causes it:
without `clang-analyzer-*`, `arrayElement.cpp` takes 28 s instead of 32 minutes.
Type dispatch creates hundreds of instantiations per function (e.g.
`ArrayElementArrayNumImpl::vector`: 19 element types x 2 modes x 8 index types
x 2 = 608; `Aggregator::executeImplBatch`: 934), and in the default (deep) mode
the analyzer re-analyzes each with its callees inlined. Which checkers are
enabled makes no difference.

Shallow mode does not inline callees. It is passed via `ExtraArgs` because
`clang-analyzer-mode` in `CheckOptions` has no effect on the analyzer mode.
Locally, clang-tidy on `arrayElement.cpp` goes from 1921 s to 255 s. `ExtraArgs`
is part of `--dump-config`, which the clang-tidy cache hashes, so the cache
keys of these directories change too.

PR: #123082

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shallow mode does not inline callees, so it produced 9 false positives in
`src/Functions` and `src/Interpreters` (`core.CallAndMessage`,
`core.NonNullParamChecker`): without inlining, the analyzer cannot see that
e.g. `shared_ptr::get` returns a non-null pointer.

Keep the default (deep) mode and lower `max-nodes`, the exploration budget per
function, from 225000 to 25000. Locally, clang-tidy on `arrayElement.cpp` goes
from 1921 s to 309 s (shallow mode: 255 s), and `arrayReduce.cpp`,
`formatDateTime.cpp` and `validateNestedArraySizes.cpp`, which failed with
shallow mode, have no findings.

Also apply it to `src/AggregateFunctions` and `src/DataTypes`, where the next
slowest files are (`AggregateFunctionAvgWeighted.cpp` 18 min,
`DataTypesDecimal.cpp` 12 min in a cold run).

PR: #123082

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread ci/jobs/build_clickhouse.py Resolved
@nickitat

Copy link
Copy Markdown
Member Author
┌───────┬──────────────────────┬──────────────┬─────────────────┬─────────────────────────────────────────┐
│ Shard │ Deep, default budget │ Shallow mode │ max-nodes=25000 │            Slowest file now             │
├───────┼──────────────────────┼──────────────┼─────────────────┼─────────────────────────────────────────┤
│ 1     │ 14.3 min             │ 12.6 min     │ 12.0 min        │ MergingSortedAlgorithm.cpp, 9.1 min     │
├───────┼──────────────────────┼──────────────┼─────────────────┼─────────────────────────────────────────┤
│ 2     │ 12.2 min             │ 11.6 min     │ 11.3 min        │ SortingTransform.cpp, 6.4 min           │
├───────┼──────────────────────┼──────────────┼─────────────────┼─────────────────────────────────────────┤
│ 3     │ 39.2 min             │ 13.2 min     │ 12.7 min        │ arrayElement.cpp, 6.6 min (was 38.0)    │
├───────┼──────────────────────┼──────────────┼─────────────────┼─────────────────────────────────────────┤
│ 4     │ 20.2 min             │ 19.2 min     │ 12.7 min        │ StorageReplicatedMergeTree.cpp, 4.2 min │
└───────┴──────────────────────┴──────────────┴─────────────────┴─────────────────────────────────────────┘

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2bdd4efe4 with master 85c3e1d61 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

nickitat and others added 2 commits October 1, 2026 11:51
After the previous change, `MergingSortedAlgorithm.cpp` (9.1 min) and
`SortingTransform.cpp` (6.4 min) were the slowest files in a cold clang-tidy
run. Both are the same pattern: `MergingSortedAlgorithm::merge` and
`initialize` are analyzed once per sort cursor variant (111 times each), and
`MergeSorter`'s constructor and `read` 56 times each. With `max-nodes=25000`,
clang-tidy on them goes from 446 s to 66 s and from 305 s to 45 s locally,
with no findings.

A codebase-wide scan at the default budget shows that 11.1% of all analyzed
functions already reach the default limit (225000). A budget of 25000 newly
cuts 5.0% of functions short; the five directories with the lower budget
hold the slowest files and most of those functions, while the rest of the
codebase keeps the full budget.

PR: #123082

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The no-op `static_assert`s were only needed to measure cold clang-tidy runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat nickitat changed the title Split the clang-tidy build into 4 shards Shard the clang-tidy build and lower the static analyzer budget for template-heavy directories Oct 1, 2026
The shard's object files were expanded into the build command with
`$(cat tidy_shard_targets.txt)`, which splits them on whitespace and expands
glob characters. Run ninja via `subprocess` with an argument list instead, so
every target name reaches ninja verbatim. A single shell command string is not
an option: Linux limits one argument to 128 KiB, and a shard's target list is
larger.

Report: #123082 (comment)
PR: #123082

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@leshikus leshikus left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Generally looks good. I wonder if we just remove clang-tidy from critical path and make it run in parallel, won't this be simpler?

Comment thread ci/jobs/build_clickhouse.py Resolved
`Result.from_commands_run` captures only what a Python callable prints, so the
output of the `ninja` child process went to the job log but not to the info of
the `Build ClickHouse` result, which shell commands get on failure. Read the
child's combined stdout and stderr through a pipe and print it from Python.

Report: #123082 (comment)
PR: #123082

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat

nickitat commented Oct 1, 2026 •

Copy link
Copy Markdown
Member Author

Generally looks good. I wonder if we just remove clang-tidy from critical path and make it run in parallel, won't this be simpler?

It'd be simpler for sure. I think the motivation to detect such problems as early as possible is still valid even though we lost the battle for the CI cost.
Also, the max-nodes change reduces the total amount of work regardless of whether we shard the job or not.

@nickitat
nickitat marked this pull request as ready for review October 1, 2026 16:40
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR changes only CI and static analysis. It splits the arm clang-tidy build into 4 shards (workflow YAML, job_configs.py, build_clickhouse.py) and adds .clang-tidy files that lower the analyzer's exploration budget for clang-tidy runs only. The release binary used for benchmarks is not affected. The only flagged queries are ClickBench Q33 (+5.5%) and Q34 (+5.0%). Both are borderline: the two tests disagree, and CPU time rose by only 1-2%. They stay not_sure and are not attributable to this change.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1137 1200 +5.5% 0.0171 The PR only changes CI workflows, clang-tidy sharding and .clang-tidy analyzer settings, none of which affect the release binary. The borderline +5.5% is not caused by this PR.
⚠️ 34 not_sure 1139 1196 +5.0% 0.0056 No server code changes: the diff splits the arm clang-tidy build into 4 shards and caps analyzer effort in .clang-tidy files. The borderline +5.0% is not caused by this PR.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 7e0438d0-91a9-454f-aef6-dc4f4fb2f8e0
  • MIRAI run: 414bb60b-d467-41c4-ab86-7565b71c83f8
  • PR check IDs:
    • clickbench_35675_1791303169
    • clickbench_35773_1791303175
    • clickbench_35872_1791303182
    • tpch_adapted_1_official_36025_1791303235
    • tpch_adapted_1_official_36123_1791303248
    • tpch_adapted_1_official_36143_1791303249

# Conflicts:
#	.github/workflows/master.yml
#	.github/workflows/pull_request.yml
Comment thread src/Functions/.clang-tidy
# It is passed as a compiler flag because analyzer options in `CheckOptions` have no effect.
InheritParentConfig: true

ExtraArgs: ['-Xclang', '-analyzer-config', '-Xclang', 'max-nodes=25000']

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.

These new per-directory .clang-tidy files now live under ./src, and the shared build_digest_config hashes the whole ./src tree for every ordinary build cache key and for the build-change filters (ci/defs/job_configs.py:109-131, ci/jobs/scripts/workflow_hooks/filter_job.py:74-84). The root .clang-tidy is intentionally outside that digest, but these files are not, so any future analyzer-budget-only tweak will invalidate the cache for all regular builds / Fast test-style digests and make the PR look like a product-code change even though only the tidy jobs observe these files.

Could we either move these configs out of ./src, or exclude the five new .clang-tidy files from the shared ./src digests and add them back only to the tidy-job digests?

@nickitat
nickitat added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit 8a5a4bd Oct 7, 2026
301 of 302 checks passed
@nickitat
nickitat deleted the tidy-shards branch October 7, 2026 08:07
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). 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