Skip to content

Fix aggregate projection not used with IS NULL under the analyzer - #126018

Open
amosbird wants to merge 13 commits into
ClickHouse:masterfrom
amosbird:fix-projection-is-null-analyzer
Open

amosbird wants to merge 13 commits into
ClickHouse:masterfrom
amosbird:fix-projection-is-null-analyzer

Conversation

@amosbird

@amosbird amosbird commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

When a query uses an aggregate projection like SELECT countIf(type IS NULL), the analyzer folds isNull(non_nullable_col) into a constant, so the aggregate argument in the query DAG is a constant column named _CAST(0_UInt8, 'UInt8'_String) while the projection DAG stores a constant named isNull(type). matchTrees never matches these nodes by name, the projection is rejected, and with force_optimize_projection = 1 the query fails with PROJECTION_NOT_USED.

Fix: in matchAggregateFunctions, when a query argument node has no match but both the query and the projection argument nodes are constant COLUMNs of the same type, compare the constant values and consider the arguments matching when they are equal.

Closes: #68949

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):

Fix aggregate projections not being used for queries with IS NULL / IS NOT NULL over non-nullable columns under the analyzer (the query failed with PROJECTION_NOT_USED when force_optimize_projection = 1).


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

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bbf9d01]

Summary: ✅


AI Review

Summary

The PR matches folded null-check constants to aggregate projection arguments and invalidates dependent projections after column replacement. One correctness blocker remains: cancelling the invalidation mutation re-enables incompatible stored states and changes query results.

Findings

❌ Blockers

  • optimizeUseAggregateProjection.cpp:826: absence of pending mutations does not establish projection validity. Insert (NULL, 1) into a nullable column with null-check count projections, stop merges, replace it with a non-nullable column using alter_sync = 0, then cancel the mutation with KILL MUTATION. On the PR head's Fast test binary, projection-disabled queries return (0, 2), while projection-preferred queries return (1, 1); EXPLAIN confirms the stale projection is read. Cancellation removes the snapshot guard before CLEAR PROJECTION executes. Preserve or verify validity across cancellation before accepting constant equivalence. Existing finding reopened with reproduction.
Tests
  • ⚠️ Add a focused stateless regression for cancellation between column replacement and projection clearing, comparing projection-enabled and disabled results. Both existing added regressions pass but omit this transition.
Final Verdict

Status: ❌ Block. Prevent cancelled invalidation from exposing stale projection states, and cover the cancellation sequence.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 15, 2026
The analyzer folds functions with a constant result over non-constant
arguments (e.g. isNull(string_col) -> 0), and so does the classic
interpreter used to analyze projection queries. Both DAGs end up with a
plain constant column, but under different names (_CAST(0_UInt8, ...)
in the query vs isNull(type) in the projection), so matchTrees finds no
match for the aggregate argument and the projection is rejected. With
force_optimize_projection = 1 the query fails with PROJECTION_NOT_USED.

Fix: in matchAggregateFunctions, when a query argument node has no match
but both the query and the projection argument nodes are constant COLUMNs
of the same type, compare the constant values and consider the arguments
matching when they are equal.

Fixes: ClickHouse#68949
@amosbird
amosbird force-pushed the fix-projection-is-null-analyzer branch from 083f7ab to 03b96b7 Compare October 15, 2026 13:05
@clickhouse-gh clickhouse-gh Bot added comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). external Author is not a member of the ClickHouse organization labels Oct 15, 2026
@arsenmuk arsenmuk added the can be tested Allows running workflows for external contributors label Oct 16, 2026
@amosbird

Copy link
Copy Markdown
Collaborator Author

Merged current upstream master in 672f2d0, including c14207b which fixes the gtest_functions_stress.cpp compilation failure after StackTrace::tryResolveAddress changed to return a value. The failure also occurred on master: https://github.com/ClickHouse/ClickHouse/actions/runs/38884911247/job/116920919005 . Local Docker builds now pass for both clickhouse and unit_tests_dbms (including the previously failing translation unit). Selected stateless tests: 87 passed, 0 failed; the projection regression passes. This push triggers fresh CI and sync checks.

if (identifier)
{
const auto column = metadata_snapshot->getColumns().tryGetPhysical(identifier->name());
if (column && !canContainNull(*column->type))

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.

❌ Check the materialization schema before equating null checks

The current table schema does not prove that existing projection states were computed over a non-nullable column. A supported drop/re-add can replace a nullable column while retaining projection states computed from its old values. This new match then reads those states for the newly folded constants and returns incorrect results.

Reproduced on a standalone server using this head's Fast test binary:

CREATE TABLE t
(
    k UInt8,
    x Nullable(UInt8),
    PROJECTION p (SELECT countIf(x IS NULL), countIf(x IS NOT NULL))
)
ENGINE = MergeTree ORDER BY k;
INSERT INTO t VALUES (1, NULL), (2, 1);
ALTER TABLE t DROP COLUMN x, ADD COLUMN x UInt8;

SELECT countIf(x IS NULL), countIf(x IS NOT NULL)
FROM t SETTINGS optimize_use_projections = 0;
SELECT countIf(x IS NULL), countIf(x IS NOT NULL)
FROM t SETTINGS prefer_optimize_projection = 1;

The results are (0, 2) and (1, 1) respectively, and EXPLAIN confirms ReadFromMergeTree (p) for the second query. Please reject or invalidate affected projection parts across schema changes before admitting this equivalence, and add a stateless regression for this DDL sequence. Checking only metadata_snapshot here cannot establish the required invariant for already stored states.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in bbf9d01. The extra null-check constant match is disabled while metadata/alter mutations are pending. For completed column replacement, dependent projection data is invalidated by generated CLEAR PROJECTION mutations; original declaration AST dependencies are retained even when analysis folds them away. The declaration remains available for new inserts. New regression 05407_projection_null_check_drop_readd covers pending drop/readd, synchronous completion, preservation of an unrelated projection, new inserts, subsequent merges, and originally folded dependencies. Docker build passes; all 72 selected tests pass, including the original forced-projection regression.

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.

The stored-schema mismatch is still present at src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp:826: cancelling the mutation makes both snapshot checks false without executing the generated CLEAR PROJECTION.

Reproduced with the Fast test binary for bbf9d012fd7e6c8704e24886228dbf67f2d2103c:

CREATE TABLE t
(
    id UInt64,
    x Nullable(UInt8),
    PROJECTION p (SELECT countIf(isNull(x)), countIf(isNotNull(x)))
)
ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, NULL), (2, 1);
SYSTEM STOP MERGES t;
ALTER TABLE t DROP COLUMN x, ADD COLUMN x UInt8 SETTINGS alter_sync = 0;
KILL MUTATION WHERE database = currentDatabase() AND table = 't' SYNC;

SELECT countIf(isNull(x)), countIf(isNotNull(x)) FROM t
SETTINGS optimize_use_projections = 0;
SELECT countIf(isNull(x)), countIf(isNotNull(x)) FROM t
SETTINGS prefer_optimize_projection = 1;

The results are (0, 2) and (1, 1) respectively; EXPLAIN confirms ReadFromMergeTree (p). Before cancellation, both queries correctly return (0, 2). StorageMergeTree::killMutation erases the pending commands and decrements their counters, while the table schema and old projection part survive.

Projection validity needs to survive cancellation, rather than depending solely on the presence of the clearing mutation. Please retain or verify sufficient validity information before admitting these stored states, and add this cancellation sequence to the regression coverage.

@clickhouse-gh

clickhouse-gh Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bbf9d012f with master 110043e5d (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.

Object file sizes

5 object files changed (+29.11 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp.o 714.50 KiB 734.41 KiB +19.91 KiB (+2.79%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

Disable constant null-check matching while the read snapshot has pending metadata or alter mutations; ordinary aggregate matching remains unchanged.

Generate `CLEAR PROJECTION` mutations for original projection declarations depending on a dropped source column, including AST dependencies erased by folding. Reuse `DROP_PROJECTION` with `clear = true` to remove old parts without removing the declaration.

Add `05407_projection_null_check_drop_readd` for pending and synchronous drop/readd, targeted invalidation, new inserts and merges, and originally folded dependencies. Preserve `05401_projection_is_null_analyzer` unchanged. Builds and tests intentionally not run yet.

Related: ClickHouse#126018

Review: ClickHouse#126018 (review)
@amosbird

Copy link
Copy Markdown
Collaborator Author

@groeneai, investigate the unrelated decimal failure: https://github.com/ClickHouse/ClickHouse/actions/runs/39131273659/job/117721298843 and provide a fix in a separate PR. If a fix is already in progress, link it here. 05339_decimal_wide_comparison_scale_overflow fails on the remote _CAST('1', 'Decimal(18, 18)') with ARGUMENT_OUT_OF_BOUND. The test was added by #124680 and creates no projections. The randomized-settings reruns in the job passed 111/111; this is not evidence that the original failure is fixed.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the 05339_decimal_wide_comparison_scale_overflow ARGUMENT_OUT_OF_BOUND failure on the remote _CAST('1', 'Decimal(18, 18)'); I'll follow up here with a fix PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #126652. toDecimal64(1, 18) is a Decimal(18, 18) holding 1, more digits than its precision, and the analyzer sent it to the replicas as _CAST('1', 'Decimal(18, 18)'), which their String to Decimal conversion rejects. You are right that the passing reruns prove nothing: with parallel_replicas_local_plan = 1 the other replicas fail in every run, and the client sees it only when the error arrives before the coordinator cancels them. It reproduces every time with remote() and prefer_localhost_replica = 0, and #126652 sends such a value as its native integer reinterpreted into the type.

middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 28, 2026
…o other servers

A `Decimal(P, S)` value is bounded only by its native integer, not by `P`:
`toDecimal64(1, 18)` is a `Decimal(18, 18)` holding 1, and
`toDecimal32(0.6, 9) + toDecimal32(0.6, 9)` is a `Decimal(9, 9)` equal to 1.2.
The analyzer printed every `Decimal` constant for another server as
`_CAST('<text>', '<type>')`, and the receiver's `String -> Decimal` conversion
(`readDecimalText`) rejects more integer digits than `P - S`, so `remote()`,
`Distributed`, parallel replicas, `IN` sets, the filter pushdown and
`serialize_query_plan = 1` failed with `ARGUMENT_OUT_OF_BOUND` where the local
query succeeded. Released 26.3 and 26.8 behave the same.

Under the ParallelReplicas CI configuration (`parallel_replicas_local_plan = 1`)
the other replicas hit this error in every run of
`05339_decimal_wide_comparison_scale_overflow`, but the coordinator usually
cancels them first, which is why the test failed only once (PR ClickHouse#126018).

A value with `|raw| >= 10^P` (exactly the condition `readDecimalText` rejects) is
now sent as its native integer reinterpreted into the type,
`_CAST(reinterpret(_CAST('<raw>', 'IntN'), T), T)`: a same-width `reinterpret`
copies the bytes, and the outer `_CAST` over constants keeps
`receivedFromInitiatorServer()` true, so the receiver names the column like the
initiator. Values within the precision keep their text form byte-for-byte.
26.3, 26.8 and 26.9 receivers evaluate the new form exactly. Same form as
ClickHouse#126262 uses for `DateTime64` ticks.

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

This branch has not been deployed

No deployments
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-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Projection is not used when using IS NULL and analyzer is enabled

3 participants