Skip to content

AST fuzzer oracle: keep aggregate parameters on -Merge, skip ANY joins - #124149

Merged
PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/tlp-aggregate-oracle-merge-parameters
Oct 9, 2026
Merged

PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/tlp-aggregate-oracle-merge-parameters

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #104591

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

Requested by @ alexey-milovidov on #104591 (CI report). AST fuzzer (amd_release, oracle) reports TLP Aggregate oracle mismatch for quantileExactWeightedInterpolated at a level other than 0.5: 5 times in 60 days, on master (https://github.com/ClickHouse/ClickHouse/actions/runs/35893278796/job/107322086153) and in four PRs.

Root cause. The TLP Aggregate oracle compares agg(params)(args) with aggMerge(_s) over aggState(params)(args) AS _s, dropping the parameters on the -Merge side. A quantile state does not record the level, so the -Merge evaluates the median. For other parametric aggregates the parameterless -Merge throws, so the oracle skipped them.

Change. Copy the parameters onto the -Merge call, unless one names columns (* APPLY isNull), which would mean something else in the outer query. Aggregates registered with is_order_dependent are now skipped from that registration property rather than from a hand-kept list (30 list entries removed); the newly compared sequenceMatch, sequenceCount, sequenceMatchEvents and sequenceNextNode, which keep arrival order on timestamp ties without that flag, go on the deny-list.

ANY joins. The fuzzer turned the new test's query into an ANY INNER JOIN in the flaky check. ANY INNER keeps one row per key and which row depends on the plan, so the TLP partitions keep more rows than the reference. The screen that skips ASOF joins now skips ANY too, as #117187 does, including an ANY that comes from join_default_strictness or from a view's definition.

Validation. With randomized settings, 05344 fails without the change in 193 of 200 runs and passes 200 of 200 with it; 05140 and 05141 fail when the is_order_dependent check is removed.


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

Version info

  • Merged into: 26.10.1.1915-master (included in 26.10 and later)

groeneai and others added 2 commits October 6, 2026 03:11
The TLP Aggregate oracle rewrites `agg(params)(args)` into `aggMerge(_s)`
over `aggState(params)(args) AS _s` computed per WHERE partition, but built
the `-Merge` call without the parameters. A `-Merge` function constructs its
nested function from its own call's parameters and only requires the same
state representation; quantile states do not store the level, so
`quantileExactWeightedInterpolatedMerge(_s)` over a level-0 state evaluated
the default level 0.5 and the oracle raised a false
`TLP Aggregate oracle mismatch` (AST fuzzer (amd_release, oracle), master
9e323d1 and several PRs). For every other parametric aggregate the
state type encodes the parameters, so the parameterless `-Merge` threw and
the oracle silently skipped them.

Clone the parameters onto the `-Merge` call and register them in `children`.

This lets the oracle compare the parametric aggregates it used to skip.
Each was measured against its own State/Merge rewrite (1000 rows, tied
timestamps, three parts, max_threads 1/16 x max_block_size 7/65409, 10
trials each). The ones whose result legitimately differs go on the
deny-list: groupArraySample, groupFormat, hierarchicalKMeans and MVTEncode
depend on row arrival order; sequenceMatch, sequenceCount and
sequenceMatchEvents sort events by timestamp only, so tied events keep
arrival order. uniqUpTo, windowFunnel, sequenceNextNode,
groupNumericIndexedVector and the weighted interpolated quantiles matched
in every trial and stay checked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sequenceNextNode breaks timestamp ties by the value only, so tied events
that differ in the base or event flags keep their arrival order, and the
State/Merge rewrite of the TLP Aggregate oracle can pick a different base
than the direct aggregate. argAndMin and argAndMax resolve ties like
argMin and argMax, which are already skipped.

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 6, 2026
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds; the final round found nothing)
  • ❌ sequenceNextNode breaks timestamp ties by value only, so the State/Merge rewrite can choose a different base: AGREE, added to the deny-list (9/60 false mismatches without it, 0/60 with it).
  • ⚠️ A parameter bound by WITH is unresolved in the outer -Merge query: DISAGREE, the oracle skips such a query (run_oracle swallows the error); before this change the same query was a false mismatch.
  • ⚠️ The test can pass without reaching the oracle: DISAGREE, it fails in 193 of 200 runs without the change; a global counter assertion would force no-parallel.
  • 💡 argAndMin/argAndMax tie like argMin/argMax: added.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Over the decimal table of 03240, quantileExactWeightedInterpolatedMerge(_s) over quantileExactWeightedInterpolatedState(0.) partitions returns 0, 0 (the median) where the reference returns -16.66666666, -50. The new test fails without the change in 193 of 200 randomized runs.
b Root cause explained? checkTLPAggregate clones the aggregate for the -State side but builds the -Merge call without its parameters. A -Merge function takes its parameters from its own call; the quantile state does not store the level, so the default level is evaluated.
c Fix matches root cause? Yes. The -Merge call gets a clone of the original parameters at its only construction site. The function stays checked; the deny-list entries are the aggregates this newly compares whose State/Merge result legitimately differs (measured), plus argAndMin/argAndMax, which tie like the listed argMin/argMax.
d Test intent preserved / new tests added? New 05344_ast_fuzzer_oracle_tlp_aggregate_parameters (singular and plural form). Existing oracle tests unchanged and passing.
e Both directions demonstrated? Without the change 193/200 FAIL with TLP Aggregate oracle mismatch; with it 100/100 OK (50 sequential, 50 with --jobs 8). Deny-list entries: 14 false mismatches in 30 oracle runs without them, 0 with them; sequenceNextNode 9/60 -> 0/60, argAndMin 13/30 -> 0/30, argAndMax 9/30 -> 0/30.
f Fix is general across code paths? One construction site serves grouped and ungrouped queries; no other -State/-Merge rewrite exists in the oracle; combinators are rejected before the rewrite.
g Fix generalizes across inputs (params/datatypes/wrappers)? The whole parameter list is cloned (plural form tested); a WITH-bound parameter does not resolve in the outer query, so the oracle skips that query; Decimal, Int64 and Float64 inputs checked; 22 parametric invocations measured against their own rewrite, windowFunnel (incl. 'strict_once') also over rows that tie on the full sort key.
h Backward compatible? (maintainer-approved exception only) Yes. Oracle-only code behind the experimental ast_fuzzer_runs / ast_fuzzer_oracle settings; no setting, format or user-visible change.
i Invariants and contracts preserved? The parameters node is registered in children after the arguments, as ASTFunction::clone does; the -Merge call names the same function, with the same parameters, as the -State call.

Session id: cron:clickhouse-impl-slot-6:20261006-033900

@groeneai
groeneai requested review from PedroTadim and qoega October 6, 2026 04:25
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3dfc826]

Summary: ❌

job_name test_name status info comment
Storage memory check FAIL
04_add_projection.sql FAIL cidb IGNORED

AI Review

Summary

This PR fixes the TLP Aggregate oracle so aggMerge keeps the original aggregate parameters, broadens the oracle safety gates to skip plan-dependent ANY joins (including through referenced definitions), and replaces part of the hand-maintained aggregate denylist with is_order_dependent metadata. I did not find any remaining correctness issue in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 3dfc826.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 41/50 (82.00%) · Uncovered code

Full report · Diff report

Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 3dfc826bbb23bea28d3c4aecc18c78f492bd7e34 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

groeneai and others added 2 commits October 6, 2026 07:08
`ANY INNER JOIN` keeps one row per join key and the row it keeps depends on
the plan. The TLP rewrite filters each partition before the join, so the
partitions together keep one row per key each and the union has more rows
than the reference: a false `TLP Aggregate oracle mismatch`. The DQP oracle
is exposed the same way (filter push-down on vs off), and the result of an
ANY join also depends on the join algorithm (measured: `count()` of the same
ANY INNER self-join is 3 with hash joins and 89 or 100 with `partial_merge`).

The server-side fuzzer adds joins with random strictness, so the new 05344
test hit this in `Stateless tests (amd_tsan, flaky check)`: its query was
mutated into `... ANY INNER JOIN oracle_tlp_agg_params AS alias27 ON
equals(w, alias27.w)`.

Skip `Any` and `RightAny` strictness in the screen that already skips ASOF
joins, as ClickHouse#117187 does. A join written without a strictness takes
`join_default_strictness`, and a view body is evaluated as part of the
query, so the screen also resolves the default and runs over the stored
definitions the query reads. A definition carrying semantic inline
settings (e.g. its own `join_default_strictness`) or its own thread count
(which would override the oracles' single-thread pin) is skipped, the same
rules the query itself is held to.

05345 runs each shape 30 times with the oracle on. Mismatches per run
without this change (20 runs): 7-15 for an explicit ANY join, 5-18 for
`join_default_strictness = 'ANY'`, 11-20 for a view over an ANY join, 10-21
for a view with `SETTINGS join_default_strictness = 'ANY'`; with it, 0 in
200 runs. The test also checks via `system.query_log` that an `ALL` join is
still checked and a view with `SETTINGS max_threads = 8` is not.

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

The TLP Aggregate rewrite repeats the aggregate's parameters on the outer
`-Merge` call, but the outer query reads only the `_s_N` states. A parameter
that names columns therefore means something else there: the fuzzer turned
`quantilesExactWeightedInterpolated(0.1, 0.9)` into
`quantilesExactWeightedInterpolated(0.1, * APPLY isNull ...)`, where `*`
expands to `v, w` in the State call and to `_s_0` in the Merge call, so the
two sides used different levels and the oracle reported a false mismatch
(1 of 100 local runs of 05344).

Only repeat parameters built from literals and function calls; skip the
check otherwise. A parameter bound by `WITH` used to fail to resolve in the
outer query and is now skipped explicitly. Literal and constant-function
parameters such as `toDecimal32(0.9, 0)` are still checked.

05344 gains the asterisk case: 14 of 30 queries mismatched before, 0 of 60
after; 05344 and 05345 pass 200 runs each.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title AST fuzzer oracle: pass the aggregate's parameters to the -Merge call AST fuzzer oracle: keep aggregate parameters on -Merge, skip ANY joins Oct 6, 2026
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-testing Test content only (no production code). labels Oct 6, 2026
/// `State`/`Merge` rewrite legitimately produces a different value than direct
/// evaluation (so they aren't "non-deterministic functions" in the
/// `system.functions` sense, but they are unsafe for oracle equality).
const std::unordered_set<String> non_deterministic_functions = {

@PedroTadim PedroTadim Oct 6, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@qoega and @groeneai I already said a few times, why we don't use the system.functions table to check for non deterministic ones. New functions are going to be added later, then this list may not get updated and the CI will fail with false positives

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.

Scalar functions already go through the same source as system.functions: FunctionFactory::tryGet(...)->isDeterministic(). For aggregates system.functions.is_deterministic is NULL, so the closest metadata is the registration's is_order_dependent flag.

Done in 42b6fed: an aggregate registered with is_order_dependent is now skipped from that flag, and the 30 list entries it covers are gone (6 of the 10 this PR had added), so a new order-dependent aggregate needs no list change. The aggregates still listed have no such flag: the floating-point and approximate ones (sum, avg, quantile*, uniqCombined, ...) are deterministic and only their State/Merge result differs, and sequence* are not registered as order-dependent.

The probe counted every internal `_s_0` query of the test, but the
server-side fuzzer mutates the ANY-join seeds as well (it drops the join,
turns it into LEFT/FULL, or even an explicit `ALL INNER JOIN`), and those
variants are TLP-checked too. With the ALL batch removed the old probe
still printed 1 in 20 of 30 runs. The ALL batch now sets its own
`log_comment` (internal oracle queries inherit it) and the count also
requires `ALL INNER JOIN` in the rewrite: with the batch removed it now
fails 30/30, and the test passes 100/100.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PedroTadim PedroTadim self-assigned this Oct 6, 2026
groeneai and others added 2 commits October 6, 2026 09:37
Every aggregate registered with `is_order_dependent` is now rejected from its
`AggregateFunctionFactory` properties, so a new order-dependent aggregate is
covered without touching `non_deterministic_functions`. The 30 entries that the
property already describes leave the set: any, anyLast, anyHeavy, first_value,
last_value, topK, topKWeighted, approx_top_k, approx_top_sum, deltaSum,
deltaSumTimestamp, stochasticLinearRegression, stochasticLogisticRegression,
groupArray, groupUniqArray, groupArrayInsertAt, groupArrayIntersect,
groupArrayMovingSum, groupArrayMovingAvg, groupArrayLast, groupArraySample,
groupFormat, hierarchicalKMeans, MVTEncode, argMin, argMax, argAndMin,
argAndMax, groupConcat, mergedJSONPatch.

`tryGetProperties` resolves aliases, case-insensitive spellings and combinator
suffixes itself, so `min_by`, `array_agg`, `GROUP_CONCAT`, `groupArrayIf` and
`groupArrayState` are covered as before. Window functions are registered as
order-dependent too and stay checked: their ordering is screened by
`hasWindowFunctionWithoutOrderBy`. The only aggregate newly skipped is
`flameGraph`, the single order-dependent registration that was not listed.

`system.functions.is_deterministic` cannot replace the remaining entries: it is
NULL for every aggregate, and the floating-point and approximate aggregates left
in the set (`sum`, `avg`, `quantile*`, `uniqCombined`, ...) are deterministic;
only their `State`/`Merge` rewrite differs. `sequence*` stay listed because their
registrations do not declare order dependence.

Measured on a debug build: all 36 probes of the removed names and spellings are
skipped by the oracle; with the property check disabled the same probes are
checked and 05140_oracle_skips_approx_top_k and 05141_oracle_skips_aggregate_aliases
fail, so those tests pin the new path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flaky check runs the server with the thread fuzzer and 8 copies of
the test in parallel, where every query takes about half a second, so
the time of 05345 grows with the number of fuzzed seeds. 180 seeds took
219 s on average in `amd_binary`, 304 s in `amd_asan_ubsan` and 198 s in
`amd_debug`, over the 180 s limit.

The `ANY` batches now run 8 seeds and the thread-view batch 6. The `ALL`
liveness probe repeats a batch of 2 seeds until a TLP Aggregate rewrite
of its own batch is seen, at most 15 times, instead of running 30 seeds
once. Measured with a debug build, the CI thread-fuzzer environment and
8 jobs: 115-225 s per run, against 599-1059 s before.

Without the `ANY` screen the test still fails in 20 of 20 runs; with the
`ALL` seed removed from the loop it fails in 5 of 5 runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
"argMin", "argMax", "groupConcat",
"groupArraySorted",
/// Events with equal timestamps are matched in arrival order.
"sequenceMatch", "sequenceCount", "sequenceMatchEvents", "sequenceNextNode",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵️ Thanks, the is_order_dependent change addresses the list concern for order-dependent aggregates.

A question on sequenceMatch, sequenceCount, sequenceMatchEvents and sequenceNextNode: they are registered without is_order_dependent (AggregateFunctionSequenceMatch.cpp:951-953), but you measured them breaking timestamp ties by arrival order (9 of 60 false mismatches for sequenceNextNode). If they depend on input order on ties, shouldn't they be flagged at registration instead of on the deny-list? The optimizer also uses that flag when deciding whether a subquery's ORDER BY can be dropped, so a missing flag could affect real queries, not just the oracle.

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.

Measured on 26.8.2.7 and 26.3.33.24: yes, the missing flag reaches real queries. removeRedundantSorting drops the subquery ORDER BY under these functions (it keeps it under groupArray), so events that share a timestamp arrive in storage order:

CREATE TABLE ev (t DateTime, x UInt8, e UInt8) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO ev VALUES ('2026-01-01 00:00:00', 2, 2), ('2026-01-01 00:00:00', 1, 1);
SELECT sequenceMatch('(?1)(?2)')(t, e = 1, e = 2) FROM (SELECT * FROM ev ORDER BY t, x); -- 0
SELECT sequenceMatch('(?1)(?2)')(t, e = 1, e = 2) FROM (SELECT * FROM ev ORDER BY t, x)
SETTINGS query_plan_remove_redundant_sorting = 0; -- 1

sequenceCount, sequenceMatchEvents and sequenceNextNode differ the same way.

The flag alone does not define the result of the first three, though: they sort events with the unstable ::sort (AggregateFunctionSequenceMatch.cpp:102), and their docs leave the order of events that share a timestamp undefined. In a debug build, which shuffles before sorting, the query with the kept ORDER BY returns 0 or 1 at random (5 runs). Following the query's tie order needs the flag plus a stable sort. That changes results and plans of real queries, so I kept it out of this fuzzer fix.

Do you want it as a separate PR (flag the four registrations, stable sort in sequenceMatch, remove them from this list), or is the documented undefined order enough?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I guess the separate PR makes more sense

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.

I would keep that as a separate PR. This change is just making the oracle stop comparing sequence* queries it cannot compare reliably today; flipping the registration flag and making the sort stable would change planner behavior and potentially user-visible results for real queries, so it deserves its own focused change.

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.

Acknowledged. I will open the separate PR (the four sequence* registrations flagged as order-dependent, a stable event sort in sequenceMatch, and the four removed from this list) and link it here.

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.

Opened #124812: the four sequence* registrations flagged is_order_dependent and a stable event sort in sequenceMatch/sequenceCount/sequenceMatchEvents (sequenceNextNode already sorted stably). The four entries can leave this list only once this PR is on master, so I will remove them then.

@PedroTadim
PedroTadim enabled auto-merge October 8, 2026 15:37
@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3dfc826

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
Storage memory check / 04_add_projection.sql not from this PR, which changes only the AST fuzzer oracle and its test: a conserved pair across adjacent scenarios. The PR arm charged +48,192 B more than master to 04_add_projection.sql (+84,512 B vs +36,320 B) and the same 48,192 B less to 05_multiple_tables.sql (+188,224 B vs +236,416 B), so the MATERIALIZE PROJECTION work of scenario 04 still held that memory at the after_04 checkpoint and released it in scenario 05. All other scenarios match master. This scenario failed on 26 pull requests in 30 days and never on master #121545 (mine, open)
Mergeable Check, PR rollups, red only because of the row above #121545 (mine, open)

Session id: cron:our-pr-ci-monitor:20261008-230012

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 9, 2026
Merged via the queue into ClickHouse:master with commit 90996be Oct 9, 2026
150 of 152 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 9, 2026
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-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants