Skip to content

Do not serve min/max from an unusable minmax_count projection bound - #115151

Merged
nihalzp merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-minmax-count-projection-unusable-bound
Aug 30, 2026
Merged

nihalzp merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-minmax-count-projection-unusable-bound

Conversation

@groeneai

@groeneai groeneai commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111938

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 min and max returning a wrong value when the implicit _minmax_count_projection answered them from a part-level bound that is not a real row value: a NULL in a Nullable sorting key, a NaN in a float key, or a Tuple bound assembled component-wise. Such a query now reads rows instead of using the projection.

Description

getMinMaxCountProjectionBlock answers min(col)/max(col) from part-level bounds, feeding each straight into an aggregate state. That is only correct when the bound is a real row value, ordered as the aggregate orders it. Three ways it is not:

  • NULL (as reported): keys sort NULLS LAST so the top index entry is a NULL while max skips NULLs, and the POSITIVE_INFINITY pruning sentinel materializes as a SQL NULL.
  • NaN, no Nullable involved: the writer sorts NaN above every number while max skips it, so Float64 ORDER BY k over (1),(200),(nan) gives nan.
  • Component-wise synthesis, no NULL or NaN: getExtremes runs per column, so a Tuple bound envelopes each component's extreme and need not be any row. This breaks min too.

Worse than the reported NULL is the silent shape: when the true maximum shares a part with a NULL, max returns the largest of the other parts, 4 instead of 200.

The fix declines the implicit projection for such a query, reusing the escape hatch this function already has earlier (return {} when a part has no final mark). A part whose bound pair is one repeated degenerate value stays exempt, since skipping it is the right contribution; for an index bound that exemption also requires a final mark, without which the index samples granule starts only and a repeated pair proves nothing.

I rejected skipping only the poisoned part, which is the silent shape above, and changing the write path, since the sentinel is needed for IS NULL pruning and existing parts would stay broken.

The new test covers each class across nullable, low-cardinality, tuple and float keys, ASC and DESC, one and several parts, and a part with no final mark. Issue #104412 is a different defect here, verified unaffected.


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

Version info

  • Merged into: 26.9.1.395 (included in 26.9 and later)

getMinMaxCountProjectionBlock answers min(col)/max(col) from part-level
bounds, feeding each bound straight into an aggregate state. That is only
correct when the bound is a real row value ordered the way the aggregate
orders, and there are three ways it is not:

- a NULL: keys sort NULLS LAST so the top index entry is a NULL while max
  skips NULLs, and on the computed-bounds path the POSITIVE_INFINITY
  pruning sentinel materializes as a SQL NULL;
- a NaN, with no Nullable involved: the writer sorts NaN above every
  number (KeyOrder.cpp) and max skips it (SingleValueData.cpp), so a plain
  Float64 sorting key holding a NaN answers max with nan;
- a Tuple bound, with no NULL or NaN involved: getExtremes runs per column,
  so the bound envelopes each component's extreme and need not be any row.
  This one returns a wrong min as well as a wrong max.

The reported symptom is max() returning NULL. The worse shape is silent:
when the true maximum shares a part with a NULL, that bound is skipped and
max returns the largest value of the remaining parts, so a table whose
maximum is 200 answers 4 with nothing to suggest the answer is wrong.

Decline the implicit projection for such a query, reusing the escape hatch
already present for a part with no final mark. The query then reads rows,
which was correct in every case measured. A part whose bound pair is one
repeated degenerate value stays exempt, since min/max skipping it is the
right contribution; that exemption matches by exact value, because
Range::createWholeUniverse() is [-Inf, +Inf] and both of those ends
satisfy Field::isNull(), so an isNull()-shaped test would re-admit a pure
sentinel pair and reintroduce the bug it exists to prevent.

The two bound sources need different predicates and this is deliberate.
Primary-key bounds are stored index rows, so a composite there is a
genuine value and rejecting it would needlessly lose the projection for
ORDER BY (a, b). Computed bounds may be synthesized, so a Tuple is
additionally suspect. Only ColumnTuple::getExtremes assembles a value;
ColumnArray, ColumnObject and ColumnMap select a real row, so the check
names Tuple rather than every composite.

Alternatives rejected: skipping only the poisoned part reproduces the
silent shape above, and making the write path NULL-aware would change the
on-disk MinMaxIndex format, do nothing for existing parts, and risk the
IS NULL pruning regression the sentinel's own comment documents.

The Field walk is iterative with an explicit worklist, as Field::isContainer
requires, because key values are user-controlled and can nest arbitrarily.

Closes: ClickHouse#111938
The degenerate-pair exemption added with the unusable-bound guard inferred
that both index ends being the same degenerate value means the part holds no
ordinary comparable value, so skipping it is the right contribution. That
inference needs the pair to sample the part's two physical ends, and it does
not when the part has no final mark: the index stores one entry per granule
start, and the actual last row is appended only under with_final_mark, which
is can_use_adaptive_granularity and therefore false at
index_granularity_bytes = 0. A single-granule non-adaptive Wide part has one
index entry, so lowest == highest while ordinary values sit unsampled below.

The pre-existing no-final-mark hatch does not cover this, because
ProjectionsDescription emits max(k), min(k) swapped for a reversed key and
primary_key_max_column_name is taken second from the end, so it names min(k)
on a DESC key. need_primary_key_max_column is then false for exactly the
DESC max(k) query that reads the last index entry. Since the writer passes
nulls_direction = 1 for both key directions
(MergeTreeDataWriter.cpp:791-793, and SortDescription.h:51 defines 1 as
"NULLs and NaNs are greater"), a NULL or NaN on a DESC key sorts physically
first and is that single entry, so max returned it: nan and NULL against a
correct value of 200.

Make the exemption conditional on the part having a final mark. Declining is
the safe direction, since it costs a projection rather than an answer. The
computed-bounds predicate keeps its unconditional exemption: those bounds
come from getExtremes over the whole column, so both ends are observed
whatever the granularity.

The narrow cost is a part that is both all-degenerate and non-adaptive,
which now reads rows instead of taking the exemption. Telling that apart
from a part with unsampled ordinary values would need its real last row,
which is the one value such a part does not store.
The two tables exercising the no-final-mark shape pinned
index_granularity_bytes, enable_mixed_granularity_parts and
min_bytes_for_wide_part, but not index_granularity. The test runner
injects a randomized MergeTree setting only when the name is absent from
the CREATE (ClientBase::addMergeTreeSettings), so index_granularity was
injected from random.randint(1, 65536).

On the non-adaptive path the granularity is used verbatim, so a 3-row
part gets ceil(3/g) marks. At g of 1 or 2 the part gains extra index
rows, the two ends of the index stop being the same degenerate value,
and the arm no longer reaches the repeated-degenerate branch it exists
to cover: it would pass with the fix reverted. It also makes the
part-shape assertions read 3 or 2 marks instead of 1, so the test fails.

The answers stay correct at every granularity, because on a DESC key the
NULL or NaN sorts physically first and remains the first index row.

Pinning the granularity in the CREATE is stronger than a settings clamp
comment: the name is then present, so the runner never injects it, and
there is no parse step that can fail silently. It also keeps the other
arms exercising randomized MergeTree settings, which a blanket
no-random-merge-tree-settings tag would not.

Verified with the runner's own injection flag: with the pin,
--index_granularity 1 and 2 both still produce a one-mark part and the
test passes; without it they produce three-mark and two-mark parts and
the test fails.
@groeneai

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

Three review rounds by an independent reviewer plus a second model, over five design rounds
before any code was written. The final round is clean: no blockers, no majors, nothing
outstanding.

Two real defects were caught and fixed during review, both in the test's ability to detect a
regression rather than in the fix itself:

  • The degenerate-pair exemption was unsound for a part with no final mark. Such a part's index
    stores granule starts only, so its last entry is not the part's last row and a repeated pair
    does not prove the part is free of ordinary values. Reachable on a DESC key, where the
    projection's max slot is named min(k) so the function's pre-existing no-final-mark hatch
    does not fire. Reproduced (max(k) returning nan against a control of 200, projection-served),
    then fixed by making that exemption conditional on the final mark.
  • The two tables added for the above pinned index_granularity_bytes but not index_granularity,
    which the test runner randomizes from 1 to 65536. Below 3 the three-row part gets more than one
    mark, the index ends stop being a repeated pair, and the arm never reaches the guard it is
    testing. Measured directly: unpinned at granularity 1 or 2 the arm passes even with the fix
    reverted. Fixed by pinning the setting in the CREATE, which the runner's injector respects.

Verification. Every guard was shown independently load-bearing by mutation: removing either
bound guard, dropping the depth walk, broadening either predicate, dropping the NaN half,
rejecting real infinities, spelling the exemption as "both ends are null", or making it
unconditional again - each makes the test fail. Two are worth naming. A null-shaped exemption
also admits the whole-universe bound pair and turns a correct query into Code: 170 BAD_GET.
An unconditional exemption brings back the wrong answers on a single-granule part while the
test's own part-shape rows stay green, which is what shows the fixture is really producing that
part shape.

Fifteen getExtremes implementations were enumerated to check the Tuple-only narrowing.
Array, Map and Object select a real row rather than assembling one, so rejecting them would
lose the projection for nothing; QBit, AggregateFunction, Variant and Lazy cannot be keys
at all.

Recorded honestly rather than as passes. Broadening the computed-bound guard beyond Tuple
moves no in-tree row, because those bounds are not projection-served today, so that narrowing
rests on reading each implementation. And the whole-universe bound is absent from the committed
test because it is not constructible from SQL: it needs a missing index file, and a stateless
test may not fabricate part files. It was verified in a throwaway binary instead.

Also noticed and deliberately not raised: ColumnAggregateFunction::getExtremes returns a
serialized default for both bounds and ColumnQBit::getExtremes synthesizes component-wise like
Tuple. Neither type can be a sorting or partition key, so there is no user-reachable
consequence.

@clickhouse-gh

clickhouse-gh Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20a8dd7]

Summary: ✅


AI Review

Summary

This PR makes _minmax_count_projection decline queries whose part-level bound cannot safely stand in for min or max because the bound is order-inconsistent (NULL or NaN) or, on the computed-bound path, a synthesized Tuple. The current head also closes the no-final-mark hole in the repeated-degenerate exemption and adds focused stateless coverage for the reported NULL, NaN, tuple-envelope, and no-final-mark cases. I did not find an unresolved correctness, performance, or metadata issue in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 20a8dd7.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 56/69 (81.16%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One clickhouse local script, no randomization needed. Pre-fix: max(k) gives \N (reporter fixture), 4 instead of 200 (max shares a part with a NULL), (NULL,2) instead of (5,3) (tuple key), (5,100) instead of (5,3) (tuple minmax column, no NULL), nan instead of 200 (float key, no Nullable), (nan,3) instead of (200,2) (nested NaN). Every arm confirmed projection-served via EXPLAIN.
b Root cause explained? Yes. getMinMaxCountProjectionBlock feeds a part-level bound straight into a min/max aggregate state, which is only valid when the bound is a real row value ordered as the aggregate orders. It is not for a NULL (keys sort NULLS LAST, max skips NULLs; the POSITIVE_INFINITY pruning sentinel becomes a SQL NULL), for a NaN (the writer passes nulls_direction = 1 for both key directions, MergeTreeDataWriter.cpp:791-793 with SortDescription.h:51, so NaN sorts above every number, while SingleValueData.cpp:341-352 skips it), or for a Tuple bound, which getExtremes assembles per component so it need not be any row. A fourth shape: a part with no final mark stores granule starts only, so its last index entry is not its last row and a repeated degenerate pair proves nothing about the part.
c Fix matches root cause? Yes. Declines the implicit projection for that query when a required bound is unusable, reusing the existing return {} escape hatch earlier in the same loop. The degenerate-pair exemption is itself conditional on the part having a final mark, since only then does the index pair sample both physical ends. No widened bound, no blanket no-random-* tag, no defensive masking, and the write-path sentinel is untouched because IS NULL pruning needs it.
d Test intent preserved / new tests added? New stateless test 04950_minmax_count_projection_unusable_bound. No existing test weakened or removed. Each no-final-mark arm asserts the part shape it depends on (Wide, one mark) beside its answer, so a fixture that stops producing that shape fails loudly instead of going vacuous, and the two tables pin index_granularity so the runner's MergeTree randomization cannot change the mark count. Verified with the runner's own --merge-tree-settings "--index_granularity 1" and 2: both still produce a one-mark part and pass, while the same injections against the unpinned form produce three-mark and two-mark parts and fail.
e Both directions demonstrated? Yes. The test reddens on the pre-fix binary with 44 differing lines and passes on the fixed one; the same 25-row matrix was run against both binaries with the Build IDs asserted (fd608268... pre-fix, a6e8d499... post-fix). The no-final-mark arms were measured the same way: \N and nan against a control of 200, both projection-served, before the guard; 200 and 200 with the projection declined after. Each arm prints its value beside its optimize_use_implicit_projections = 0 twin, so a regression shows as a mismatched pair.
f Fix is general across code paths? Both bound sources are guarded (primary-key index rows and computed partition/minmax columns), and both slots of each - which is how I found min is also wrong for a synthesized Tuple bound, not just max. The three sibling getExtremesNullLast callers (MergeTreeIndexMinMax.cpp:176, MergeTreeIndexSet.cpp:136 and :297) were read and excluded: they build pruning ranges, where the sentinel is correct by design, and never feed an aggregate.
g Fix generalizes across inputs (params/datatypes/wrappers)? Covered Nullable, LowCardinality(Nullable), Nullable(String), Nullable(Float64), Tuple(Nullable(...), ...), Array(Nullable(...)), and plain Float64/Float32/BFloat16; ASC and DESC keys; single and multiple parts; sorting-key and minmax-column paths; and the degenerate boundary pairs (all-NULL, all-NaN, whole-universe). Real inf/-inf stay usable, since only NaN is order-inconsistent.
h Backward compatible? (maintainer-approved exception only) Yes. No new or changed setting, no on-disk format change, no write-path change, so no SettingsChangesHistory.cpp entry and nothing to gate. Parts already written are fixed with no re-materialization; the only user-visible change is that some queries now return the correct answer and read rows to do it.
i Invariants and contracts preserved? The guard runs before any aggregate state is created, so the early return {} cannot leave a half-filled block, and the caller already handles an empty block. The Field walk is iterative with an explicit worklist per Field::isContainer (Field.h:629-635), so a deeply nested user-supplied key value cannot overflow the stack. Partition-value columns are deliberately untouched (they are GROUP BY keys, where a NULL is legitimate). The guard is per-slot, so min-only and count-only queries keep the projection.

Each guard was checked to be independently load-bearing by mutation: removing either bound guard, dropping the depth walk, broadening either predicate, dropping the NaN half, rejecting real infinities, writing the degenerate-pair exemption as "both ends isNull()", or making that exemption unconditional again instead of requiring a final mark - each makes the test fail. Two are worth naming. An isNull()-shaped exemption also admits the whole-universe pair [-Inf, +Inf] and turns a correct query into Code: 170 BAD_GET. And an unconditional exemption brings back \N/nan on a single-granule part with no final mark, while the test's own part_type, marks rows stay green, which is what shows the fixture really is producing that part shape rather than the arm being vacuous.

Two results recorded honestly rather than as passes. Broadening the computed-bound guard from Tuple to every non-scalar moves no in-tree row, because Array/Map/Object minmax bounds are not projection-served today; the narrowing to Tuple rests on reading each getExtremes implementation, where only ColumnTuple assembles a value. And the whole-universe row is absent from the committed test because it is not constructible from SQL: that loop iterates only partition-key columns, so the range requires a missing minmax_*.idx file, and a stateless test may not fabricate part files. It was verified in a throwaway binary instead.

Of the 302 minmax/projection tests I ran, 282 pass and 20 fail in my sandbox both before and after the change. I re-ran exactly those 20 against a pristine pre-change binary and the failing sets are identical, so none is caused by this change. They need infrastructure a bare local server does not have: ZooKeeper (Coordination::Exception, TABLE_IS_READ_ONLY), a cluster config (ALL_CONNECTION_TRIES_FAILED, Connection refused), or parallel replicas. The sibling no-final-mark test 04318_sparse_pk_index_analysis_last_mark_null passes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @hanfei1991, could you review this? getMinMaxCountProjectionBlock feeds a part-level bound straight into a min/max aggregate state, which is only valid when the bound is a real row value ordered as the aggregate orders it, so a NULL or NaN key end and a component-wise synthesized Tuple bound all produce wrong answers; the fix declines the implicit projection for those queries.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 17, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
A pull_request workflow run raised from a fork does not start until a
maintainer approves it. The run for the previous head was created but
never approved, so GitHub cancelled it 58 hours later with zero jobs.
That head therefore carries no check runs and cannot acquire any on its
own, since a cancelled run is terminal.

This commit is empty: its tree is identical to its parent's, so the code
under test is unchanged and the merge commit below it is untouched. It
exists only to raise a fresh run that can be approved.
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 20a8dd783 with master 194df773e (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c0938b0c2; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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

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

Compile time of recompiled translation units

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

Job report

@nihalzp
nihalzp added this pull request to the merge queue Aug 30, 2026
Merged via the queue into ClickHouse:master with commit 9b89056 Aug 30, 2026
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 Aug 30, 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-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.

Implicit minmax_count projection returns NULL for max() over a Nullable sorting key at default settings (max must skip NULLs)

4 participants