Skip to content

Recognise an arrayJoin hidden in an APPLY column transformer - #122118

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:oracle-apply-arrayjoin-screen
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:oracle-apply-arrayjoin-screen

Conversation

@groeneai

@groeneai groeneai commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118224

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

The AST fuzzer oracles now recognise an arrayJoin written inside an APPLY column transformer, so
they no longer check a query whose row count they cannot predict.

Description

SELECT * APPLY (x -> arrayJoin([x, x + 1])) FROM t WHERE i > 1, run with ast_fuzzer_runs and
ast_fuzzer_oracle set, returned a false Code: 906 AST_FUZZER_ORACLE_MISMATCH for a query that
answers correctly: the NoREC oracle compared a count of 8 against a count of 2, which is exactly the
row multiplication its screen exists to refuse.

ASTColumnsApplyTransformer keeps its lambda, its parameters and a bare function name outside
children, so expressionContainsArrayJoin, which recursed over children only, never saw a call
written inside an APPLY. One walk in that helper covers every caller.

The three oracle gates using it as their row-count screen gate 8 of the 9 oracles. The 9th rewrites
only the WHERE predicate, so both sides multiply rows identically and it needs no such screen.

Two DDL surfaces change on purpose: a row policy filter and a CHECK/ASSUME constraint carrying
this spelling are now refused at statement time (ILLEGAL_PREWHERE, INCORRECT_QUERY), as the
plainly written call already was. Both were accepted before and then failed on every read or insert
(Code: 36, Code: 47). Stored metadata is exempt, so no existing table stops attaching, verified
with DETACH/ATTACH.

No CI job shows this shape and none can: QueryFuzzer builds an APPLY only from toString,
toTypeName and isNull, and never recurses into a lambda it finds, so the shape has to come from
the user's own query. The measured repro and the both-direction counters live in the new test instead.

Noticed, not addressed here: a PROJECTION whose body carries the same spelling is still accepted;
#117791 adds that screen and inherits this walk, in either merge order. #121897 is a different screen
in a different file, with no overlap.


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

groeneai and others added 2 commits September 24, 2026 19:05
`SELECT * APPLY (x -> arrayJoin([x, x + 1])) FROM t WHERE i > 1`, run with `ast_fuzzer_runs` and
`ast_fuzzer_oracle` set, returned a false `Code: 906 AST_FUZZER_ORACLE_MISMATCH` for a query that
answers correctly. The NoREC oracle compared `SELECT count() FROM (<the query>)` = 8 against
`SELECT countIf(i > 1) FROM t` = 2: the rewrite drops the select list, hence the lambda, hence the
row multiplication, which is exactly what its screen exists to refuse.

`ASTColumnsApplyTransformer` keeps `lambda`, `parameters` and the bare `func_name` outside
`children` - its `clone()` copies the first two by hand instead of calling `cloneChildren()` - and
`expressionContainsArrayJoinImpl` recursed over `children` only, testing a name only on an
`ASTFunction`. So a call written inside an `APPLY`, or a UDF named by `func_name` whose body contains
one, was invisible to it. One walk in the shared helper covers every caller; the name test is
factored out so the canonical-name lookup that catches `unnest` and the cycle-guarded UDF descent are
reused for the bare function name.

Measured on two binaries built from the same tree, 8 fuzzed rounds per arm, as
checks / mismatches:

  * APPLY (x -> arrayJoin(...))     WHERE   16/6  ->  5/0
  * APPLY (x -> unnest(...))        WHERE   12/6  ->  8/0
  * APPLY (x -> aj_udf(x))          WHERE   19/4  ->  7/0
  * APPLY aj_udf  (bare func_name)  WHERE   12/6  ->  5/0
  COLUMNS('i') APPLY ...            WHERE    8/4  ->  4/0
  t.* APPLY ...                     WHERE   14/5  ->  5/0
  chained APPLY ... APPLY ...       WHERE   14/7  ->  4/0
  * APPLY (x -> x + 1)              WHERE   25/0  -> 29/0   (must stay > 0)
  arrayJoin only inside a subquery  WHERE   30/0  -> 20/0   (must stay > 0)
  arrayJoin written in the list     WHERE    0/0  ->  0/0   (already refused)

Against a real server the same query produced 4 client-visible `Code: 906` in 6 rounds before and
0 after. Reverting each of the three gate lines in turn shows the client-visible mismatch is
attributable to `isSafeForOracle` alone, and that all three gates consume the one walk.

`checkIdentityWhere` keeps running on these queries, by design: it rewrites only the `WHERE`
predicate, so both sides multiply rows identically. That is why the checks counter stays non-zero
above, and why the new test asserts the mismatch counter instead.

Two DDL surfaces change acceptance on purpose. A row policy filter and a `CHECK`/`ASSUME` constraint
carrying this spelling are now refused at statement time (`ILLEGAL_PREWHERE`, `INCORRECT_QUERY`), the
same codes the plainly written call already gets; both were accepted before and then failed on every
read or insert with `Code: 36` and `Code: 47`. Stored-metadata replay is exempt via
`isFreshTableDefinition`, so no existing table stops attaching. The two limit-pushdown callers and
the TTL and sharding-key callers are unaffected: they read the AST after the transformer has been
expanded, or the transformer is not expressible there at all.

Rejected: a local wrapper in `QueryOracleChecker.cpp` (leaves the other eight callers blind, does
not cover the `func_name` carrier, and collides with the pending non-deterministic-function screen in
that file); widening the NoREC rewrite to preserve the select list (changes what the oracle tests
rather than what it refuses, and the row-count invariant is genuinely unavailable for a
row-multiplying query); refusing every query carrying an `APPLY` transformer (the positive control
above shows the oracles run correctly on those, so it would delete real coverage and newly reject
harmless row policies and constraints).

Related: ClickHouse#118224
The walk added in the previous commit reaches three hidden members of
ASTColumnsApplyTransformer, but only two of them were asserted. The lambda and
a function name resolving to a SQL UDF were covered; a bare canonical function
name and the parameters member were exempted as unreachable, on the strength of
Code: 43 and Code: 36 measured through a SELECT.

Those two codes are raised only once the expression has been resolved and
evaluated, so they say nothing about the surface where this change actually
alters acceptance. A row policy filter is screened straight off the parsed AST
in InterpreterCreateRowPolicyQuery::execute, before name resolution, arity
checking or constant folding, so neither code can fire there.

Measured one policy at a time on both binaries: `* APPLY unnest` and
`* APPLY (quantile(arrayJoin([0.1, 0.9])))` are each accepted at DDL by the
unpatched build and then make every read of the table fail Code: 36, and both
are refused at statement time with ILLEGAL_PREWHERE once the walk is in place.
That is the same already-broken-at-use class as the lambda spelling, and it is
the same error code this test already asserts for every other spelling.

Each new branch of the walk now carries an assertion on the surface where it is
reachable, so the parameters member is covered by a measurement rather than by
being walked because the walk was free. Nothing is added for these two
spellings to the oracle test: neither is a valid SELECT, so a fuzzer probe
there could assert nothing.

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; 5 findings across 2 cold reviews and 2
gate passes, one of them re-raised in the delta pass; bounded: 1 full pass + 1 fix round + a delta
recheck). The delta pass found nothing new.

# Sev Finding Verdict Evidence / action
1 ⚠️ Two of the three new branches (parameters, bare canonical func_name) are exempted as "not reachable" by a measurement taken on the query surface, where the expression is resolved; the DDL screens this change touches read the raw parsed AST, so that bound does not hold there (src/Interpreters/ExpressionContainsArrayJoin.cpp:43,47) AGREE, fixed @ 9445450 Both spellings measured at DDL on a base and a fixed binary (accepted, then refused ILLEGAL_PREWHERE), and pinned in 04509_row_policy_arrayjoin_filter.sh. Each is attributable to exactly one new branch: for APPLY unnest the lambda and parameters are both absent, and for APPLY (quantile(arrayJoin(...))) the name is not an arrayJoin alias and not a UDF
2 ⚠️ The oracle probes read a counter moved by the fuzzed mutant rather than the written query, so a zero can arise without the screen being exercised (05244_oracle_skips_apply_array_join.sh) AGREE in the actionable part, fixed @ 9445450 The walk is pinned deterministically and fuzzer-free by the row policy and constraint assertions; finding 1 closes the two arms that lacked such an assertion. Declined: an assertion on parsed ASTs (a test must not reference internal identifiers) and pinning ast_fuzzer_runs = 0 on non-probe calls (its default is 0, the stress runner forces the client option to 0, and both model tests pin it in the same single place)
3 ⚠️ Re-raised after the fix round: the added DDL assertions still leave the oracle test itself probabilistic, so it could pass without exercising the screen. Asked for a seeded oracle path or a direct oracle-gate observable DISAGREE (recorded, terminal) The premise is true and documented in the test; the remedy is not available and the risk is measured. (i) No fuzzer-seed setting exists (Settings.cpp:3759-3771) and the fuzzer is a process-global singleton seeded by randomSeed() under a shared mutex (executeQuery.cpp:3425-3435), so a parallel stateless test cannot pin the mutation sequence; a fixed seed exists only in coverage builds, which no test can request. (ii) The counter observable was already measured unsound here: it is a property of the fuzzed query and the fuzzer adds a WHERE (120 no-WHERE rounds gave exactly 2 checks and 2 matching log lines), which is why those two arms were dropped rather than shipped. (iii) The scenario is bounded by measurement: on the unpatched binary 6 of 6 runs fail with all 6 refusal lines reddening every run, at 6 of 8 rounds mismatching, so an attempt reaching zero by chance is about 0.02%, and a green run needs all 6 independent arms to do it at once. (iv) The retry it objects to is the documented remedy for a different, measured flake class (1 red in 25 runs on #121897), so weakening it would trade a measured zero for an unmeasured risk. (v) The determinism asked for exists where the code changed: one shared helper, pinned per spelling by three fuzzer-free DDL assertions, consumed by each of the three gates on a single line, with one binary per gate proving it
4 💡 No positive control for the non-lambda arm, so a widening of the UDF descent would delete oracle coverage silently AGREE, not shipped (cost) Raised as optional and capped at two added lines; the smallest correct form needs five (a control, a reference line, a function in setup and its drop in teardown), so it was dropped under its own clause rather than grow the test against the standing ask to add fewer
5 💡 Three test comments describe the parse tree rather than what the test pins AGREE, noted not blocking The mechanism is stated in the commit message, which is where it belongs
6 💡 The projection residual was disclosed without naming the open pull request that already adds that screen AGREE, fixed Description now points at #117791, which inherits this walk in either merge order

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-221600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * APPLY (x -> arrayJoin([x, x + 1])) FROM t WHERE i > 1 under ast_fuzzer_runs=1, ast_fuzzer_oracle=1: 6 of 8 fuzzed rounds mismatch unpatched, and the new test fails on 6 of 6 runs against an unpatched binary.
b Root cause explained? Yes. ASTColumnsApplyTransformer keeps lambda, parameters and func_name outside children (its clone() copies them by hand), and the helper recursed over children only, so the row-count screen under-reported and NoREC compared 8 rows against 2.
c Fix matches root cause? Yes. Fixed in the shared helper, which is where the defect is, rather than guarded at the three call sites. No widened bound, no no-random-* tag, no dataset reduction, no defensive check.
d Test intent preserved / new tests added? Yes. Two existing test files extended beside their assertion for the same surface; one new counter test. Every shipped assertion has a measured pre-fix red; two planned assertions were dropped rather than shipped vacuous, with the measurement recorded.
e Both directions demonstrated? Yes. Two binaries from the same tree (Build IDs 1998ca49... unpatched, dffd1964... patched), identity-asserted per server. 12 probe arms measured on both. The shipped tests FAIL on the unpatched binary, which names each asserted spelling individually, and pass on the patched one: 300/300 for the three tests as first shipped, plus 50/50 randomized and 50/50 --no-random-settings for the two assertions added in the last fix round.
f Fix is general across code paths? Yes. One walk fixes all three oracle gates and all eight non-oracle callers; mutation proves each gate consumes it. Sibling screens out of scope and named in the body.
g Fix generalizes across inputs? Yes. No type logic here, so the matrix is the spelling matrix: 10 ways of hiding the call enumerated, 7 measured live on SELECT (lambda, unnest, UDF in the lambda, bare UDF name, COLUMNS(...), qualified asterisk, chained transformers), 3 negative controls measured unchanged. Each unreachability claim names its surface: three spellings are unreachable on SELECT with their exact resolution-time codes, and the two of them that ARE reachable on the DDL screens (which read the raw parsed AST) were measured accepted-then-refused there and are asserted in 04509. So all three new branches ship an assertion on the surface where each is reachable.
h Backward compatible? Yes. No setting, no SettingsChangesHistory.cpp entry, no format or metadata change. Stored-metadata replay is exempt, so no existing table stops attaching (DETACH/ATTACH verified on both binaries). Two DDL surfaces newly refuse input that was already broken at use; both are stated in the body.
i Invariants and contracts preserved? Yes. Pure predicate, no state. Same signature and house style, the UDF cycle guard moved verbatim into the extracted helper, the ASTSelectQuery boundary untouched and pinned by two positive controls. The ASTFunction extraction is behaviour-preserving: both old branches fell through to the children loop when they did not return, and so does the extracted call.

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9445450]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
generate_random_json #1 FAIL dashboard
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
set_index #0 FAIL dashboard
timeseries_to_grid_aggregation_functions #2 FAIL dashboard
set_index #1 unstable query history
timeseries_to_grid_aggregation_functions #0 slower query history
timeseries_to_grid_aggregation_functions #1 slower query history
timeseries_to_grid_aggregation_functions #7 slower query history

AI Review

Summary

The PR fixes expressionContainsArrayJoin so it also detects arrayJoin hidden inside APPLY column transformers, which closes the oracle false positive and brings the shared row-count guard in line with that syntax. I reviewed the current diff, the touched callers, the added tests, and the prior PR discussion, and I did not find any code or test issues that warrant a new review comment.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit 9445450.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

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

Full report · Diff report

@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 25, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9445450d8 with master 51ce1e82f (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 92ac39e0a; 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, 6 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 - 9445450

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
Performance Comparison (arm_release, master_head, 1/6) / generate_random_json #1 dashboard gate verdict, not a measurement of this diff: client_time 1.476 -> 1.995 s (+35.1%), tier confirmed_regression. The shard's own report reads 7 too long, 1 slower, and in master_head mode neither term can fail a shard: only error_tests or the dashboard gate can (ci/jobs/performance_tests.py:2795-2816), and this run logged no errors. Measured at the tree that actually ran (ffc656b916c2, job 107901640010), the in-tree half of this class, #121847, IS present and the shard reddened anyway, so it is not the owner ClickHouse/performance-comparison#5 (external, open; the dashboard confidence-scoring half)
Performance Comparison (arm_release, master_head, 4/6) / set_index #0, timeseries_to_grid_aggregation_functions #2 same class, two confirmed regressions in one shard: 0.0222 -> 0.0369 s (+66.2%) and 0.0703 -> 0.1107 s (+57.4%). Both queries are recurrently noisy on this metric: over 7 days set_index reads slower on 142 distinct pull requests (52 of those rows on true master) and timeseries_to_grid_aggregation_functions on 124 (38 on true master), against 104984 and 101622 success rows in 14 days. Since #121847 merged, 117 distinct pull requests have taken a dashboard-confirmed red shard (168 shards). Same measurement at the tested tree ffc656b916c2 (job 107901639707) ClickHouse/performance-comparison#5 (external, open; the dashboard confidence-scoring half)
Mergeable Check, PR commit-status rollups of the two shards above, no independent failure ClickHouse/performance-comparison#5 (external, open)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

Nothing is PR-caused. The diff is src/Interpreters/ExpressionContainsArrayJoin.cpp and its header
plus three stateless tests; the new branch runs only on an ASTColumnsApplyTransformer node or a SQL
UDF name, and none of the three flagged benchmarks contains APPLY, arrayJoin or unnest, so on
their path the change adds one failed node type test per AST node walked at analysis time. That is
orders of magnitude below the 15 ms to 520 ms deltas above.

One more in-tree half is in flight for the measurement side of this class, not linked as the owner
because I have not measured it against these three queries: #122073 reports that the measured runs
never received --stop-merges, so background merges ran during measurement while the
confirm_changes rerun that feeds the dashboard's repeated-measurement tier had them stopped.

Gates (a) to (d): 0 of 173 check runs queued or running (130 pass, 41 not selected, 2 fail),
Config Workflow, Style check, Fast test and Finish Workflow all success, 45 min since the last
job finished (anchor 2026-09-25T03:31:30Z), and every failing row above has an owner.

Session id: cron:our-pr-ci-monitor:20260925-040239

@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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 19, 2026

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-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant