Skip to content

AST fuzzer oracle: recognise an aggregate hidden in an APPLY column transformer - #118224

Merged
alexey-milovidov merged 1 commit into
masterfrom
fix/ast-fuzzer-oracle-apply-aggregate
Sep 5, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
fix/ast-fuzzer-oracle-apply-aggregate

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

Related: #111327
Related: #99980

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

The AST fuzzer (amd_release, oracle) job on #111327 failed with a false TLP DISTINCT oracle mismatch on

SELECT DISTINCT a.* APPLY any APPLY toDate FROM columns_transformers AS a WHERE 100

The reference query returns one row, the partitioned UNION DISTINCT returns two: the WHERE not(100) partition has no input rows, and an aggregate without GROUP BY still returns one row on empty input, which the reference never produces.

The query is an aggregation, but QueryOracleChecker::hasAggregates did not see it. scanAggregatesSafe only recognises ASTFunction nodes, while SELECT * APPLY any stores the aggregate in an ASTColumnsApplyTransformer as a bare function name (or as a lambda that is not among the node's children). So the query was routed to the non-aggregate TLP / DISTINCT oracles, whose partitioning is invalid for aggregates.

The fix records such a transformer as an aggregate when its function name resolves to an aggregate function (combinators included, via AggregateFunctionFactory::isAggregateFunctionName) or when its lambda body contains one. hasAggregates then reports it, the non-aggregate oracles skip the query, and checkTLPAggregate rejects it because the node is not a rewritable ASTFunction. Window functions found inside the lambda are propagated too. A non-aggregate APPLY such as APPLY toString stays eligible for the oracles.

The new test 05097_ast_fuzzer_oracle_apply_aggregate runs the reported shape (and the APPLY max, lambda and minOrNull combinator forms) with ast_fuzzer_oracle = 1; the server trace on the private build shows the queries classified as agg=true and only the aggregate-safe identity / subquery-wrap oracles running. APPLY toString still goes through the TLP WHERE oracle and passes.

Failing report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111327&sha=54552ebb872436c9c49b255a436fbef738a967b8&name_0=PR&name_1=AST%20fuzzer%20(amd_release,%20oracle)


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

Version info

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

… transformer

`SELECT DISTINCT a.* APPLY any FROM t WHERE 100` aggregates every column, but the
aggregate is not an `ASTFunction`: `ASTColumnsApplyTransformer` keeps only the
function name (or a lambda that is not among its children). `scanAggregatesSafe`
missed it, so `hasAggregates` returned false and the query went through the TLP
DISTINCT oracle, where the `WHERE not(100)` partition still yields the single row
every aggregate returns on empty input, and the oracle reported a false
`AST_FUZZER_ORACLE_MISMATCH`.

Record such a transformer as an aggregate when its function name resolves to an
aggregate function (combinators included) or its lambda contains one.
`hasAggregates` then reports it, the non-aggregate oracles skip the query, and
`checkTLPAggregate` rejects it since the node is not a rewritable function.

Seen in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111327&sha=54552ebb872436c9c49b255a436fbef738a967b8&name_0=PR&name_1=AST%20fuzzer%20(amd_release,%20oracle)
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cca33c9]

Summary: ✅


AI Review

Summary

This PR teaches scanAggregatesSafe to notice aggregates hidden in an APPLY column transformer and adds a focused stateless regression test for the reported false oracle mismatch. The remaining problem is that the checker still reasons over the pre-expansion ASTColumnsApplyTransformer shape, while execution expands APPLY and can inline SQL UDFs afterward, so some unsafe APPLY forms are still misclassified. I would request one more fix here before merge.

Findings

⚠️ Majors

  • [src/Interpreters/QueryOracleChecker.cpp:982-995] The new branch only covers literal aggregate names or a lambda body that already contains a literal aggregate call in the raw AST. QueryOracleChecker runs on fuzzed_ast before column-transformer expansion, but execution expands APPLY later and can inline SQL UDFs after that. As a result, CREATE FUNCTION f AS x -> any(x); SELECT DISTINCT a.* APPLY f FROM t AS a WHERE 100 is still seen here as non-aggregate and can reach the non-aggregate TLP oracles. The same hidden-carrier issue also remains for non-deterministic APPLY bodies such as APPLY rand / APPLY (x -> rand()), because hasNonDeterministicFunctionsImpl still only walks children.
    Suggested fix: classify ASTColumnsApplyTransformer through a shared helper that also visits func_name / parameters / lambda and resolves SQL UDF bodies the same way execution does, or run the oracle classification on a post-expansion AST instead of the raw transformer form.
Final Verdict

Status: ⚠️ Request changes

  • Make the oracle safety analysis understand the remaining hidden APPLY carriers, especially SQL UDF expansion and non-deterministic bodies, so the fix matches the executed query shape rather than only the literal aggregate-name case.

LLVM Coverage Report

Measured on commit cca33c9.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 13/14 (92.86%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 5, 2026
/// every aggregate returns on no input — a false mismatch. Record the
/// transformer itself as an aggregate: `hasAggregates` then reports it, and
/// `checkTLPAggregate` rejects it because it is not a rewritable function.
if (const auto * apply = ast->as<ASTColumnsApplyTransformer>())

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.

This still leaves ASTColumnsApplyTransformer only partially visible to the oracle safety gates. QueryOracleChecker runs on the raw fuzzed_ast, but execution expands APPLY later (translateQualifiedNames / QueryTreeBuilder) and then resolves SQL UDFs. So a shape like CREATE FUNCTION f AS x -> any(x); SELECT DISTINCT a.* APPLY f FROM t AS a WHERE 100 is still classified as non-aggregate here and can reach the non-aggregate TLP oracles even though the executed query contains an aggregate. The same carrier problem also remains for hidden non-deterministic bodies such as APPLY rand or APPLY (x -> rand()), because hasNonDeterministicFunctionsImpl still only walks children.

I think this needs a shared traversal for the non-child func_name / parameters / lambda fields (or a post-expansion oracle check) instead of fixing only the literal aggregate-name branch here.

@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cca33c9ef with master d1adb9f9f (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

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
Merged via the queue into master with commit 3324e94 Sep 5, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/ast-fuzzer-oracle-apply-aggregate branch September 5, 2026 12:59
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026
diegomestre2 pushed a commit to diegomestre2/ClickHouse that referenced this pull request Oct 16, 2026
…n `APPLY` lambda

`QueryOracleChecker` already refuses a query whose `WHERE` or `HAVING` defines an
alias that the rest of the query uses, because an oracle which removes that clause
rebinds the identifier to a same-named table column and the two executions stop
being comparable. The guard, `clauseDefinesAliasUsedElsewhere` into
`referencesAnyAlias`, is a generic `children` walk, and
`ASTColumnsApplyTransformer` copies `parameters` and `lambda` by hand in `clone`
instead of registering them as `children`. A use inside an `APPLY` lambda is
therefore invisible to the guard, while the analyzer does resolve that lambda
against the parent query scope. The six clause-removing oracles then proceed and a
valid query is rejected with a false `AST_FUZZER_ORACLE_MISMATCH`.

Measured on `t(i Int32, a Int32)` holding `(1,100),(2,201),(3,302)`, where the
column deliberately differs from the alias so the rebinding changes rows rather
than spelling:

    SELECT * APPLY (x -> toInt32(x) + a) FROM t WHERE (i * 100 AS a) > 1

raised `Code: 906. TLP WHERE oracle mismatch!` with
`Only in partitioned: 202 401` (the alias `i * 100`) against
`Only in reference: 203 402` (the column). Over 8 fuzzed rounds per shape,
`ASTFuzzerOracleMismatches` was 6 for that spelling, 6 for `i + 1 AS a` and 6 for
the `COLUMNS('i')` form, and 0 after this change, while the alias-free control
kept its oracle checks (19 before, 31 after) so no coverage is traded away. The
same before and after pair holds for a `Nullable` or `LowCardinality` shadowing
column, an alias used in a nested lambda or in a scalar subquery inside the
`APPLY` lambda, and two chained transformers.

The loop is added to the traversal rather than to any oracle, so all seven call
sites in this file, that is six clause-removing oracles, are covered once. Making
`lambda` and `parameters` real `children` would fix every `children` walk in the
server at once, but it would newly descend every AST visitor into the lambda, so
the narrower per-screen route of ClickHouse#118224 and ClickHouse#121897 is kept here.

`hiddenApplyMembers` is copied byte-identically from ClickHouse#121897, which was still open
when this was written, at the same insertion point, so whichever merges second
resolves a duplicate definition by deleting one copy.

A third carrier of the same blindness, `arrayJoin` hidden in an `APPLY` lambda,
defeats `expressionContainsArrayJoin` in the same way and is measured, but that
helper is shared by eight non-oracle callers such as row policies, TTL and
constraints, so teaching it this node has a different blast radius and belongs
with ClickHouse#117791.

Related: ClickHouse#121897

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... and removed comp-testing Test content only (no production code). labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... pr-ci 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.

2 participants