Skip to content

AST fuzzer oracle: walk the hidden APPLY members in every eligibility screen - #122055

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:oracle-alias-in-apply-lambda
Oct 16, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:oracle-alias-in-apply-lambda

Conversation

@groeneai

@groeneai groeneai commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #121897
Related: #122118

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

ASTColumnsApplyTransformer keeps its lambda and parameters outside children. Only two
screens of QueryOracleChecker read them, so whatever an APPLY lambda holds passed every other
screen. Oracle checks on master, 6 fuzzed rounds per query, with t(i Int32, a Int32) =
(1,100),(2,201),(3,302):

inside the APPLY lambda master this PR
a subquery on system.processes, with FINAL, ANY JOIN, WITH FILL, a Distributed table or inline SETTINGS (truncating, join_use_nulls, max_threads) 9 to 24 0
a subquery on a view over rand() 11, 3 of them Code: 906 0
a WHERE alias: SELECT * APPLY (x -> toInt32(x) + a) FROM t WHERE (i * 100 AS a) > 1 5, all Code: 906 no Code: 906

anyChild / forEachChild visit children plus those two members, and every recursive screen
in the file uses them, including the inline blocks of hasNonDeterministicFunctionsImpl and
scanAggregatesSafe. containsIdentifier keeps children: the lambda always holds its own
parameter, and walking it made ORDER BY COLUMNS('a') APPLY (x -> 1) checkable (0 to 8 checks).

The alias guard now also matches function names. With
WHERE arrayCount((y -> y > 100) AS identity, [101]) > 0, removing the WHERE rebinds
identity(x) to the builtin: Code: 906 in 2 to 6 of 12 rounds on master, with or without
APPLY, none with this PR.

No stateless test, as in #125003. The fuzzer and oracle tests pass locally, except 3 that need
Keeper or transactions. This supersedes #121897. arrayJoin in a lambda stays in #122118:
expressionContainsArrayJoin is in another file and also serves row policies, constraints and TTL.


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

Version info

  • Merged into: 26.11.1.71-master (included in 26.11 and later)

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 24, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 2 findings;
bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠ The traversal counts an APPLY lambda's own parameter as a clause-alias reference, so APPLY (a -> 1) with WHERE (i AS a) > 0 skips the six oracles (QueryOracleChecker.cpp:341,602) DISAGREE Real, but pre-existing in this same predicate and not introduced here: ASTFunction::clone registers arguments as children, so referencesAnyAlias already matches the parameter of an ordinary arrayMap(a -> a + 1, arr) against a WHERE alias a. This change makes the APPLY form behave like every other lambda; masking lambda_arg would make it uniquely scope-aware inside one name-based predicate, and collectAliases has no scope tracking either. Direction is fail-closed: both callers only SKIP an oracle, so the cost is a check, never a wrong result or a false mismatch, and it is measured at nil (alias-free control 19 checks before, 31 after). A control for it could not redden on either build without a server-global ProfileEvents counter and therefore a no-parallel tag.
2 ⚠ The test passes unchanged if the oracle silently declines every fuzzed query, since only seed-query rows are compared (05255_oracle_alias_in_apply_lambda.sql:20-29) DISAGREE The file alone cannot prove the oracle ran, but liveness is measured, not argued: through tests/clickhouse-test against a real server the test is red 10/10 on the unfixed build (return code: 138, Code: 906 ... TLP WHERE oracle mismatch!) and green 10/10 plus 50/50 randomized on the fixed one. clickhouse local would have been a fake zero here (it swallows the finish-callback exception); a real server returns it to the client, which is what makes a .sql file the right instrument. The scenario is also self-neutralising: if the oracle declines every fuzzed query, the six clause-removing oracles never run, so this guard has no behaviour left to regress. The counter instrument the finding asks for already exists in-tree as 04658_ast_fuzzer_oracle_tlp_aggregate_counter.sh, which is no-parallel for exactly that reason; this file follows the merged 05097_ast_fuzzer_oracle_apply_aggregate instead, and the coverage bound is measured out of band and reported in the description.

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

Session id: cron:clickhouse-review-self-slot-58:20260924-163700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-test 05255_oracle_alias_in_apply_lambda against a server on the unfixed binary: 10 of 10 runs FAIL, return code: 138, Code: 906 ... TLP WHERE oracle mismatch!. One manual replay of the same file raised the exception 4 times in a single pass over its 6 repetitions.
b Root cause explained? Yes. ASTColumnsApplyTransformer copies lambda and parameters by hand in clone() instead of registering them as children, and the alias guard (clauseDefinesAliasUsedElsewhere into referencesAnyAlias) is a generic children walk. The analyzer resolves an APPLY lambda against the parent query scope, so the identifier binds to the WHERE alias while the clause is present and to the same-named table column once a clause-removing oracle deletes it. The server's own report shows the rebinding: Only in partitioned: 202 401 (alias i * 100) against Only in reference: 203 402 (column a).
c Fix matches root cause? Yes. One missing edge in one traversal, added at that traversal. No widened bound, no no-random-* tag, no reduced dataset, no guard at the point of failure, and no change to any oracle.
d Test intent preserved / new tests added? New regression test 05255_oracle_alias_in_apply_lambda.sql, with a positive control (an APPLY lambda that uses no alias, which must stay eligible for the oracle) so a blanket refusal cannot pass it. Its .reference was generated by running, not written by hand. No existing test is weakened, and the whole in-tree oracle and fuzzer family stays green: 20 of 20 OK, including 05097, 05099, 05140, 05141, 04256_04250, 04658, 05069 and 05227.
e Both directions demonstrated? Yes, on two Build-IDs from the same base. Unfixed 947047f9: test 10/10 FAIL; the counter probe reports ASTFuzzerOracleMismatches 6, 6, 6 on the three alias spellings and 0 on both controls. Fixed 0ed2dea0: test 10/10 PASS and 50/50 under randomized settings; the same probe reports 0 on all six arms, with the positive control rising from 19 to 31 oracle checks.
f Fix is general across code paths? Yes, and that is the design. The edge is added to the shared traversal, so all seven call sites of the guard in this file are covered at one site: select.where() at lines 1562, 1654, 1769, 1831 and 2074, select.having() at 1912, and the NoREC select-list check at 1665. Six clause-removing oracles (TLP WHERE, DISTINCT, GROUP BY, HAVING, Aggregate, and NoREC) are therefore fixed once rather than six times. All 18 recursive children-walk screens in the file were enumerated with a disposition for each. The one remaining carrier, arrayJoin hidden in the same lambda, is real and measured but sits in a helper with 8 non-oracle callers (row policies, TTL, constraints and others), so it is left with #117791 rather than folded in here.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured rather than argued. Five further arms, 8 fuzzed rounds each, on both binaries: the shadowing column as Nullable(Int32) (6 mismatches before, 0 after), as LowCardinality(String) (6, 0), the alias used in a nested lambda inside the APPLY lambda (6, 0), in a scalar subquery inside it (6, 0), and with two chained APPLY transformers (7, 0). The guard compares identifier names, which no type wrapper changes. Two shapes were measured and found NOT to carry the defect, so nothing claims them: a HAVING alias (0 mismatches on both builds) and the case-1 parameters member, whose reference side errors with Code: 36 instead of rebinding.
h Backward compatible? Yes, vacuously. No setting default changes, so no SettingsChangesHistory.cpp entry is owed; no serialized format, no on-disk state, no public header. The file is reachable only under ast_fuzzer_runs and ast_fuzzer_oracle, both experimental-tier and off by default.
i Invariants and contracts preserved? Yes. referencesAnyAlias is a pure read-only AST predicate with no error path, no allocation contract and no locking; the added loop mirrors its existing children loop and exits through the same return true. Its only two callers are eligibility screens whose sole effect is to skip an oracle, so a false positive costs coverage and never correctness, and the positive control bounds that cost. The helper returns an empty list for every node that is not an ASTColumnsApplyTransformer, so no other traversal changes. Nothing outside src/Interpreters/QueryOracleChecker.cpp is touched.

Session id: cron:clickhouse-impl-self-slot-57:20260924-153500

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [06a34e6]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05345_text_index_prewhere_read_step_order FAIL cidb IGNORED
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb IGNORED
03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key NOT_FAILED cidb IGNORED
02884_create_view_with_sql_security_option NOT_FAILED cidb IGNORED

AI Review

Summary

QueryOracleChecker now traverses hidden APPLY lambdas and parameters across oracle eligibility screens and recognizes callable aliases before removing their defining clauses. The previous callable-alias finding is fixed in 06a34e6b71a5b and its thread has been resolved. No new actionable findings remain.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 24, 2026
@groeneai
groeneai requested review from nihalzp and qoega September 24, 2026 17:36
@PedroTadim

Copy link
Copy Markdown
Member

cc @qoega

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0f9d4e4

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) job error before any test ran: Failed to load test selection: CIDB query failed ... play.clickhouse.com Read timed out (read timeout=60); 69 PRs hit this same signature between 09:09Z and 20:03Z a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_asan_ubsan, targeted) same test-selection read timeout against the CI database, same outage window a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR aggregator statuses reporting the rows above, no independent failure a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260924-210057

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Failed to load test selection targeted-shard errors in my 2026-09-24 ledger: #122111 (external, merged 2026-09-26).

groeneai and others added 2 commits October 15, 2026 12:22
Master removed the stateless tests of the AST fuzzer oracle in 91dc673
(a testing tool, not server behavior; 04658 is kept as the only one), so this
PR no longer adds one. Validated locally instead: the same queries fail 10/10
with `Code: 906` on master and pass 50/50 under randomized settings with the
fix.

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

Copy link
Copy Markdown
Member

@groeneai 🕵️ This fixes the alias screen, but the same blind spot is in most of the other screens in this file. On master, only hasNonDeterministicFunctionsImpl and scanAggregatesSafe look at apply->lambda and apply->parameters. Every other recursive walker goes through ast->children only, so it misses whatever an APPLY lambda holds:

  • referencesSystemDatabaseAnywhere, referencesDistributedTableAnywhere, referencesUnscreenedDefinitionAnywhere
  • usesFinalAnywhere, hasNonDeterministicJoinAnywhere, subtreeContainsSetOperation, hasWithFillAnywhere
  • hasTruncatingInlineSettings, hasNonStrippableInlineSettings, hasNestedThreadSettings
  • hasWindowFunctionWithoutOrderBy, containsAsterisk, containsIdentifier, collectAliases

A lambda can hold a scalar subquery, so for example (from reading the code, not run):

SELECT * APPLY (x -> x + (SELECT count() FROM system.processes)) FROM t WHERE i > 1;
SELECT * APPLY (x -> x + (SELECT count() FROM t2 SETTINGS max_rows_to_read = 10, read_overflow_mode = 'break')) FROM t WHERE i > 1;

skip the system-table and truncating-settings screens, which leads to the same kind of false mismatch this PR fixes. arrayJoin, which the description sends to #117791, is one more case of this.

Instead of a PR per screen, could hiddenApplyMembers become a single traversal helper that visits children plus the hidden APPLY members, used by every walker here, with the inline blocks in hasNonDeterministicFunctionsImpl and scanAggregatesSafe switched to it as well? That closes the whole class in one place and stays local to this file, so it avoids the cost of making lambda a real child that the description mentions. It would also settle the duplicate with #121897.

Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
`ASTColumnsApplyTransformer` keeps `lambda` and `parameters` outside
`children`, so every screen in `QueryOracleChecker.cpp` that recursed over
`children` missed what an `APPLY` lambda holds (a scalar subquery reading
`system`, `FINAL`, an `ANY` join, a view over `rand()`, inline `SETTINGS`,
`WITH FILL`, a `Distributed` table, a window without `ORDER BY`, an alias).
Only `hasNonDeterministicFunctionsImpl` and `scanAggregatesSafe` read them,
each with its own inline block.

`anyChild` / `forEachChild` visit `children` plus those two members, and
every recursive screen uses them, including the two that had inline blocks.
`scanAggregatesSafe` still records the transformer itself, scanning its
members into a separate result. `containsIdentifier` keeps walking
`children` only: it proves a window `ORDER BY` key is not constant, and the
identifiers of an `APPLY` lambda include its own parameter, so
`ORDER BY COLUMNS('a') APPLY (x -> 1)` would pass as ordered.

`referencesAnyAlias` also matches a function name and the bare `APPLY`
function name: an alias of a lambda defined in `WHERE` is callable, and
removing the `WHERE` rebinds `identity(x)` to the builtin `identity`.

Requested on ClickHouse#122055. Supersedes the per-screen loops of ClickHouse#121897.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title AST fuzzer oracle: do not drop a WHERE whose alias is used inside an APPLY lambda AST fuzzer oracle: walk the hidden APPLY members in every eligibility screen Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 06a34e6. anyChild / forEachChild visit children plus the lambda and parameters of APPLY, and every recursive screen in the file uses them, including the inline blocks of hasNonDeterministicFunctionsImpl and scanAggregatesSafe (which still records the transformer itself, so checkTLPAggregate keeps refusing it).

Measured on master and on this commit, 6 fuzzed rounds per query: your two examples were checked 12 and 17 times on master and 0 times now. The same holds for FINAL, ANY JOIN, WITH FILL, join_use_nulls, max_threads and a Distributed table inside the lambda (9 to 24 checks, now 0), and a view over rand() went from 3 Code: 906 to not checked.

Two exceptions:

  • containsIdentifier stays on children. It proves a window ORDER BY key is not constant, and a lambda always holds its own parameter, so walking it made ORDER BY COLUMNS('a') APPLY (x -> 1) checkable (0 to 8 checks).
  • arrayJoin stays in Recognise an arrayJoin hidden in an APPLY column transformer #122118: expressionContainsArrayJoin lives in ExpressionContainsArrayJoin.cpp and also serves row policies, constraints and TTL, so it cannot be local to this file.

This supersedes #121897.

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 06a34e6b7 with master e0d54e882 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 7b9b80ae3; 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, 12 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 06a34e6

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) / 05345_text_index_prewhere_read_step_order flaky, not from this PR (it only changes QueryOracleChecker.cpp): the known read_order_index_first 0 -> 1 diff in the ParallelReplicas lane, 78 of 78 reruns passed; it failed on 58 other PRs and 10 times on master in the last 30 days #125892 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125892 (mine, open)

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

Session id: cron:our-pr-ci-monitor:20261015-183012

@PedroTadim

Copy link
Copy Markdown
Member

@qoega LGTM. Can you give a final look?

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 16, 2026
Merged via the queue into ClickHouse:master with commit 2239bc3 Oct 16, 2026
176 of 178 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 16, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 19, 2026
`ASTColumnsApplyTransformer` keeps `lambda` and `parameters` outside
`children`. Every recursive screen in this file now walks them through
`forEachChild` (master, ClickHouse#122055); `collectReadParts` still walked
`children` only, so a table read inside an `APPLY` lambda, e.g.
`SELECT * APPLY (x -> (SELECT count() FROM t)) FROM s`, was missing from
the part snapshot and a mismatch caused by a new part of `t` was
reported instead of skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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.

4 participants