Skip to content

AST fuzzer oracle: screen the hidden APPLY members in every eligibility gate - #121897

Closed
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:oracle-nondeterminism-screen-apply-transformer
Closed

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:oracle-nondeterminism-screen-apply-transformer

Conversation

@groeneai

@groeneai groeneai commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125728
Related: #122055

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 parameters and lambda outside its children. #125728 made the
non-determinism screen of QueryOracleChecker read them, but the other eligibility gates still walk
children only, so a construct the oracle skips in the select list is checked when it sits inside an
APPLY lambda. For example, with nd a view over rand(),

SELECT * APPLY (x -> toInt32(toInt32(x) % 2 IN (SELECT r % 2 FROM nd))) FROM t WHERE i > 1

raised Code: 906 ... TLP WHERE oracle mismatch! in 1 of 6 attempts on master (0 of 6 with this
change), while the same subquery in the select list is skipped.

hiddenApplyMembers returns those two members, and nine gates walk them after children: window
without ORDER BY, non-strippable and nested thread SETTINGS, WITH FILL, FINAL,
non-deterministic joins, system tables, Distributed tables and unscreened view definitions. The
WHERE/HAVING alias guard is #122055.

Only a hand-written query reaches this: the fuzzer generates APPLY as toString, toTypeName or
isNull and does not mutate the lambda.

No stateless test, as in #125003. Validated locally on this branch merged with master, one probe per
gate counting ASTFuzzerOracleChecks over 3 fuzzed rounds, 3 runs each: with master's
QueryOracleChecker.cpp every probe is checked 4-14 times, with this change 0 times. Distributed
was not probed, as it needs the test cluster config.


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

groeneai and others added 2 commits September 24, 2026 04:19
…PPLY column transformer

`Stateless tests (arm_asan_ubsan, targeted)` on ClickHouse#112355 raised a false
`AST_FUZZER_ORACLE_MISMATCH`:

    Code: 906. Identity WHERE (NOT(NOT p)) oracle mismatch!
    Reference (1 rows): SELECT DISTINCT a.* APPLY any FROM oracle_apply_agg AS a
                        FULL OUTER JOIN a AS alias19 ON equals(alias19.i, i > 1) WHERE 100
    Variant   (1 rows): ... WHERE not(not(100))

Both sides return one row, so the values differed rather than the row count.

`any` picks an arbitrary row, and it is already listed in `QueryOracleChecker`'s
backstop deny-list for exactly that reason. The name never reached the lookup.
`ASTColumnsApplyTransformer` stores the applied function as a bare `String
func_name` (or an `ASTPtr lambda`), and `func_name`, `parameters` and `lambda` are
none of them registered among the node's children: `clone()` copies the latter two
by hand instead of calling `cloneChildren()`, which is also why the node carries its
own `updateTreeHashImpl`. `hasNonDeterministicFunctionsImpl` inspects
`ASTTableExpression` and `ASTFunction` nodes and then recurses over `children`, so
it saw none of the three.

`checkIdentityWhere` deliberately admits DISTINCT, GROUP BY and aggregates, because
rewriting `WHERE p` into `WHERE not(not(p))` changes no query structure; that screen
plus the window screen are its only defences against an order-dependent result. With
the screen blind, the oracle compared two executions whose value `any` chooses
arbitrarily. The fuzzer's `FULL OUTER JOIN` mutation, under that job's randomized
`query_plan_optimize_join_order_randomize=1`, is what made the join output order
actually vary; 05097's own unjoined three-row shape returns a stable row, which is
why the test normally passes.

This is the sibling of cca33c9 (ClickHouse#118224), one screen over: that commit taught
the aggregate screen `scanAggregatesSafe` about this node, and it was the only place
in the whole file that knew about it.

The name-only tests are extracted out of the `ASTFunction` branch into
`namesNonDeterministicFunction` so both node types share one implementation rather
than drifting apart again, and an `ASTColumnsApplyTransformer` branch screens
`func_name` through it and recurses into `lambda` and `parameters`. Fixing the shared
screen fixes all nine oracles at once and needs no per-oracle knowledge.
`lambda_sort_functions` stays in the `ASTFunction` branch because it reads the
argument count, which a name alone cannot decide.

Alternatives rejected: pinning `query_plan_optimize_join_order_randomize=0` in 05097
hides the symptom in one test while leaving the screen blind for every other query
the oracle job checks; rejecting the query inside `checkIdentityWhere` alone would
have to be redone for the eight other oracles; and registering `parameters`/`lambda`
in `children` would change behaviour for every consumer of the node in the codebase,
including identifier resolution descending into a lambda argument that is not a
column, for a blast radius far out of proportion to a CI false positive. The other
`children`-only predicates in this file stay as they are: `QueryFuzzer` generates
`APPLY` only from `{toString, toTypeName, isNull}` and never mutates the hidden
members, so those hazards need a hand-written `* APPLY (x -> <hazard>)` query with
the oracle enabled, and none exists in the tree.

`hasNonDeterministicFunctions` runs only when `ast_fuzzer_runs > 0 AND
ast_fuzzer_oracle = 1`, both EXPERIMENTAL and default off, so no default
configuration changes behaviour and no `SettingsChangesHistory.cpp` entry is needed.
The only effect on the oracle is that strictly more queries are skipped, the
direction the file already documents as safe.

A rows-based assertion cannot catch this defect, because the false mismatch needs a
particular fuzzer mutation plus join-order randomization. The new
`05243_oracle_skips_apply_transformer` therefore asserts deltas of the server-global
`ASTFuzzerOracleChecks` counter, as its merged siblings 05140 and 05141 do: four
unsafe spellings (`APPLY any`, `APPLY (x -> any(x))`, `APPLY (quantile(0.9))`, and
`APPLY (uniqUpTo(randConstant() % 2 + 1))`, which is unsafe only in its `parameters`
subtree) plus an `APPLY toString` positive control, so the screen cannot pass by
rejecting every `APPLY`. It fails on the unpatched build and passes with the fix;
deleting any one of the three new checks reddens it, and making the branch return
true unconditionally does not compile, because `-Wunreachable-code` proves the three
checks are independent. 05097 is untouched and still passes. 50/50 randomized runs
are green for the new test and for 05097, 05140 and 05141.

Failing report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112355&sha=f04b15679c1412c072def6c57c16e0b749412bc5&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the extracted helper's refactor-narrating header and the clause explaining why the argument-count test stayed behind; restate the ASTColumnsApplyTransformer note as a bare invariant. Master's relocated timeSeries and SQL-UDF property comments are left byte-identical.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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; plus 1 from my own
cold read; bounded: 1 full pass + 1 fix round + 1 delta recheck). No blockers, no fix round
needed.

# Sev Finding Verdict Evidence / action
1 ⚠️ A negative probe could pass with one member screen removed, if all three fuzzed rounds were oracle-ineligible for an unrelated reason rather than rejected by the screen (05243_oracle_skips_apply_transformer.sh) DISAGREE Measured per member, each arm applied alone to the patched tree and rebuilt: dropping only the func_name test gives any checked 4 times + quantile checked 4 times; dropping only the lambda recursion gives lambda any checked 2 times; dropping only the parameters recursion gives randConstant parameter checked 4 times. With all three absent (unpatched build, Build ID asserted via SELECT lower(buildId())) all four probes report 4, 5, 4 and 4. Eight observations of "screen absent", none of them zero. Those deltas also measure the premise: 4 to 5 increments across 3 rounds puts per-round eligibility at about 1.0. Seed pinning is not available to close it differently (getGlobalASTFuzzer takes randomSeed() unless WITH_COVERAGE, and the fuzzer is a process-global singleton).
2 💡 The test carries more explanatory prose than executable logic DISAGREE Sibling-calibrated rather than an outlier: the two merged tests this one extends are larger at the same density (05140 is 207 lines, 05141 is 240) and 05243 is the smallest of the three at 192, with 5 probe invocations against 05141's 8.
3 💡 The test's comments name C++ internals, which breaks abstraction and can go out of sync DISAGREE Same family calibration: 05140 and 05141 carry 12 such lines each to this file's 17. Happy to strip them here if you would rather the family moved the other way.

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.

Noted, not raised: groupArraySample is absent from the deny-list despite arrival-order-dependent
sampling, and the other children-only predicates in this file remain blind to this node. Both are
code-reading only with no observed occurrence, and the second is unreachable by the fuzzer, which
generates APPLY solely from toString, toTypeName and isNull.

Session id: cron:clickhouse-review-slot-8:20260924-042400

@clickhouse-gh clickhouse-gh Bot closed this Sep 24, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bd66daa]


AI Review

Summary

PR #121897, reviewed at bd66daaa4912ca9239121dbd85b1e0e28285346c, extends nine QueryOracleChecker eligibility checks to the hidden lambda and parameters members of ASTColumnsApplyTransformer, preventing false oracle mismatches. The prior inline finding is addressed. No new actionable findings.

Final Verdict

✅ Approve. The recorded local probes provide focused regression evidence; this review did not run a local build or runtime tests.

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

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 14430d05d with master 596f844fb (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, 13 s compile time in total, 7 of them have a recent master baseline.

Job report

05243_oracle_skips_apply_transformer asserts that the non-determinism screen
refuses a query whose only hazard lives in an `APPLY` transformer, by requiring
`ASTFuzzerOracleChecks` not to move while the query runs under
`ast_fuzzer_runs = 1, ast_fuzzer_oracle = 1`.

The assertion is about the fuzzed query rather than the seed query, and a round
can mutate the hazard out of it. `QueryFuzzer::fuzzExpressionList` replaces a
select-list element outright with probability 1/1500, one of the replacements
being a reference to a virtual column of whatever the query reads. The element
it replaces here is the `*` that carries the transformer, so what executes is a
plain deterministic query: the screen admits it and the oracle checks it, which
is correct behaviour.

That is what the flaky check on this PR hit: 1 red in 130 runs (24 OK / 1 FAIL
under amd_debug, 25/25 in the four other flaky lanes). The job's own query_log
records the offending round executing

    SELECT DISTINCT _part FROM oracle_apply_screen WHERE i > 1

in place of `SELECT * APPLY (uniqUpTo(randConstant() % 2 + 1)) ...`, followed by
that query's Identity-WHERE, TLP and subquery-wrap rewrites, while rounds 1 and 3
of the same probe kept the hazard and were screened as expected. One replacement
in 1500, over three rounds of each of the four probes, puts a run's chance of
this at about 1 in 125, which is the rate the flaky check measured.

The two outcomes are not symmetric. A screen that stopped reading the member
admits every hazard-carrying round, so it moves the counter on every attempt,
whereas this mutation is random and independent per attempt. So the probe retries
while the delta is non-zero, up to three attempts, and keeps the minimum. The
common path is unchanged: the first attempt is already zero, so no extra rounds
are run and no probe gets slower.

Validation on one tree:

  - 300 randomized runs, patched server: 300 OK (the unfixed test also passed
    300, so volume alone cannot show this).
  - The escape forced deterministically, by redirecting the first round of every
    probe to a checkable query: the unfixed probe fails on all four probes, the
    retrying probe passes. That is the shape the flaky check hit.
  - The fixed test against the unpatched server, where the screen is absent
    entirely: FAIL 3/3 with every probe reporting `checked N times`, so the retry
    cannot mask a regression.
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
@PedroTadim

Copy link
Copy Markdown
Member

cc @qoega

@qoega qoega self-assigned this Sep 24, 2026
@qoega

qoega commented Sep 24, 2026

Copy link
Copy Markdown
Member

@groeneai fix 05243_oracle_skips_apply_transformer being too long

…ty gate

The previous commit taught the non-determinism screen to read the members
`ASTColumnsApplyTransformer` keeps outside its `children`. The AI review and a
bot review comment on this PR pointed out that the other gates in
`QueryOracleChecker::check` walk `children` too, so a hazard hidden in the same
place still reaches the oracles. That is correct, and it is not only a needless
check: measured on the previous head of this branch (build id 81a84ce473eb51b9),

    CREATE VIEW nd AS SELECT toInt32(rand() % 1000000) AS r;
    SET ast_fuzzer_runs = 1, ast_fuzzer_oracle = 1;
    SELECT * APPLY (x -> toInt32(toInt32(x) % 2 IN (SELECT r % 2 FROM nd)))
    FROM t WHERE i > 1;

raised `Code: 906 ... TLP WHERE oracle mismatch!` in 2 of 4 attempts, while the
same subquery written directly in the select list is refused by the gate and
never reaches an oracle. So the gate a name hides behind decided whether a valid
query fails. It no longer does: 0 of 6 attempts after this commit.

One helper now names what the node hides, and the gates walk it. Those members
are not registered as children on purpose (their identifiers must not be
resolved like ordinary expressions), which is why the screens are fixed rather
than the node.

Coverage, measured per gate as the oracle-check delta on the unfixed vs the
fixed build (unfixed -> fixed):

  system database       8 -> 0     stored definition     9 -> 0
  non-strippable SET    8 -> 0     nested thread SET    12 -> 0
  ORDER BY WITH FILL    4 -> 0     ASOF JOIN             8 -> 0
  unordered window      6 -> 0

Those seven are probes in 05243. The window screen is the one the Identity WHERE
and subquery-wrap oracles rely on directly, so an unordered window hidden in a
lambda had the same effect there as the non-deterministic function did.

Two gates get the same line without a probe of their own. No probe can redden
`usesFinalAnywhere`: a `FINAL` read hidden in an `APPLY` lambda is refused even
when that gate cannot see the hidden members, measured as an oracle-check delta
of 0 on both the fixed and the unfixed build, so that line is consistency with
its neighbours rather than a tested claim. The `Distributed` gate needs the
stateless test cluster configuration to build such a table.

`hasTruncatingInlineSettings` deliberately does NOT get the line. It has one
caller, immediately followed by `hasNonStrippableInlineSettings`, and the two
name sets are disjoint - every truncating setting is also non-strippable - so no
query can reach an oracle because of it and the line could never be exercised.

Three positive controls keep the change from being "refuse every transformer":
`APPLY toString`, a deterministic subquery under an `APPLY` lambda, and an
ORDERED window under one must all still be checked, and all three are.

The whole file costs three client invocations: one that builds the fixture and
gates every probe query for validity, one that sweeps all fourteen probes with a
tagged counter read between consecutive ones, and one that drops the fixture.
Client startup, not the fuzzed rounds, is what a test like this spends its time
on, and the sweep is what keeps eleven refusal probes and three controls
affordable: measured through the real runner on a debug build, the four-probe
version this branch published takes 1.43-1.69s, the expanded set took 3.44-3.70s
while every probe opened its own two clients, and it takes 1.5-2.5s now, with the
invocation count down from twelve to three. The siblings measured 2.25-2.40s
(05140) and 2.86-3.09s (05141) in the same batch.

Three rounds per refusal probe is measured, not conventional: with one round,
several probes cannot redden at all against a server with none of these screens,
so they would pass vacuously. Controls take one round because they only need the
counter to move once and already retry until it does.

The `amd_msan` flaky-check timeout on the previous head was not the probe count.
Its bashlog ends at line 35, the fixture invocation, started at 19:46:11 and
still running when the 180s limit fired at 19:49:23, so no probe had run yet;
that head's p50 for this file was 17.0s on the same lane.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 1151b5bc97f76 (test only).

The 194s amd_msan run was a hang in the fixture invocation rather than in the probes: the
bashlog's last command is line 35, the DROP/CREATE/INSERT, started at 19:46:11 and still
running when the 180s limit fired at 19:49:23, so no probe had run yet. p50 for the file on that
head was 17.0s.

What was genuinely too expensive is the invocation count, which is what a test shaped like this
spends its time on. All fourteen probes and controls now share three client invocations instead of
twenty-six, with one tagged counter read between consecutive probes. Measured through the runner
on a debug build: 3.44-3.70s per run before, 1.5-2.5s now, against 05140's 2.25-2.40s and 05141's
2.86-3.09s in the same batch.

A positive control takes one fuzz round instead of three, since it only needs the counter to move
once and already retries until it does. The refusal probes keep three: with one round, several of
them cannot redden at all against a server without these screens, so they would pass vacuously.

It tripped `Test runs too long (> 180s)` on `Stateless tests (amd_msan, flaky
check)` twice: 194s on head a69bd1d and 285s on head 1151b5b.

That limit is per SINGLE run, not the sum over the flaky check's repetitions.
`total_time` comes from `run_single_test`, which times one invocation, and the
gate at tests/clickhouse-test:3861-3876 compares that one number against 180. My
earlier reading of the 194s failure as a hang in the fixture invocation was
therefore wrong, and so was the conclusion that the invocation count was what
this file spends its time on. What it spends its time on is server query
executions: ~167 per run, measured with the `Query` profile event, and the msan
p50 tracks them closely (17.0s when the file had 5 probes, 37.2s at 14).

Those executions are one fuzzed execution per gate probed plus the oracles that
accept it, and the probe set cannot absorb the cost: this PR gives the
hidden-member traversal to ten separate gate functions, and each probe is the
only cover its own gate has. I measured the alternatives rather than assuming
them. Drawing a probe's three rounds from `ast_fuzzer_runs` instead of from three
statements saves 5.3% of executions (paired, 30 randomized runs per version), but
`executeQuery.cpp:3757` assigns `base_ast = fuzzed_ast` after a successful run, so
those rounds chain instead of each starting from the probe query, and against a
screenless build that shape reddened fewer probes per run than the three
statements do. 5.3% would not have been enough regardless.

`long` is what the tree provides for a test whose cost scales with what it probes
rather than with data it writes. It exempts the per-run limit and, through
`--long-test-runs-ratio` (0.1), cuts the repetitions in the flaky and targeted
lanes, which is a far larger saving in total CI time for this file than any
per-run change available here. Its sibling
05099_ast_fuzzer_oracle_view_definition carries the tag for the same reason.

Only the tag and its justification change; the script and the reference file are
untouched, so the probes keep the shape that was reviewed. Re-verified on this
content: 3/3 FAIL against 935b0142e908f113, one of the three runs reddening all
eleven refusal probes on its own.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Tagged long in 14430d05ddeb2.

A correction first: I said the 194s amd_msan failure was a hang in the fixture invocation, and
that invocation count was what this file spends its time on. Both were wrong. Test runs too long
is measured per single run (total_time from run_single_test), not across the flaky check's
repetitions, and what a run spends is server query executions: ~167 of them, which the amd_msan
p50 tracks closely (17.0s when the file had 5 probes, 37.2s at 14). The restructure I pushed on
that reading raised the p50 on every flaky lane instead (asan 33.1 -> 53.5s, msan 17.0 -> 37.2s)
and then failed at 285s.

That cost is one fuzzed execution per gate probed plus the oracles that accept it, so it lives in
the probe set, and the probe set does not compress here: this PR gives the hidden-member traversal
to ten gate functions, and each probe is the only cover its own gate has. The one saving that
leaves them alone is drawing a probe's three rounds from ast_fuzzer_runs instead of three
statements, worth 5.3% (paired, 30 randomized runs per version). But executeQuery.cpp:3757
assigns base_ast = fuzzed_ast, so those rounds chain rather than each starting from the probe
query, and against a screenless build the chained shape reddened fewer probes per run. I left the
probes as reviewed.

Hence long, as on 05099_ast_fuzzer_oracle_view_definition: the cost scales with what the file
probes rather than with data it writes, and --long-test-runs-ratio also cuts the repetitions,
which saves more of this file's CI time than 5.3% a run would. Script and reference unchanged, and
3/3 FAIL re-verified against the pre-fix build, one run reddening all eleven refusal probes alone.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 14430d0

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_tsan, s3 storage, 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)
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:25
…sm-screen-apply-transformer

Conflict in `hasNonDeterministicFunctionsImpl`: ClickHouse#125728 added its own
`ASTColumnsApplyTransformer` branch there (checks `func_name`, recurses into
`parameters` and `lambda`). Take master's version of that function as is and
drop this branch's duplicate (`namesNonDeterministicFunction` and the
`hiddenApplyMembers` loop in that walker). `hiddenApplyMembers` stays for the
other nine eligibility gates; `hasAsofJoinAnywhere` is now
`hasNonDeterministicJoinAnywhere`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClickHouse#125003 removed the stateless tests of the AST fuzzer oracle: it is a testing
tool, and these `no-parallel` tests with retry loops over fuzzed queries are
expensive in the sequential job. This one is the same kind.

Validated locally instead, on the tree merged with master: with master's
`QueryOracleChecker.cpp` the seven probes for the gates this PR changes are
checked 4-14 times in each of 3 runs, so each of those gates still lets the
query through; with this PR all of them are skipped (3 of 3 runs). The four
determinism probes are skipped on both, since ClickHouse#125728 covers them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title AST fuzzer oracle: screen a non-deterministic function hidden in an APPLY column transformer AST fuzzer oracle: screen the hidden APPLY members in every eligibility gate Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master and resolved the conflict with #125728 by taking its APPLY branch in hasNonDeterministicFunctionsImpl as is. That leaves this PR with the other nine gates (src/ +44, nothing else); I removed 05243_oracle_skips_apply_transformer in line with #125003, and the local measurement is in the description.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
`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

Copy link
Copy Markdown
Collaborator Author

Superseded by #122055: following review there, one traversal helper now walks the hidden APPLY members in every screen of QueryOracleChecker.cpp, including the nine this PR covers.

@PedroTadim PedroTadim closed this Oct 15, 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]>
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-ci-master PR origin: master/nightly CI monitoring finding pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants