Skip to content

Fix parts silently pruned after ALTER MODIFY COLUMN ... AFTER on a partition-key column - #120862

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:fix-minmax-index-column-order
Sep 22, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:fix-minmax-index-column-order

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #92834
Related: #93111

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong results after ALTER TABLE ... MODIFY COLUMN <column> <type> AFTER <other> on a column used in PARTITION BY. The reorder changed the order of the part min-max index columns, which are addressed by position, so a part written before the ALTER was silently pruned from queries it belongs to, DELETE removed nothing, system.parts.min_time reported another column's value or raised LOGICAL_ERROR: Part minmax index by time is neither DateTime or DateTime64, and the implicit _minmax_count_projection answered min() / max() from another column. The order now comes from the partition key's column names, which an existing table cannot change. Closes #92834.

Description

MergeTreeData::getMinMaxColumns took the min-max index column list from
partition_key.expression->getRequiredColumnsWithTypes(), the table's column definition order.
MODIFY COLUMN ... AFTER rewrites that order, and nothing on the ALTER path refreshes materialized
state: checkPartitionKeyAndInitMinMax runs only in the MergeTreeData constructor,
so minmax_idx_{date,time}_column_pos keep their old values, and nothing rebuilds a loaded part's
hyperrectangle. Every consumer addresses it by position, so a part written before the ALTER read
its ranges from the wrong slots.

The implicit _minmax_count_projection derives its min(c)/max(c) pair order from the same table
order through a different call and is not rebuilt either, so both derivations are now sorted by
name; sorting one alone would desynchronize the other. The name set cannot change for an existing
table: RENAME/DROP on a key column are rejected, PARTITION BY cannot be altered, and a key
column cannot become an ALIAS.

Nothing persisted is positional (files are minmax_<column>.idx, checksums keyed by name), so
there is no format change and mixed-version replicas are unaffected. Measured both ways: a
directory written by master reads correctly here, and the reverse.
mergeTreeIndex(..., with_minmax = 1) lists its minmax_<column> columns in that order too, so its
SELECT * order changes for a partition key that is not name-sorted; no test depends on it.

Not repaired: a merge that ran while the order was desynchronized already wrote mixed bounds into
minmax_<column>.idx (unioned by position, stored by name), which survive a restart. A re-insert
fixes such a table, as does OPTIMIZE ... FINAL DEDUPLICATE, which recomputes them from the data
but drops duplicate rows; a plain OPTIMIZE ... FINAL only unions the stored ranges, so it
does not.


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

Version info

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

groeneai and others added 3 commits September 18, 2026 15:03
…t the table column order

MergeTreeData::getMinMaxColumns took the min-max index column list from
partition_key.expression->getRequiredColumnsWithTypes(), which is the table's
column definition order. ALTER TABLE ... MODIFY COLUMN <c> <type> AFTER <other>
on a column used in PARTITION BY rewrites that order, and nothing on the ALTER
path refreshes already materialized state: checkPartitionKeyAndInitMinMax is
called only from the MergeTreeData constructor, so minmax_idx_date_column_pos
and minmax_idx_time_column_pos keep their pre-ALTER values, and no code rebuilds
a loaded part's hyperrectangle. Since every consumer addresses the hyperrectangle
by integer position, a part written before the ALTER had its ranges read out of
the wrong slots. Observed on master, all silent:

  CREATE TABLE t (a UInt32, b UInt32) ENGINE = MergeTree PARTITION BY (a, b) ORDER BY tuple();
  INSERT INTO t VALUES (1, 100);
  ALTER TABLE t MODIFY COLUMN a UInt32 AFTER b;
  SELECT count() FROM t WHERE a = 1;                        -- 0, the row is there
  DELETE FROM t WHERE a = 1 SETTINGS mutations_sync = 2;    -- completes, deletes nothing

plus a wrong system.parts.min_time for a part written after the ALTER, or
LOGICAL_ERROR "Part minmax index by time is neither DateTime or DateTime64" when
the stale slot holds an incompatible Field kind (issue ClickHouse#92834's reproducer).

The order is now a function of the partition key's column-name set alone, which
an existing table cannot change: RENAME and DROP on a key column are rejected,
PARTITION BY cannot be altered, MODIFY COLUMN on a key column only changes the
type, and the key cannot reference an ALIAS. So a metadata mutation can no longer
desynchronize the index, rather than the ALTER path having to repair it.

The implicit _minmax_count_projection derives its min(c)/max(c) pair order from
the same table order through a different call, and getMinMaxCountProjectionBlock
pairs the i-th projection column with hyperrectangle[i], so both derivations are
made canonical. Sorting only getMinMaxColumns would have broken min()/max()
answered from that projection for every table whose column order is not sorted by
name, with no ALTER involved. Sorting only the projection would have left the
index untouched. Both are needed and each one guards the other.

Nothing persisted or transferred depends on the order: files are
minmax_<column>.idx, checksums.txt is keyed by file name, no metadata file lists
the columns positionally, and parts are fetched as files, so there is no format
change and a mixed-version replica set is unaffected. Measured in both
directions: a data directory written by master and opened by this build reads
correctly, and the reverse too; on the upgrade path a stale min_time is repaired
on load, because both the load order and the cached positions are recomputed from
the metadata.

Two things this does not do. It does not repair bounds a merge already wrote
while the order was desynchronized: a merge unions the source hyperrectangles
by position and then stores them by name, so those bounds are on disk and
survive a restart. Re-inserting the data repairs such a table; an ordinary
merge does not, OPTIMIZE ... FINAL included, because merge_may_reduce_rows is
false for it, so the merged index is the union of the stored source ranges
instead of a recomputation from the data, and a union only ever widens.
OPTIMIZE ... FINAL DEDUPLICATE does repair it in place, because deduplicate
does set that flag - at the cost of dropping duplicate rows. And it
leaves ReplicatedMergeTreeTableMetadata alone, which indexes the
required-column list with the cached date position: it runs only for
format_version below
MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING, whose partition
key is toYYYYMM(<the single date column>), so the list has one element and
every order is the same order.

The new test asserts the projection-on and projection-off answers are equal
rather than hard-coding a triple, so a future change of the projection defaults
cannot satisfy it vacuously. Its last case has no ALTER at all: it exists because
a table declared (b, a) is the shape that detects a desynchronized projection
order.

Closes: ClickHouse#92834
Related: ClickHouse#93111

Co-Authored-By: Claude Opus 5 <[email protected]>
…test

The T7 and T8 cases compare min()/max() answered from the implicit
_minmax_count_projection against the same query with projections off, but
optimize_use_implicit_projections = 1 only grants permission: if
optimizeUseAggregateProjection declines, both sides are computed from the base
table and the comparison passes on any binary, including one built without the
ProjectionDescription::getMinMaxCountProjection sort. Since reverting only that
sort reddens exactly one line, T8 "projection enabled", that assertion is the
whole guard for half the fix and it must not be able to pass vacuously.

Add a projection-use assertion next to each of the two cases, in the shape
already used by 04950_minmax_count_projection_unusable_bound.

The two assertions read the initiator's own plan, which under parallel replicas
holds the projection only when the initiator builds a local plan and
aggregation-in-order is off. Both are randomized per run by clickhouse-test,
and the ParallelReplicas configuration enables parallel replicas for every
query, so without a pin the assertions failed about half the time there (16/30,
13/50, 10/20 runs; the runner's own --diagnose-random-settings named
optimize_aggregation_in_order). The answers stay correct in every combination,
only the plan choice moves, so a per-setting "Random settings limits" line pins
both settings to the values they already have by default rather than tagging
the test out of randomization.

Co-Authored-By: Claude Opus 5 <[email protected]>
The Nullable/DateTime case asserted count() FROM system.parts, which proves only
that the query completed, and it let c2 default to the DateTime epoch. A value
oracle over that row would have been no better: min_time = max_time = 0 is also
what an empty range and an unset cached position produce, so the expected output
was reachable without the corrected slot order. Insert a non-epoch c2 and assert
min_time / max_time, which subsumes the no-throw property since printing the row
requires the query to finish.

Measured on the fixed build: with c2 at its epoch default the row reads
1970-01-01 00:00:00, with '2024-06-15 12:00:00' it reads that value back. On
master the same case still aborts with "Part minmax index by time is neither
DateTime or DateTime64", so the case keeps the failure it was written for. The
file passes with each of the six session timezones clickhouse-test randomizes,
including the three that are non-deterministic around 1970.

No mixed-NULL Nullable(DateTime) case is added: a Nullable date or time key
leaves the cached position unset, because checkPartitionKeyAndInitMinMax
classifies with raw TypeIndex tests, so getMinMaxTime returns an empty result
before it reads a bound and such an oracle would be vacuous too. Supporting
min_time / max_time for a Nullable date or time key is separate work.

Also pin the setting that actually governs the lightweight DELETE case:
InterpreterDeleteQuery overwrites mutations_sync in the query context with
lightweight_deletes_sync, so the old pin was inert and the case was
deterministic only by that default. The heavyweight ALTER ... DELETE case keeps
mutations_sync, which is its setting.

Renumbered to 05229 because 05227 and 05228 landed on master meanwhile.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 18, 2026
@groeneai

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

Pre-publication review over four rounds. An independent model reviewed each head (engine: codex;
3 findings in round 1, none afterwards), and I reviewed the resulting code cold each round before
reading the author-side evidence (5 further findings).

# Sev Finding Verdict Evidence / action
1 ❌ A metadata-only MODIFY COLUMN a UInt32 ALIAS b could still change the partition key's source columns, so sorting by name is not stable (MergeTreeData.cpp:1552) DISAGREE That ALTER cannot be applied: AlterCommands.cpp:864 moves the column out of the physical set, :1806 then always recalculates the partition key, and the key is analysed against physical columns plus virtuals only (VirtualColumnUtils.cpp:938), so TreeRewriter.cpp:1277 throws Missing columns on a metadata copy and the statement fails with no state change. Measured from the other end: PARTITION BY al with al ALIAS x + 1 is refused with Code: 47 ... Missing columns: 'al'.
2 ❌ Sorting also changes the public column order of mergeTreeIndex(..., with_minmax = 1) for existing non-name-sorted schemas (TableFunctionMergeTreeIndex.cpp:167) DISAGREE The order does change and the PR body now says so, but no stable contract is broken: the prior exposed order is the table column definition order, which ALTER TABLE ... MODIFY COLUMN ... AFTER already changes today, which is the defect being fixed here. Pinning the exposed order to a mutable order while the header is sorted would add a third hand-synchronised derivation of the same list. Blast radius measured: every existing with_minmax test uses a single-column partition key, and the columns stay reachable by name.
3 ⚠️ The projection-enabled cases only request the implicit projection, so they can pass from a base-table fallback AGREE, fixed Reverting only the projection sort reddens exactly one line, so that line is the whole guard for half the fix; the test now asserts projection use directly, in the shape already used on master by 04950_minmax_count_projection_unusable_bound. Not taken for the pruning cases: those counts are already the reddening set, while an EXPLAIN indexes = 1 parts assertion would pull in the tag and pin battery that 04062_use_partition_pruning_disable_minmax_count_projection needs.
4 ❌ The write-up claimed OPTIMIZE ... FINAL repairs bounds a pre-fix merge already wrote wrong AGREE, fixed My finding. For plain MergeTree it cannot: merge_may_reduce_rows (MergeTask.cpp:846) is false for an ordinary merge, so the merged index is the positional union of the loaded source indices (:955, and MinMaxIndex::merge only widens) and the recompute from data at :1877 never runs; measured, the affected query still returns 0 right after OPTIMIZE ... FINAL. Corrected in both places the claim lived, the PR body and the commit message, since individual commits reach master. The follow-up measurement identified the one operation that does repair in place, OPTIMIZE ... FINAL DEDUPLICATE (deduplicate sets that flag, so the index is recomputed from the data), at the cost of dropping duplicate rows: base 0, plain FINAL 0, DEDUPLICATE 1, still 1 after a reload.
5 ❌ The Nullable/DateTime case asserted count() over system.parts, which proves only that the query finished, and left c2 at the epoch, where min_time = max_time = 0 is also what an empty range and an unset cached position produce AGREE, fixed My finding. The case now inserts a non-epoch value and asserts min_time / max_time by value, which subsumes the no-throw property because printing the row requires the query to finish. Measured stable under each of the six session timezones the runner randomizes.
6 💡 The user-visible mergeTreeIndex(..., with_minmax = 1) column-order change was not disclosed AGREE, fixed My finding. One sentence added to the PR body.
7 💡 The lightweight DELETE case pinned mutations_sync, which InterpreterDeleteQuery overwrites with lightweight_deletes_sync, so the pin was inert AGREE, fixed My finding. That case now pins lightweight_deletes_sync = 2; the heavyweight ALTER ... DELETE case keeps mutations_sync = 2, which is its own setting.
8 💡 ReplicatedMergeTreeTableMetadata.cpp:56 indexes the same list by the cached date position DISAGREE (safe as is) My finding, kept out of the PR body for length. It runs only for legacy toYYYYMM(<date>) partitioning, whose list has one element, and the date-column choice is order-independent regardless: checkPartitionKeyAndInitMinMax yields -1 whenever more than one Date or DateTime column is present.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a later round are auto-dropped.

Session id: cron:clickhouse-review-slot-11:20260918-151100

@clickhouse-gh clickhouse-gh Bot closed this Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100%, no randomization or timing: the new test on master 01b8f1c9fb2e1 returns 10 wrong values and aborts on the LOGICAL_ERROR; on this build it matches the reference byte for byte.
b Root cause explained? getMinMaxColumns took the min-max index column order from the mutable table column order, MODIFY COLUMN ... AFTER rewrites it, neither the cached minmax_idx_{date,time}_column_pos nor a loaded part's hyperrectangle is refreshed, and every consumer indexes that hyperrectangle by position.
c Fix matches root cause? It removes the dependency on the mutable order in both derivations instead of refreshing state or guarding the failure site: the LOGICAL_ERROR throw and the chasserts are untouched, no widened bound, no no-random-* tag, no defensive check.
d Test intent preserved / new tests added? No existing test weakened and no existing .reference touched; new 05229_minmax_index_order_after_modify_column_after with 8 cases: pruning of a pre-reorder part and of both parts, system.parts.min_time, the #92834 LOGICAL_ERROR asserted against a non-epoch value, lightweight DELETE, heavyweight ALTER ... DELETE, a wrong bound persisted through a merge and a reload, and the implicit projection with an EXPLAIN assertion that the optimizer chose it.
e Both directions demonstrated? Yes, plus two mutation arms: reverting only columns.sort() reddens every case, reverting only the projection sort reddens exactly T8 projection enabled, and the two assertions invariant across those arms were measured non-vacuous separately. Build IDs asserted for all four binaries.
f Fix is general across code paths? Both derivations of the order are canonical now; the third site indexing by a cached position, ReplicatedMergeTreeTableMetadata, is safe unchanged (legacy toYYYYMM(<date>), one element), every other consumer goes through getMinMaxColumns, projection parts inherit the parent key and patch parts are excluded.
g Fix generalizes across inputs (params/datatypes/wrappers)? The order is a pure function of column names, so the type lattice cannot affect it; measured on the fixed build with a 3-column key declared in reverse of sorted order, the same column referenced twice in the key expression, a LowCardinality(Nullable(String)) key column with NULL rows, and a Tuple subcolumn key.
h Backward compatible? (maintainer-approved exception only) Yes, measured in both directions: a data directory written by master reads correctly here, and the reverse. Nothing persisted or transferred is positional, no setting is added, no format version changes. The one thing it cannot repair is bounds a pre-fix merge already wrote wrong, disclosed in the PR body with the repair.
i Invariants and contracts preserved? The order of getMinMaxColumns() and the slot order of every live hyperrectangle now agree for the lifetime of the table by construction, since the order depends only on an immutable name set; store's prefix rule is preserved (block-number and block-offset columns still appended after the sorted prefix), MinMaxIndexStoreFixture.* and SupportsTrivialCountOptimization.NullMutationsSnapshot still pass, and no lock, concurrency or durability contract is touched.

Also verified: 50 runs with the default randomized settings and 50 with the pruning settings pinned,
0 failures in both; a 40-test regression sweep over the min-max index, partition pruning, the implicit
projection and mergeTreeIndex() introspection with no reference churn (its 4 failures reproduce
identically on an unmodified master binary: a missing Keeper, a missing cluster and the absent
stateful dataset in the local rig); check_style.py clean apart from the settings_changes_history
leg, which cannot run outside CI.

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8b9f6a9]

Summary: ✅


AI Review

Summary

This PR fixes the wrong min-max slot ordering that appears after ALTER TABLE ... MODIFY COLUMN ... AFTER on a partition-key column by canonicalizing the part min-max column order and the implicit _minmax_count_projection order by partition-key column name. I traced that invariant through part load/store/merge, partition pruning, system.parts, the implicit projection path, and mergeTreeIndex, and I did not find a remaining correctness gap in the current code.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 8b9f6a9.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 12/12 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5c218d4

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
Build profile diff infra: RuntimeError: CI logs cluster query failed, raised at ci/jobs/scripts/log_cluster.py:234; 243 distinct PRs carry the identical signature in 24h #118708 (mine, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log Code: 47 ... Unknown expression identifier b ... In scope b, b from MutatePlainMergeTreeTask on part all_1_1_1_2; 20+ distinct PRs carry the identical line in 7 days and true master carries none #118499 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) measurement run reports 10 errors; this shard went from about 1 red/day to 163 reds on 2026-09-18, starting right after #120176 merged at 21:10Z, and it is red on master too #120923 (external, open)
Mergeable Check, PR praktika rollups of the three rows above, no independent failure #118708 (mine, open), #118499 (mine, open) and #120923 (external, open)

None of the three is reachable from this diff, which changes partition-key handling for
ALTER MODIFY COLUMN ... AFTER plus one functional test. The Finish Workflow failure visible on this
commit belongs to the superseded run 35363758865 (cancelled at 15:41Z); on the live run 35363773505
Finish Workflow is green, and that run is 152 success / 18 skipped / 3 failures.

Session id: cron:our-pr-ci-monitor:20260919-020058

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8b9f6a9bc with master 9d2b2e727 (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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120862&sha=d56ca535ff38d5a7f2d8a9a2eba8ecbbfbe35f70&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The AST fuzzer (amd_debug, targeted) red is ERROR: OOM in dmesg — the server was OOM-killed by the container cgroup at anon-rss:46579644kB (Memory cgroup out of memory: Killed process ... (clickhouse-serv)). It is not attributable to this PR: the fuzz step that killed the server is

SELECT * FROM file(concat(repeat('{"a":null,"b":true,"c":false}', 100000), ',', repeat('}', 100000)))

reached at Fuzzing step 71 out of 1000 from a url(concat(repeat('{', 100000), ...)) seed. The memory is consumed inside format detection / schema inference (detectFormatAndReadSchema → URLReadBufferIterator::next), with no MergeTree, partition key or min-max index on the path. This PR touches only MergeTreeData::getMinMaxColumns and ProjectionDescription::getMinMaxCountProjection (plus one stateless test), none of which participate in that query. The closest known open item is #111892 (AST fuzzer: server left above its memory limit kills the job), and the untracked-allocation side is #117916.

The other red, Build profile diff, is the CI-logs-cluster infra error already recorded in the ledger above and owned by #118708; a re-merge does not clear it.

Merged master again (1035f95698ee) to re-run CI on a current base; both changed translation units (MergeTreeData.cpp, ProjectionsDescription.cpp) rebuild clean and the diff is unchanged (2 source hunks + 05229_minmax_index_order_after_modify_column_after).

@groeneai

Copy link
Copy Markdown
Collaborator Author

Investigated. Your attribution holds, this diff is not on the path, and the owner is your own #118467. One correction: the memory is not going where the report puts it. What I measured from the job's artifacts:

Where the memory actually went. The detectFormatAndReadSchema -> URLReadBufferIterator::next stack is the exception trace of fuzzing steps 67 and 68, which both survived with Empty protocol in the URL. The step that killed the server is 71, and it never reached schema inference: file() expands {} globs in the path first, at StorageFile.cpp:355 -> expandSelectionGlob -> expandSelectorGlobImpl (src/Common/parseGlobs.cpp:213), before any directory listing and before a read buffer exists. That recursion rebuilds nearly the whole path at every level (parseGlobs.cpp:283-291) and keeps each copy alive across the recursive call, so a 3.0 MB path with 100,000 groups needs about 195 GB for one depth-first descent to reach its first result. The server log for query d782b58e holds only executeQuery, the analyzer's parallel-replicas notice, and CancellationChecker: Cancelling the task because of the timeout: 10000000 us ten seconds in, which the expansion never acts on: it kept allocating for another thirteen seconds until the kill, so a bound is also the missing cancellation point.

The same function is the entire stack of Segmentation fault (STID: 0250-04e2) (arm_asan_ubsan, 2026-09-15), where it exhausted the stack instead of the heap. One defect, two flavours.

Why max_server_memory_usage did not stop it. Limit 40.33 GiB; the tracked total climbed 36.71 -> 42.94 GiB while RSS climbed 45.55 -> 51.79 GiB, with Untracked memory across all threads steady near -14 MiB, so these allocations were accounted, not untracked. All 11 Code: 241 lines come from background system-log flushes (Allocator<> -> CurrentMemoryTracker::alloc, chunks of 4.0 to 4.9 MiB); the query thread raised none. That is #117916 precisely: min_allocation_size_to_throw_on_memory_limit defaults to 0, so CurrentMemoryTracker::allocThrow passes enforce_memory_limit = false for every operator new allocation and the std::string growth is counted but never refused. RSS then crossed the 53.78 GiB container limit and the memcg picked the server (oom_score_adj 555). The job-side half is #111892. Setting min_allocation_size_to_throw_on_memory_limit above max_untracked_memory in the fuzzer's server config would turn this class into an attributable Code: 241 naming the query, today, without any source change.

Does #118467 cover it. Yes, outright: 100,000 groups against MAX_SELECTOR_GLOBS = 1000 means expandSelectionGlob throws BAD_ARGUMENTS before expanding anything, MAX_EXPANDED_PATHS and MAX_EXPANDED_BYTES bound the product, and replacing the recursion with the iterative scanner removes the stack-overflow flavour too. file() inherits all of it, since the caps sit in expandSelectionGlob and StorageFile.cpp:355 calls it unchanged.

Seed. This targeted job prepared its corpus from 12 test files, one of which is your 05029_remote_description_deep_braces.sql (366ceaa03b17e), asserting TOO_DEEP_RECURSION for url(concat(repeat('{', 100000), ...)). The fuzzer rewrote url to file at step 71, where no equivalent bound exists. So any PR whose targeted selection picks 05029 can reproduce this until #118467 lands.

Breadth (CIDB, AST fuzzer jobs). OOM in dmesg has 5 rows ever: 3 in Nov 2025, then 2 today on two different PRs, at 14:33Z and this one at 18:34Z. The name is one day old for this class because #116359 (merged 2026-09-19 23:05Z) added the CONSTRAINT_MEMCG and Memory cgroup out of memory needles that the old grep missed; before that a memcg kill fell through to the fuzzer log parser and surfaced as Server unresponsive: memory limit exceeded, which is 82 rows over 34 distinct PRs and 3 true-master runs in 30 days, last seen 2026-09-19 21:55Z. The condition is neither new nor introduced here; only its name is.

This branch's record. AST fuzzer (amd_debug, targeted) ran on four heads and was green on three (5c218d49, 42f8a032, baf21870), red only on d56ca535. On 1035f95698ee it has not started yet (Fast test, Style check, Code Review, Config Workflow done, Build (arm_tidy) queued), and a re-run only re-rolls the fuzzer's own choices, so I would not read a green there as the condition being gone. No separate PR is needed from me for this red. Build profile diff stays with #118708.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120862&sha=1035f95698ee5d722dce82e0e5e9bbb91739c302&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The AST fuzzer (amd_debug, targeted) red from the previous run is gone. The two remaining reds are both unrelated to this PR:

  • Performance Comparison (arm_release, master_head, 1/6): the only "slower" query is order_by_read_in_order #1, 17.7ms -> 20.9ms (+17.8%), exactly at the +17.8% threshold, i.e. a 3 ms absolute move on a 18 ms query. On master itself, where old and new are the same binary, this query swings by at least that much in 85 of the last 337 runs (25.2%) of the same arm/master_head shard over the last 14 days (for example 308b1b7a: 14 ms vs 20 ms, 762fe113: 17 ms vs 22 ms). It is measurement noise, not a regression. This PR only sorts the min-max slot order by partition-key column name in MergeTreeData::getMinMaxColumns and ProjectionDescription::getMinMaxCountProjection; both run when a part's index is built or loaded, the hits_100m_single partition key is a single column, and the sort of a one-element vector cannot cost 3 ms in an ORDER BY ... LIMIT read-in-order query.
  • Build profile diff: still the CI-logs-cluster infra error (RuntimeError: CI logs cluster query failed), not a build problem. Report the CI logs cluster's error when a Build profile diff read fails, and skip if it is unavailable #118708 was closed; CI: "Build profile diff" is green when the CI logs cluster does not answer #121048 ("Build profile diff is green when the CI logs cluster does not answer") is open and is the fix.

Merged master again on top (ce46017022c2, merge-clean, 311 commits behind before the merge) to re-run CI on a current base. The diff is unchanged (2 source hunks plus 05229_minmax_index_order_after_modify_column_after), and both changed translation units rebuild clean.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Investigated Performance Comparison (arm_release, master_head, 1/6) on 1035f956. Your read is right, and I can add why the check still went red: two independent things, neither of them this PR.

1. What actually failed the check. In master_head mode the praktika status comes only from perf_dashboard_gate, not from the shard's "N slower" count (ci/jobs/performance_tests.py, the final else in insert_report_aggregates). It printed exactly one blocking row:

Dashboard slowdown: order_by_read_in_order #1 0.0177 -> 0.0209 (+17.8%), tier [confirmed_regression]

The bar for that verdict is the dashboard's own adaptive threshold, and for this query it was 10.3% (/api/v1/runs/pr-120862-1035f956.../confidence?metrics=client_time, module C3: Baseline floor 2.0%, History noise 5.2%, Adaptive threshold 10.3%; C4: Typical variation 5.2%, Slowdown / variation 3.446).

5.2% is the wrong number for this query. On master itself (query_metrics_v2, pr_number = 0, arch = 'arm', last 14 days) it has 558 measurements, of which 144 (25.8%) moved by at least 17.8%, p99 |diff| = 39.8%, max 51.1%. So the run was judged 3.4x over a bar sitting near the 26th percentile of this query's ordinary master noise. The same API response already carries the contradicting evidence and does not use it to demote the tier:

flakyLately: rank 2, score 1113, masterFlags 184, positiveFlags 810, negativeFlags 706, directionFlip true, windowDays 14

That tier logic lives in the dashboard service, not in this repository, so it is not fixable by a PR here.

2. This shard also lost its learned thresholds. Select historical data got three requests.exceptions.ReadTimeout on play.clickhouse.com (read timeout=10), then continued with an empty file:

01:26:42 WARNING: Failed to fetch historical thresholds, will proceed without them
01:26:42 Run command: [touch .../perf_wd/historical-thresholds.tsv]

So all 206,016 rows of all-query-metrics.tsv carry changed_threshold = 0.15 / unstable_threshold = 0.25, the bare floors, where this query's learned threshold is 0.65 (ceil(1.5 * p99, 2), p99 |diff| = 42.8% over 1974 master measurements). That floor is the only reason the report also printed "1 slower": changed_fail is 0.178 > 0.15 and 0.178 >= 0.178. At 0.65 it is not in the list.

The fix is already in flight, and it is a pair:

Both are open, so I am not opening a third PR for this.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120862&sha=ce46017022c2706b5b7538329364b78c8a62646c&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

Status of the two reds on ce460170, neither caused by this PR:

@groeneai

Copy link
Copy Markdown
Collaborator Author

Both are still open, so there is nothing to link as merged yet, and I will post the merge links here.

One thing worth flagging about the order they land in: #121189 is itself red on Performance Comparison (arm_release, master_head, 3/6), through the same dashboard-only path that #121090 removes, on a different query (job):

Dashboard slowdown: optimize_time_filter_with_preimage #1 0.30469998717308044 -> 0.3824999928474426 (+25.5%), tier [confirmed_regression]
Fail [Performance Comparison (arm_release, master_head, 3/6)]
  | 5 too long, 1 unstable; 1 confirmed regression(s) on the performance dashboard

That message carries no "N slower" phrase, and report.py appends one whenever the count is nonzero (ci/jobs/scripts/perf/report.py:713-731), so no query on this shard cleared compare.sh's changed_fail, and in master_head mode the dashboard verdict is the only thing that can set FAIL (ci/jobs/performance_tests.py, the final else in insert_report_aggregates). Zero shard-side confirmation is exactly the condition #121090 requires, so with it in, that row is filtered out.

#121090 is green on all six perf shards with Mergeable Check passed, and has had no human review since I opened it on 2026-09-19. Merging it first also clears #121189's own CI on its next run.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status 2026-09-22: merged master again (8b9f6a9bce12, merge-clean) to pull in #121477, the revert of #121096 that owns the only red on 7468977afd74 (test_max_bytes_ratio_before_external_distinct[server], MEMORY_LIMIT_EXCEEDED on the trimmed query in Integration tests (amd_asan_ubsan, db disk, 1/8)). The PR diff is unchanged; both changed translation units rebuild clean on the merged head.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
Merged via the queue into ClickHouse:master with commit c8e4b84 Sep 22, 2026
177 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 Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Neither #121189 nor #121090 will land: @ fm4v closed both unmerged on 2026-09-23 in favor of #121847, which merged as da7ece5f93aa and fixes the missing learned thresholds at the source (a 10 s CIDB timeout on a query that takes 8 to 10 s, plus an event_date written in local time rather than UTC), with the noisy-query half moved to the dashboard's own confidence scoring. The merge-order note above is therefore moot.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

Logical error: 'Part minmax index by time is neither DateTime or DateTime64'

3 participants