Skip to content

Compare aggregate function state constants by function and state - #124867

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/aggregate-state-constant-identity
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/aggregate-state-constant-identity

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #122362

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 wrong results when two expressions differ only in an aggregate function state constant, for example initializeAggregation('groupArrayState', 'x') and initializeAggregation('groupArrayState', 'y'), or quantileState(0.5) and quantileState(0.9) of the same data. Such constants were treated as the same value, so a filter, an IN subquery or a subquery column could use the other one, and a conflicting alias was not reported.

Description

On 26.8.18.2, SELECT number, a FROM (SELECT number, finalizeAggregation(materialize(arrayReduce('quantileState(0.5)', [1, 2, 3, 100]))) + number AS a FROM numbers(2)) WHERE finalizeAggregation(materialize(arrayReduce('quantileState(0.9)', [1, 2, 3, 100]))) + number > 50 returns no rows instead of two, and a subquery whose two columns differ only in an aggregate state constant returns the first column twice. The second shape is the Subquery wrap oracle mismatch of AST fuzzer (amd_release, oracle) on #122362 (job.log).

ConstantNode::isEqualImpl and the ActionsDAG constant deduplication (ConstantKeyEqual) compare constants with IColumn::compareAt, which returns 0 for any two aggregate function states, and DataTypeAggregateFunction::equals compares normalized state types, so quantile(0.5) and quantile(0.9) states with equal bytes also match. The duplicate alias check, GROUP BY validation and the projection rename then treat two different constants as one, and mergeExpressions evaluates the filter with the other constant. The tree hash, the only key of IN subquery sets, also ignores the parameter values.

Both places now also compare the nested aggregate functions, including those in a state's argument types, with their parameters (other argument types stay with equals) and, walking the columns, the states position by position; both constant hashes add the functions. sameConstantValue moves from ActionsChain.cpp to Field.cpp and replaces the Field comparison of the constant projection rename and of matchTrees (read-in-order and aggregate projection matching), which threw Code: 43 for different functions.

Not covered: a state stored inside Dynamic or JSON keeps the previous comparison.

The new test fails on master and passes with the fix.

🤖 Generated with Claude Code


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

IColumn::compareAt returns 0 for any two aggregate function states, and
DataTypeAggregateFunction::equals compares normalized state types, so two
constants holding different states (or the same bytes of different
functions, e.g. quantileState(0.5) and quantileState(0.9)) were the same
constant in ConstantNode::isEqualImpl and in the ActionsDAG constant dedup.
Both now also compare the names of the nested AggregateFunction types and
the states position by position, walking the columns instead of building
a Field of the whole value, which cannot hold an array of more than
1000000 elements; values inside Dynamic and JSON are not looked into.
Both constant hashes add the same names: IDataType::updateHash skips
aggregate function parameter values, and the tree hash alone keys IN
subquery sets. Move sameConstantValue from ActionsChain.cpp to Field.cpp
(iterative, with Object) and use it in the projection rename, whose
Field != threw for states of different functions.

Co-Authored-By: Claude Opus 5.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 Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

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

Pre-publication review: my own cold review plus an independent model (engine: codex; 6 rounds; the last round found nothing).

# Sev Finding Verdict Evidence / action
1 ⚠️ Comparing Dynamic/JSON constants through their Field calls ColumnDynamic::get, which misreads (and can throw on) a state in the shared variant AGREE, fixed The comparison walks the columns and never reads a Dynamic/JSON column; control test line
2 ❌ The tree hash ignores aggregate function parameter values, so two IN subqueries over quantileState(0.5) / quantileState(0.9) of the same data share one set AGREE, fixed Both constant hashes add the names of the nested AggregateFunction types; test line added
3 ❌ Hashing the whole type name made equal constants hash differently (a DateTime time zone is in the name, not in equals), so a GROUPING argument missed its key AGREE, fixed Only the nested AggregateFunction type names are hashed; test line with an omitted and a spelled-out zone
4 ⚠️ A state next to a Dynamic or JSON value (another Tuple element) still compared as before AGREE, fixed The column walk compares it; a state inside Dynamic keeps the previous comparison; test line
5 ❌ Building a Field of the whole constant rejects a valid query with an array of more than 1000000 states (TOO_LARGE_ARRAY_SIZE) AGREE, fixed States are compared position by position without a Field of the whole value; boundary test line
6 ⚠️ A test line pinned two different DateTime time zones as one expression AGREE, fixed Replaced by an omitted zone and the same zone spelled out (session_timezone = 'UTC')
7 ⚠️ The filter test line does not prove that mergeExpressions ran DISAGREE Master returns no rows for it only through that merge (2 rows with query_plan_merge_expressions = 0); reverting the fix brings the empty result back
8 💡 matchTrees still compares constants with Field ==, which throws for states of different functions noted No reachable input found
9 ❌ Different states under Nullable(Tuple(...)) were still one constant: the column walk skipped Nullable AGREE, fixed The walk descends into non-NULL Nullable rows; test line

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261009-085200

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, no settings involved: SELECT * FROM (SELECT concat(initializeAggregation('groupArrayState', 'x'), toString(number)) AS r, concat(initializeAggregation('groupArrayState', 'y'), toString(number)) AS r FROM numbers(2)) returns x0 x0 / x1 x1 on master, 26.8.18.2 and 26.3.42.3; the planner filter query in the description returns 0 rows on master and 26.8.18.2.
b Root cause explained? Constant identity in ConstantNode::isEqualImpl and in ActionsDAG's ConstantKeyEqual uses IColumn::compareAt, which returns 0 for any two aggregate function states, and DataTypeAggregateFunction::equals compares normalized state types. Every isEqual caller (duplicate alias check, GROUP BY validation, projection rename) and the planner constant deduplication then treat two different constants as one.
c Fix matches root cause? Yes: the two identity predicates also compare the nested AggregateFunction type names and the states position by position (a column walk, no Field of the whole value), and the rename's throwing Field != uses sameConstantValue. compareAt, an ordering primitive, is unchanged.
d Test intent preserved / new tests added? New test 05356_aggregate_state_constant_identity: the alias check (plain, wrapped, quantile 0.5/0.9, nested in Array/Map/Tuple/Variant/Nullable(Tuple)), the planner filter, two IN subqueries over quantile 0.5/0.9 states, GROUPING keys (a DateTime zone omitted vs spelled out; more than a million states), the constant rename, repeated tuple element names, GROUP BY in both directions, different states beside a Dynamic value, and positive controls where equal states stay equal (also inside Dynamic(max_types=0)).
e Both directions demonstrated? Fails on a master server with and without random settings; passes on the fix server 1x and 50/50 with random settings (randomization confirmed in system.query_log).
f Fix is general across code paths? Every site that decides constant identity was checked: the analyzer node comparison, the ActionsDAG deduplication, the projection rename and the hash-only consumers of the tree hash (IN subquery set keys) are fixed; Field == sites stay as they are (they throw on a function mismatch rather than merging).
g Fix generalizes across inputs (params/datatypes/wrappers)? States nested in Array, Map, Tuple, Variant and Nullable(Tuple) are covered and tested; a state cannot be directly inside Nullable or LowCardinality. Not covered: a state stored inside Dynamic or JSON, which keeps the column comparison, as on master.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change. A conflicting alias over aggregate state constants, accepted with a wrong result before, now fails with MULTIPLE_EXPRESSIONS_FOR_ALIAS like the same query over String constants.
i Invariants and contracts preserved? Both predicates only gain a conjunct, so they stay symmetric and everything equal now was equal before. Both hashes add only the nested AggregateFunction type names, which the predicates compare, so equal constants still hash equally. No Field of a whole constant is built, and Dynamic/JSON columns are not read.

Session id: cron:clickhouse-impl-slot-40:20261009-014700

@groeneai
groeneai requested review from novikd and yariks5s October 9, 2026 09:19
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f409687]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR distinguishes aggregate-state constants by function, parameters, versions, and serialized values in analyzer and optimizer identities. The main regression test matches its reference on the PR-head Fast test binary, but wrapper casts still let different live functions share an identity and produce wrong results. One earlier time zone finding also remains reproducible and is tracked separately.

Findings

❌ Blockers

  • src/DataTypes/DataTypeAggregateFunction.cpp:641: The declared type does not identify the function actually held by the column. Inline finding. A normalized-equal tuple cast can retain a quantile(0.9) column under a declared quantile(0.5) type. The new comparison reads only state bytes, and both hashes read function metadata only from the declared type. Consequently, independently evaluated values 2.5 and 70.9 become 2.5, 2.5 when selected together; two IN subqueries share one set and return a count of 1 instead of 2; expression merging drops both matching rows. Verified on the PR-head Fast test binary. Ensure column/type agreement before identity construction, or include the actual column function consistently in equality and both hashes.

    WITH
        arrayReduce('quantileState(0.5)', [1, 2, 3, 100]) AS lo,
        tupleElement(CAST(
            tuple(arrayReduce('quantileState(0.9)', [1, 2, 3, 100])),
            'Tuple(AggregateFunction(quantile(0.5), UInt8))'), 1) AS hi
    SELECT count() FROM numbers(100)
    WHERE number IN (SELECT toUInt64(finalizeAggregation(materialize(lo))) AS v)
       OR number IN (SELECT toUInt64(finalizeAggregation(materialize(hi))) AS v);
  • src/DataTypes/DataTypeAggregateFunction.cpp:603 [dismissed by author -- https://github.com/Compare aggregate function state constants by function and state #124867#discussion_r4506596349]: Finalization-relevant argument time zones still share an identity. Counting numbers matching either finalized hour of argMaxState constants over DateTime('UTC') versus DateTime('Asia/Tokyo') still returns 1 instead of 2 on this head: equal bytes and normalized-equal argument types conceal the distinct hours 0 and 9. The author moved the fix to PR #117161, which remains open; that explains the decision but does not change this head's result.

Tests
  • ⚠️ Extend 05356_aggregate_state_constant_identity with a wrapper cast that leaves the declared aggregate function different from the live column function. Check independent evaluation against shared IN sets and merged versus unmerged filters; the current tests only distinguish functions visible in the declared type.
Final Verdict

Status: ❌ Block

Fix the wrapper-cast identity gap and add focused regression coverage. The earlier time zone issue remains tracked in PR #117161; incorporate or land that fix before treating that finding as resolved.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 9, 2026
The constant identity compared the full names of the nested
AggregateFunction types, which spell argument types that equals ignores
on purpose (LowCardinality, which the aggregate function factory strips,
and time zones), so two spellings of one state, e.g.
AggregateFunction(argMax, LowCardinality(String), DateTime) and
AggregateFunction(argMax, String, DateTime), became a conflicting alias.
Compare and hash only the state version, the function name and its
parameters, which equals no longer sees after normalization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/Field.cpp Resolved
…rees

matchTrees compared an unmapped constant child with Field ==, which throws
ILLEGAL_TYPE_OF_ARGUMENT for states of different functions whose types
IDataType::equals considers equal, e.g. quantileState(0.5) and
quantileState(0.9). A query ordering or grouping by such an expression over
a table whose sorting key or aggregate projection uses the other one failed
in read-in-order or projection matching. Use sameConstantValue, which
compares those states as different, so the trees do not match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The line checks that a constant of more than 1000000 elements carrying an
aggregate state is compared without building a Field of it. It used an array
of 1000001 countState values, which took about 7 s alone under ASAN and made
the test exceed 180 s in the flaky check. The cap of ColumnArray::get is a
compile-time constant, so keep the array length and put a single state next
to range(1000001) instead. The line still fails with TOO_LARGE_ARRAY_SIZE on
the earlier Field-based comparison, and takes about 1.5 s under ASAN.

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

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b6259d7

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR: Code: 60 UNKNOWN_TABLE for _materialized_cte_c_* when a MATERIALIZED CTE is read twice inside an IN subquery under parallel replicas. 140/140 reruns pass; 36 PRs show it since 2026-10-08 #123121 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines not from this PR: under DatabaseReplicated the test's last query_log check counts the CREATE DICTIONARY row twice (0 2 instead of 0 1; the password stays hidden). 180 PRs show it since 2026-10-02 #124928 (external, merged 17:58Z). This run was dispatched at 15:19Z, before that merge, so I will merge master here to pick it up
Mergeable Check, PR praktika rollups of the two stateless rows above (Failed: 2) #123121 (mine, open), #124928 (external, merged)

The earlier Stateless tests (amd_asan_ubsan, flaky check) red of my own test 05356_aggregate_state_constant_identity (2 of 50 runs over 180 s, on 7fe8cd0) is fixed in this PR @ b6259d7: all five flaky checks are 50/50 on this head.

Session id: cron:our-pr-ci-monitor:20261009-230008

Comment thread src/Analyzer/ConstantNode.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f40968715 with master f4b38120c (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

181 object files changed (+21.31 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/DataTypeAggregateFunction.cpp.o 199.42 KiB 215.73 KiB +16.30 KiB (+8.18%)

716 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7fff5c8

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) TSan report in vendored contrib/aws-c-common, not from this PR (which changes how the analyzer identifies aggregate-state constants): ThreadSanitizer: data race contrib/aws-c-common/source/arch/intel/cpuid.c in aws_common_private_has_avx2. First seen 2026-10-10 00:23Z; 7 PRs and 3 master commits so far, also in amd_tsan integration tests #125039 (mine, open)
Stateless tests (arm_asan_ubsan, azure, sequential) job timeout, not from this PR: all 1180 tests finished (1082 passed, 98 skipped, none failed), then the job hit its 9000 s limit while exporting logs. The same job-level error hit 177 PRs and 25 master runs in 7 days #123849 (mine, open), which splits this job into 2 batches
Mergeable Check, PR praktika rollups of the rows above (the azure job is allow_failure) #125039 (mine, open), #123849 (mine, open)

Session id: cron:our-pr-ci-monitor:20261010-073010

…state-constant-identity

Resolve the conflict with ClickHouse#121725, which removed the `function` argument of
`DataTypeAggregateFunction::formatParameters`: `getAggregateFunctionNames`
now spells the parameters with the one-argument form, as `getNameImpl` does.

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

forEachInTypeTree does not descend into the argument types of an
AggregateFunction type, so AggregateFunction(groupArray,
AggregateFunction(quantile(0.5), UInt8)) and its quantile(0.9) counterpart
recorded only groupArray. IDataType::equals normalizes the nested
parameters away and the states serialize to the same bytes, so the two
constants were still merged: an IN over the two finalized values shared one
set, a filter on one was merged with the other expression, and a duplicate
alias over them was accepted.

Collect the aggregate functions with their parameters and state versions
from the argument types too. The rest of the argument types is still left to
IDataType::equals, so spellings such as LowCardinality(String) and String of
one state stay equal.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0563f9c

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
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) / 05355_top_k_dynamic_filter_single_sort_column_ties flaky, not from this PR: 2 of 50 runs gave cache read 0 instead of 1 (the same job had 48 OK, and the arm targeted job 50 of 50 OK). A parallel test that drops a UUID-less MergeTree table clears the query condition cache between the fill and the rerun; the same line also failed on master and on 3 other PRs #127694 (mine, open)
Finish Workflow / Post Hooks cascade of the row above: both Bugfix validation (functional tests) jobs and 71 other jobs were DROPPED due to that failure, so the post-hook saw no Bugfix validation result #127694 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #127694 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261024-180006

…state-constant-identity

Only the include lists of `DataTypeAggregateFunction.cpp` (master added
`ColumnReplicated.h`) and `ActionsDAG.cpp` (master added
`ColumnAggregateFunction.h`) conflicted; both sides' headers are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…state-constant-identity

# Conflicts:
#	src/Analyzer/ConstantNode.cpp
#	src/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp
{
Field lhs_state = (*lhs_column)[lhs_row];
Field rhs_state = (*rhs_column)[rhs_row];
return lhs_state.safeGet<AggregateFunctionStateData>().data != rhs_state.safeGet<AggregateFunctionStateData>().data;

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.

[Blocker] Include the function held by the column in constant identity

The declared type can disagree with the function in ColumnAggregateFunction: FunctionCast::prepareImpl uses an identity conversion for normalized-equal tuple types, retaining the original nested column. A cast from Tuple(AggregateFunction(quantile(0.9), UInt8)) to its 0.5 counterpart therefore leaves a column that still finalizes to 70.9, while its declared state type says 0.5. This branch compares only the serialized data, and both new hashes collect functions only from the declared type, so they still conflate that constant with the actual 0.5 state.

On the PR-head Fast test binary, this returns 1 instead of 2:

WITH
    arrayReduce('quantileState(0.5)', [1, 2, 3, 100]) AS lo,
    tupleElement(CAST(
        tuple(arrayReduce('quantileState(0.9)', [1, 2, 3, 100])),
        'Tuple(AggregateFunction(quantile(0.5), UInt8))'), 1) AS hi
SELECT count() FROM numbers(100)
WHERE number IN (SELECT toUInt64(finalizeAggregation(materialize(lo))) AS v)
   OR number IN (SELECT toUInt64(finalizeAggregation(materialize(hi))) AS v);

Evaluated independently, the two subqueries produce 2 and 70. Using the same pair in the PR's filter reproducer also returns no rows; disabling query_plan_merge_expressions restores both rows.

Please ensure column/type agreement before constructing constant identities, or consistently include the actual column function and its parameters in comparison and both hashes. Add a regression covering a state carried through a wrapper cast; extending the declared-type traversal alone cannot distinguish this pair.

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.

This returns 1 on master too, and the cause is the column rather than the identity: DataTypeAggregateFunction::equals ignores the quantile level, so a CAST inside a Tuple keeps the quantile(0.9) function under the declared quantile(0.5) type (70.9 here, while a top-level CAST to the same type and a MergeTree round trip of this value both give 2.5). With a column that agrees with its type, both constants are the same quantile(0.5) state and one set is correct, so I keep this PR's identity on the declared type.

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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant