Skip to content

Do not rewrite unchanged generated files on a CMake re-run, and configure faster - #130176

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/cmake-rerun-unchanged-generated-files
Nov 10, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/cmake-rerun-unchanged-generated-files

Conversation

@groeneai

@groeneai groeneai commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #130064

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A CMake re-run no longer rewrites unchanged generated files (TimeZones.generated.cpp, StorageSystemLicenses.generated.cpp, the LLVM .def headers and the musl bits/*.h headers), so it no longer recompiles the code that uses them, and it configures faster: git status skips the work trees of submodules and list-licenses.sh no longer forks per vendored Rust crate.

Description

Based on part (d) of patch 2 by snelheidai in #130064.

Every CMake re-run rewrote some configure-time outputs even when their content did not change, so ninja recompiled their dependents: 20 TUs in a debug build (TimeZones.generated.cpp, the 13 MB licenses source, 18 LLVM/CHJIT.cpp TUs), and almost everything in a musl build, because bits/alltypes.h is on every compile's -isystem path. The new write_file_if_changed() in cmake/utils.cmake writes a temporary file and copies it with file(COPY_FILE ... ONLY_IF_DIFFERENT); the licenses source is copied the same way. Configure time also went to a git status that scans all submodule work trees (now --ignore-submodules=dirty; the configure log no longer lists modified content inside submodules) and to a license script that forked about 10 processes per crate.

Two changes against the posted patch: its process_library shortcut drops libxml2, rapidjson and sz3 from system.licenses under mawk, the awk of the CI builder image, so the shortcut here is equivalent under any awk; and the helper does not use file(READ), which drops the \r of a CRLF line end.

Validation, debug build, ccache, touch CMakeLists.txt, median of 4 runs:

master this PR
ninja build.ninja 18.5 s 7.4 s
ninja clickhouse 62.3 s 52.4 s
TUs compiled 20 0
musl build dir, ninja _lz4 1682 compiles 0

The generated files, system.licenses and the list-licenses.sh output (gawk and mawk) are byte-identical to master. The ninja clickhouse gain is smaller than the saved compiles because master re-runs the Rust archive post-processing on every build (part (a) of #130064).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1783-master (included in 26.11 and later)

groeneai and others added 3 commits November 8, 2026 14:55
…-run

Several configure-time generators rewrote their output on every CMake run even
when the content did not change, so after any re-run ninja recompiled their
dependents and relinked:

- contrib/cctz-cmake: file(REMOVE) + file(APPEND) of TimeZones.generated.cpp
  (1 TU).
- contrib/llvm-project-cmake: file(WRITE) of the six llvm/Config/*.def files
  and llvm/Support/VCSRevision.h (18 TUs, including
  src/Interpreters/JIT/CHJIT.cpp).
- src/Storages/System: file(RENAME) of StorageSystemLicenses.generated.cpp
  (1 TU, a 13 MB source).
- contrib/musl-cmake: bits/alltypes.h, bits/syscall.h and version.h.
  bits/alltypes.h is on the -isystem path of every C/C++/ASM compile of a musl
  build, so a re-run dirtied almost the whole build (1682 compile edges for
  the _lz4 target alone).

Add write_file_if_changed() to cmake/utils.cmake. It writes a temporary file
and copies it with file(COPY_FILE ... ONLY_IF_DIFFERENT), so an unchanged file
keeps its timestamp. A file(READ) + STREQUAL comparison is not used: file(READ)
drops '\r', so content with a carriage return would never compare equal.
The licenses source already goes through a .tmp file and is copied the same
way; the copy still happens only after the script succeeded.

The time zone files stay dependencies of TimeZones.generated.cpp.o through the
#embed entries of its depfile, so a tzdata change still rebuilds it.

Measured on a debug build (touch CMakeLists.txt, then ninja clickhouse): the
20 compile edges are gone (58 -> 29 ninja edges); every generated file is
byte-identical to before.

Based on part (d) of patch 2 by snelheidai in ClickHouse#130064.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
list-licenses.sh runs at configure time. It forked dirname, basename, rev,
cut and grep for each vendored Rust crate (about 1400) and walked the whole
tree of every C/C++ library.

- process_rust_crate uses shell builtins only, and xargs runs it on batches
  of 64 crates.
- process_library looks at the top-level license candidates first and walks
  the whole tree only when none of them is chosen. This is equivalent with any
  awk: after LC_ALL=C sort every depth-1 line comes first, and once a line
  matches, only lines with depth <= min_depth can change the result.
  Keeping only the depth-1 candidates whenever there is one is NOT equivalent
  under mawk (the awk of the CI builder image), where IGNORECASE has no
  effect: it drops libxml2, rapidjson and sz3 from system.licenses.
- StorageSystemLicenses.sh reads the license files with $(< file) instead of
  $(cat file).

The output is byte-identical to before under both gawk and mawk, and a crate
with an unrecognized license still makes the script fail.
list-licenses.sh: 2.0 s -> 0.5 s; StorageSystemLicenses.sh: 5.1-5.5 s -> 0.8 s.

Based on part (d) of patch 2 by snelheidai in ClickHouse#130064.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cmake/git.cmake runs git status only to print the state of the tree into the
configure log. A plain git status scans the work trees of all submodules
(5.0-5.6 s here); with --ignore-submodules=dirty it takes 0.2 s.

A submodule checked out at another commit is still listed; modified or
untracked content inside a submodule is no longer listed. Nothing reads this
output (no OUTPUT_VARIABLE), and system.build_options does not contain it.

Based on part (d) of patch 2 by snelheidai in ClickHouse#130064.

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

groeneai commented Nov 8, 2026

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

Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 Three mechanisms in one PR (generated-file writes, list-licenses.sh forks, git status) AGREE, noted One scenario (a CMake re-run), one commit per mechanism; I can split along the commits if preferred.
2 💡 file(READ) drops only the \r of a CRLF line end AGREE Description wording made precise.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-11:20261108-161900

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. touch CMakeLists.txt, ninja build.ninja, then ninja -d explain clickhouse: on master the 9 generated files get a new mtime and 20 compile edges are dirtied, in every run (5/5). A musl build dir recompiles 1682 TUs for _lz4.
b Root cause explained? The generators used write-always CMake primitives (file(REMOVE) + file(APPEND), file(WRITE), file(RENAME), execute_process(OUTPUT_FILE)), so unchanged outputs got a new mtime on every configure and ninja recompiled their dependents. Configure time went to a git status scanning all submodule work trees and to about 10 forks per Rust crate in list-licenses.sh.
c Fix matches root cause? Yes. Each generator writes only when the content changes (temporary file + file(COPY_FILE ... ONLY_IF_DIFFERENT)); the two slow commands are narrowed, not removed.
d Test intent preserved / new tests added? Build-system change, no in-repo test (a configure-time mtime is not observable from a test). Validated locally: byte-identical generated files, mtime and ninja-explain oracle, a cmake -P unit check of the helper, list-licenses.sh under gawk and mawk.
e Both directions demonstrated? Yes. Master: 9 files rewritten, 20 compiles (musl: 1682). This PR: 9 files untouched, 0 compiles (musl: 0). Negative control: the posted process_library shortcut under mawk drops 3 rows, this version keeps the output byte-identical.
f Fix is general across code paths? Yes. Every file(WRITE/APPEND/RENAME/REMOVE/COPY/COPY_FILE) and OUTPUT_FILE in repo-owned CMake was checked; the explain oracle shows no other configure-caused compile edge; the musl headers are included beyond the posted patch.
g Fix generalizes across inputs (params/datatypes/wrappers)? Helper: CRLF, empty, ;, \, [[ ]], ${...}, @x@. Script: gawk and mawk, crate names with and without -, -alpha versions, a Cargo.toml without a final newline, a crate with an unrecognized license (still exits non-zero).
h Backward compatible? (maintainer-approved exception only) Yes. No settings or formats; generated files and system.licenses are byte-identical. Only the configure log no longer lists modified content inside submodules.
i Invariants and contracts preserved? Changed content is always written; the licenses source is still replaced only after the script succeeded; a failing crate still fails the configure.

Session id: cron:clickhouse-impl-slot-6:20261108-141300

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @thevar1able, could you review this and add the can be tested label so CI runs? The configure-time generators (cctz TimeZones.generated.cpp, the LLVM .def files, musl bits/*.h, the licenses source) now write only when the content changes, so a CMake re-run no longer recompiles their dependents (20 TUs in a debug build, 1682 in a musl build), and git status and list-licenses.sh take less configure time.

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f085015]

Summary: ✅


AI Review

Summary

PR #130176, reviewed at f0850151cc23e4109cfc850c1e6315ae2c606bd9, preserves unchanged configure-time generated files and reduces license-discovery and Git-status overhead. No actionable correctness, compatibility, or failure-handling issues found. Focused checks passed for unchanged timestamps, generated bytes, batched crate processing, license selection under mawk and gawk, and invalid-license rejection.

Missing context / blind spots
  • ⚠️ Full ClickHouse builds and compiler #embed dependency invalidation were not independently repeated: this checkout lacks populated build submodules and a configured build directory. Repeating the PR's reported debug/musl incremental-build measurements in a populated checkout would close this gap; local checks used synthetic fixtures.
Final Verdict

Status: ✅ Approve. No inline findings.

@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement submodule changed At least one submodule changed in this PR. can be tested Allows running workflows for external contributors manual approve Manual approve required to run CI labels Nov 8, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-build-system Build system (CMake, compilation, platform builds). label Nov 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f0850151c with master 634d83a99 (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, 4 s compile time in total, 6 of them have a recent master baseline.

Job report

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f085015

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found hung query, not from this PR (it changes only CMake and shell build files): a server-side AST fuzzer variant of 03711_contingency_window_function computes cramersV, cramersVBiasCorrected, theilsU and contingency over window frames on numbers(100000) and recomputes them in AggregateWindowFunctionRecalculate::evaluate; it was still running 1274 s after it was cancelled a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20261108-203007

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

About the Stress test (amd_tsan) hung check row of the ledger above: I am not opening a fix for it. The fuzzed query computes theilsU over ROWS BETWEEN 0 PRECEDING AND 99999 FOLLOWING, so its frame start moves every row and the frame is re-aggregated per row, and window functions evaluate each batch without cancellation checks by design (see WindowTransform::computeReadyRows). The query keeps running until its batch ends. It is not caused by this PR, and this PR needs no change for it.

@Algunenano Algunenano self-assigned this Nov 9, 2026
@Algunenano

Copy link
Copy Markdown
Member

About the Stress test (amd_tsan) hung check row of the ledger above: I am not opening a fix for it. The fuzzed query computes theilsU over ROWS BETWEEN 0 PRECEDING AND 99999 FOLLOWING, so its frame start moves every row and the frame is re-aggregated per row, and window functions evaluate each batch without cancellation checks by design (see WindowTransform::computeReadyRows). The query keeps running until its batch ends. It is not caused by this PR, and this PR needs no change for it.

This is not the established procedure. At the very least you need to propose a possible fix to address this problem. @groeneai

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Acknowledged, closing that row without a fix was wrong. I am working on a fix for this hung check and will link the PR here (and on #125015, which has the same row).

@snelheidai

Copy link
Copy Markdown

@groeneai the hang is a regression from #129257 (merged Nov 6), and a small patch fixes it (below).

#129257 moved aggregate window evaluation into per-block batches. WindowTransform::computeReadyRows still checks isCancelled() per row, but only while it records frame bounds. AggregateWindowFunctionRecalculate::evaluate then re-aggregates the whole frame for every row whose frame start moved, for a whole block, with no check. Before that, the aggregation ran inside the per-row loop, whose comment said the check was per row "since one block can take long on quadratic frames". #127389 batched the general window functions the same way on Oct 28, and exponentialTimeDecayedMax scans its whole frame for every row of a batch.

CI shows the same. In the 90 days before Nov 3, no hung check involved a window query. On Nov 3, master hung on a fuzzed 02020_exponential_smoothing query (exponentialTimeDecayedMax). Since #129257 merged, 6 of the 11 hung checks are fuzzed window queries with a moving frame start: #128896, #128773, #130053, #130144, #125015 and this PR.

The patch gives WindowBounds a pointer to the processor's cancellation flag. The recalculating aggregate checks it once per frame run and exponentialTimeDecayedMax once per row. evaluateRowsBatch then discards a batch that was cut short instead of packing it. Such frames still cost rows × frame; the patch only makes cancellation prompt again.

On master 7a516a1 (x86, Release build), with both CI hung queries verbatim:

Case master patched
KILL QUERY 5 s after start, this PR's hung query still running after 150 s returns 0.06 s after the KILL
Same query with max_execution_time = 5 still running after 150 s stops at 5.07 s with TIMEOUT_EXCEEDED
KILL QUERY 5 s after start, the 02020_exponential_smoothing hung query still running after 150 s returns 0.09 s after the KILL

The 248 window-related stateless .sql tests give identical output on both builds (220 pass; the other 28 need datasets or remote shards missing from our standalone runner). Server time of small-frame window queries over 5M rows (sliding sum, exponentialTimeDecayedMax, 10-row partitions) moved between -1.7% and +1.5% across two paired sessions of 11 and 21 runs, with no consistent direction. Checking only after every 65536 frame rows instead was consistently 2.7% slower on two of them.

cc @Michicosun as the author of #129257.

Patch against master 7a516a1 (these files are unchanged on current master)
--- a/src/Processors/Transforms/WindowTransform.cpp
+++ b/src/Processors/Transforms/WindowTransform.cpp
@@ -86,6 +86,8 @@
     , arguments(params.input_header, functions)
     , frame(params)
 {
+    bounds.is_cancelled = &getCancellationFlag();
+
     for (const auto & function : functions)
         if (const auto general = asGeneralWindowFunction(function.aggregate_function))
             general->checkWindowFrameType(params.window_description);
@@ -133,7 +135,7 @@
 
 void WindowTransform::computeReadyRows()
 {
-    /// Cancellation is checked per row here; window functions evaluate each batch without cancellation checks
+    /// Cancellation is checked per row here; inside a batch, only functions whose cost per row grows with the frame check it
     while (!isCancelled())
     {
         if (bounds.rows != 0 && peers.current().location.block != batch_start.block)
@@ -201,6 +203,14 @@
     for (auto & slot : aggregate_functions)
         first_row = std::min(first_row, slot.function->evaluate(bounds, arguments.view(slot.function_index), *current_results[slot.function_index]));
 
+    /// A function may stop early on cancellation and leave its result column short, so the batch is not packed.
+    if (isCancelled())
+    {
+        current_results.clear();
+        clearBounds(bounds);
+        return;
+    }
+
     const bool block_complete = batch_start.row + bounds.rows == block.rows_count;
     if (block_complete)
         packReadyBlock();
--- a/src/WindowFunctions/Aggregate/AggregateWindowFunctionRecalculate.cpp
+++ b/src/WindowFunctions/Aggregate/AggregateWindowFunctionRecalculate.cpp
@@ -36,6 +36,10 @@
 {
     for (Int64 from = 0; from < bounds.rows;)
     {
+        /// A moved frame start re-aggregates the whole frame, so one batch can cost rows * frame additions.
+        if (bounds.isCancelled())
+            break;
+
         const Int64 to = equalFrameRun(bounds, from);
         const Int64 frame_start = bounds.frame_start[from];
         const Int64 frame_end = bounds.frame_end[from];
--- a/src/WindowFunctions/Common/WindowBounds.h
+++ b/src/WindowFunctions/Common/WindowBounds.h
@@ -3,6 +3,8 @@
 #include <Common/PODArray.h>
 #include <base/types.h>
 
+#include <atomic>
+
 namespace DB
 {
 
@@ -16,6 +18,12 @@
     PaddedPODArray<Int64> peers_end;
     PaddedPODArray<Int64> peer_group_index;
     PaddedPODArray<Int64> partition_end;
+
+    /// Cancellation flag of the processor evaluating the batch. A function whose cost per row grows with the frame
+    /// checks it inside the batch and may stop early; the transform then discards the incomplete batch.
+    const std::atomic<bool> * is_cancelled = nullptr;
+
+    bool isCancelled() const { return is_cancelled && is_cancelled->load(std::memory_order_relaxed); }
 };
 
 void clearBounds(WindowBounds & bounds);
--- a/src/WindowFunctions/General/WindowFunctionExponentialTimeDecayed.cpp
+++ b/src/WindowFunctions/General/WindowFunctionExponentialTimeDecayed.cpp
@@ -158,6 +158,10 @@
         auto & data = assert_cast<ColumnFloat64 &>(result).getData();
         for (Int64 i = 0; i < bounds.rows; ++i)
         {
+            /// Every row scans its whole frame.
+            if (bounds.isCancelled())
+                break;
+
             const Int64 start = bounds.frame_start[i];
             const Int64 end = bounds.frame_end[i];
             Float64 max = std::numeric_limits<Float64>::quiet_NaN();

@Algunenano

Copy link
Copy Markdown
Member

@groeneai Please remember it's ok/expected to investigate what caused a new issue and propose a revert so we stop having issues in CI

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Understood, I will do that from now on. This hung check points to #129257 (merged on Nov 6). I am verifying that the query stops on max_execution_time at its first parent and not at its merge commit; if it does, I will open a revert of #129257 and link it here. The forward fix stays the alternative.

@snelheidai

Copy link
Copy Markdown

Reverting #129257 makes the aggregate hangs cancellable again, but not the Nov 3 hang on master.

At the first parent of #129257 (e1e15a9), aggregates are still re-aggregated row by row inside the while (!isCancelled()) loop of WindowTransform::computeReadyRows. That covers 7 of the 8 hung checks with a window query since Nov 3, all aggregates over a moving frame start; the latest was today on PR 128389. #129940 reports the same case.

The 8th is a fuzzed 02020_exponential_smoothing query: exponentialTimeDecayedMax over numbers(1000000) with ORDER BY 1 DESC GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING. The constant ORDER BY 1 makes all rows peers, so every row scans a million-row frame inside one batch. That batching of general window functions came from #127389 and stays after the revert. The exponentialTimeDecayedMax part of the patch above (its per-row check, the WindowBounds pointer and dropping a cut batch) covers this path.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

I opened the revert of #129257: #130331. With max_execution_time = 5 the reproducer stops after 5.7 s at its first parent e1e15a9 and is still running after 120 s at its merge commit d55bffe and on master 4ce8938 (5/5 runs each); a build of the revert stops after 5.5 s. #130328 is the alternative fix. The revert does not cover the 2026-11-03 master hang (a fuzzed exponentialTimeDecayed* query over GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING), which predates the merge of #129257.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (amd_tsan) / Hung check failed, possible deadlock found row of the ledger above: #130328 (external, open), which replaced the revert #130331. On its CI build the reproducer stops after 5.4 s with max_execution_time = 5 and within 0.2 s of KILL QUERY, so I am not opening a second fix.

#130328 does not cover the 2026-11-03 master hang in exponentialTimeDecayedMax (a general window function, evaluated per batch since #127389). A possible fix is the same budgeted check in its per-row frame scan, but @ Michicosun ruled that case not a problem (#127389 (comment)), so I am not opening a PR for it unless asked.

@Algunenano
Algunenano enabled auto-merge November 9, 2026 16:33
@Algunenano
Algunenano added this pull request to the merge queue Nov 9, 2026
Merged via the queue into ClickHouse:master with commit f51f86e Nov 10, 2026
559 of 561 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 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 comp-build-system Build system (CMake, compilation, platform builds). manual approve Manual approve required to run CI pr-build Pull request with build/testing/packaging improvement pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants