Skip to content

Fix false AST fuzzer oracle mismatch on approx_top_k - #118489

Merged
PedroTadim merged 18 commits into
masterfrom
oracle-approx-top-k
Sep 10, 2026
Merged

PedroTadim merged 18 commits into
masterfrom
oracle-approx-top-k

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

QueryOracleChecker compares a query's result against a metamorphic rewrite of it for exact row equality, so it keeps a backstop set of aggregates whose State/Merge path legitimately diverges from direct evaluation. topK and topKWeighted were in that set; their space-saving counterparts approx_top_k and approx_top_sum were not, even though QueryFuzzer's aggregate swap list offers approx_top_k for any single-argument aggregate. Every oracle mismatch recorded on master over the last three weeks is that substitution — four of them, all false:

Fuzzed query: SELECT g, count(), approx_top_k(v), max(v)
              FROM oracle_tlp_agg WHERE v > 50 GROUP BY g ORDER BY g ASC
TLP Aggregate oracle mismatch!

Which elements survive the bounded counter table, and the counts reported for them, depend on the order the values arrive in and on how the partial states merge, so the three-way WHERE partition the TLP Aggregate oracle builds is entitled to disagree with the whole-table reference.

The failure surfaced twice over in the reports below: once as the failing test, and again as a blocker named Unknown error whose description reads "Lost connection to server. See the logs." Nothing had crashed and no connection was lost — clickhouse_proc.py treats any <Fatal> line in the server log as a failure it must classify, the oracle reports a mismatch with LOG_FATAL, and FuzzerLogParser.ERROR_PATTERNS has no pattern for it, so it fell through to UNKNOWN_ERROR. #118056 fixes that reporting side; this change removes the mismatch itself.

Aliases are now resolved through AggregateFunctionFactory::getAliasToOrName instead of being enumerated. ClickHouse aliases plenty of aggregates the set already rejects — min_by/max_by for argMin/argMax, array_agg for groupArray, lttb for largestTriangleThreeBuckets, every median* for the matching quantile*, STDDEV_POP/VAR_SAMP/COVAR_POP for the stddev*/var*/covar* families — and each unlisted spelling is another false mismatch waiting to red master. The expansion is stripped of combinators in turn, so array_concat_agg reaches groupArray through groupArrayArray, and the raw spelling is still tested first so the set stays free to name a function by whichever spelling reads best. getAliasToOrName was protected; making it public means the lookup is the factory's own, consulting both the case-sensitive and the case-insensitive alias map, so a spelling like StdDev_Pop resolves as readily as STDDEV_POP.

The remaining additions are the aggregates QueryFuzzer can substitute in that fall in classes the set already rejects: sumCount and the sumMap* family (non-associative floating-point addition, like sum), corrMatrix/covarPopMatrix/covarSampMatrix (like corr), analysisOfVariance and studentTTestOneSample (like studentTTest), quantileExactWeightedInterpolated and quantilePrometheusHistogram with their plural forms, groupArrayIntersect (hash-table iteration order, like groupUniqArray), mergedJSONPatch (last write per path wins, by sort key) and boundingRatio (on ties in the x argument the first point seen wins). min, max, count, uniq, uniqExact and the groupBitmap* family stay checkable, so oracle coverage of the interesting cases is untouched.

Measured on a pre-fix binary, over 20 rounds of one fuzzer iteration each against the same query shape, using the ASTFuzzerOracleChecks profile event:

select list oracle checks
topK(v), topK(v + 1), topK(v * 2), topKWeighted(v, 1) (already in the set) 0
approx_top_k(v), approx_top_k(v + 1), approx_top_k(v * 2), approx_top_sum(v, 1) 13
approx_top_count(v), min_by(v, v), array_agg(v), medianExact(v), array_concat_agg([v]) 14
count(), min(v), max(v) (deterministic) 34

Set membership is the only variable between the first two rows. Every one of the checked approx_top queries still named an approx_top_* aggregate in the mutated AST — approx_top_kOrNull, approx_top_sumDistinct, approx_top_kDistinctOrDefault — so all of them are rejected once the name is in the set and its combinators are stripped. 05140_oracle_skips_approx_top_k asserts exactly that, with the deterministic select list as the positive control proving the counter is live. 05141_oracle_skips_aggregate_aliases takes the alias spellings that only a factory lookup can reject — the raw min_by / array_agg / array_concat_agg / medianTDigest / anova, the combinator-suffixed min_byOrNull, and the mixed-case StdDev_Pop — against controls proving that aliases of safe aggregates stay checkable in each of those shapes.

Reports:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=6c335833c268d3c52d83b47abf4c2f807251e716&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20sequential%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=6c335833c268d3c52d83b47abf4c2f807251e716&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20sequential%29

Related: #118056
Related: #99980

Changelog category (leave one):

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

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

Version info

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

`QueryOracleChecker` compares a query's result against a metamorphic rewrite
of it for exact row equality, so it keeps a backstop set of aggregates whose
`State`/`Merge` path legitimately diverges from direct evaluation. `topK` and
`topKWeighted` were in that set; their space-saving counterparts
`approx_top_k` and `approx_top_sum` were not, even though `QueryFuzzer`'s
aggregate swap list offers `approx_top_k` for any single-argument aggregate.
Every oracle mismatch recorded on master over the last three weeks is that
substitution - four of them, all false:

    Fuzzed query: SELECT g, count(), approx_top_k(v), max(v)
                  FROM oracle_tlp_agg WHERE v > 50 GROUP BY g ORDER BY g ASC
    TLP Aggregate oracle mismatch!

Which elements survive the bounded counter table, and the counts reported for
them, depend on the order the values arrive in and on how the partial states
merge, so the three-way `WHERE` partition the TLP Aggregate oracle builds is
entitled to disagree with the whole-table reference.

The failure surfaced twice over: as the failing test, and again as a
blocker named `Unknown error` whose description reads "Lost connection to
server. See the logs." Nothing had crashed and no connection was lost -
`clickhouse_proc.py` treats any `<Fatal>` line in the server log as a
failure to classify, the oracle reports a mismatch with `LOG_FATAL`, and
`FuzzerLogParser.ERROR_PATTERNS` has no pattern for it, so it fell through to
`UNKNOWN_ERROR`. #118056 fixes
that reporting side; this change removes the mismatch itself.

Aliases are now resolved through `AggregateFunctionFactory` instead of being
enumerated. ClickHouse aliases plenty of aggregates the set already rejects -
`min_by`/`max_by` for `argMin`/`argMax`, `array_agg` for `groupArray`, `lttb`
for `largestTriangleThreeBuckets`, every `median*` for the matching
`quantile*`, `STDDEV_POP`/`VAR_SAMP`/`COVAR_POP` for the `stddev*`/`var*`/
`covar*` families - and each unlisted spelling is another false mismatch
waiting to red master. The expansion is stripped of combinators in turn, so
`array_concat_agg` reaches `groupArray` through `groupArrayArray`, and the
raw spelling is still tested first so the set stays free to name a function
by whichever spelling reads best.

The remaining additions are the aggregates `QueryFuzzer` can substitute in
that fall in classes the set already rejects: `sumCount` and the `sumMap*`
family (non-associative floating-point addition, like `sum`),
`corrMatrix`/`covarPopMatrix`/`covarSampMatrix` (like `corr`),
`analysisOfVariance` and `studentTTestOneSample` (like `studentTTest`),
`quantileExactWeightedInterpolated` and `quantilePrometheusHistogram` with
their plural forms, `groupArrayIntersect` (hash-table iteration order, like
`groupUniqArray`), `mergedJSONPatch` (last write per path wins, by sort key)
and `boundingRatio` (on ties in the x argument the first point seen wins).
`min`, `max`, `count`, `uniq`, `uniqExact` and the `groupBitmap*` family stay
checkable, so oracle coverage of the interesting cases is untouched.

Reports:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=6c335833c268d3c52d83b47abf4c2f807251e716&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20sequential%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=6c335833c268d3c52d83b47abf4c2f807251e716&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20sequential%29

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7d3afbd]

Summary: ✅


AI Review

Summary

This PR fixes the approx_top_* false-oracle mismatches and substantially improves alias coverage in QueryOracleChecker. The remaining issue is that the sumMap* denylist expansion stops one sibling short: plain sumMap still follows the same merge-order-sensitive FieldVisitorSum path but remains oracle-checkable.

Findings

⚠️ Majors

  • [src/Interpreters/QueryOracleChecker.cpp:186] The new sumMap* exclusions still omit plain sumMap. sumMappedArrays, sumMapWithOverflow, and sumMapFiltered* all share the same AggregateFunctionMapBase<..., FieldVisitorSum> implementation as sumMap, so Float* values are merged in an order-dependent way there too. That leaves the sumMapState / sumMapMerge false-mismatch path open for queries that already contain sumMap. Suggested fix: add sumMap to non_deterministic_functions alongside the other sumMap* entries.
Final Verdict

❌ Changes needed before merge: include plain sumMap in the oracle-unsafe aggregate set so the family is covered consistently.

LLVM Coverage Report

Measured on commit 7d3afbd.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 6, 2026
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7d3afbdf1 with master b666e5df6 (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

1415 translation units recompiled, 7685 s compile time in total, 1413 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 7, 2026
`quantileExactWeightedInterpolated` / `quantilesExactWeightedInterpolated`
only accept `UInt64` weights: `merge` adds those per-value counters with
exact integer addition, and the cumulative distribution is built with
`std::partial_sum` only after the values are sorted. The result of the
`State`/`Merge` path is therefore identical to direct evaluation, so
listing them in `non_deterministic_functions` would drop deterministic
queries from oracle coverage for no gain. Added without a reproducer,
removed now.

`quantilePrometheusHistogram` stays: it accumulates the cumulative bucket
value per bucket bound, and that value may be a `Float64`, so the
per-bucket sums really are merge-order dependent. Spelled that difference
out in a comment so the two are not conflated again.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The review is right that the previous test did not prove the new denylist
memberships independently: both negative queries named several unsafe
aggregates at once, so `ASTFuzzerOracleChecks` staying flat only proved that
the query as a whole stayed oracle-unsafe. Dropping `approx_top_sum`, or
breaking one of the alias-resolution paths, would have left the test green
because the other untouched aggregates kept the oracle off.

Each spelling now gets its own probe naming only that spelling, so a probe
fails on its own as soon as its name stops being rejected. Within a probe the
name is repeated three times, because `QueryFuzzer` replaces an aggregate node
with a random name from its swap list once in 30 nodes: with a single
occurrence a swap to a deterministic aggregate would let the oracle run and
turn the assertion into a false failure, while losing all three occurrences in
one round is vanishingly unlikely.

Also replace the `medianExact` negative alias probe: it resolves to
`quantileExact`, whose `merge` concatenates the exact sample so the result does
not depend on merge order, and using it as a probe reads as an endorsement of
that (pre-existing) denylist entry. The alias-resolution path is now probed
with `medianTDigest` (an alias of the genuinely approximate `quantileTDigest`)
and `anova` (an alias of `analysisOfVariance`, one of the entries this pull
request adds).

Verified against a local server: all eight probes report "not checked" over
five consecutive runs, and the same query shapes over safe aggregates - scalar,
two-argument, array-returning and tuple-returning - do move the counter, so no
probe is vacuous.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
The previous commit split the batched oracle probes into one probe per
aggregate spelling, which is the right shape, but it also kept eight fuzz
rounds per probe. That took the query count from 40 to 64 and the test from
~132s to ~204s under `amd_asan_ubsan`, over the 180s per-test limit: 5 of 108
runs in the flaky check failed with `Test runs too long (> 180s)`. It was not
far off elsewhere either — `amd_msan` reached 168s.

Cut the rounds per probe from eight to three, keeping one probe per spelling.
Rounds were never what detects a missing denylist entry: that moves the counter
on the very first round. They only insure against a round whose mutation makes
the query ineligible for an unrelated reason, leaving the probe vacuous, and
that risk falls off geometrically — so three is plenty, while every extra round
costs time and adds one more chance for the fuzzer to swap all three
occurrences away and produce a false failure.

Also bound the positive control at 40 retries instead of 100. It normally
succeeds on the first round, but an unbounded-in-practice loop could exhaust
the limit on its own, and reporting `exact aggregates never checked` is far
more useful than being killed as a timeout.

At ~3.0s per fuzzed query under `amd_asan_ubsan` (measured from the 40-query
and 64-query revisions) this should land near ~90s, below the previous
batched revision as well.
Every alias probe in `05111_oracle_skips_approx_top_k` names an alias whose
canonical aggregate is oracle-unsafe, so the test stayed green for a checker
that rejected *every* alias outright rather than only the unsafe ones. Add a
second positive control over `BIT_AND` / `BIT_OR` / `BIT_XOR` — aliases of
`groupBitAnd` / `groupBitOr` / `groupBitXor`, which are associative and
commutative over integers, are absent from the backstop set, and must stay
oracle-checkable under their alias spelling. The control asserts that
`ASTFuzzerOracleChecks` does move for them, which fails the moment alias
resolution starts over-rejecting.

The retry-until-the-counter-moves loop of the existing positive control is
factored into a `positive_control` function and reused, so the new control
inherits the same bounded retry budget.

Verified on a private local server: 4 consecutive runs match the reference,
~4s each.
The AI review's Major argued that resolving aliases through the factory widens
the pre-existing `quantile*` denylist entries to their `median*` spellings, and
that the deterministic and exact families are oracle-safe to begin with. Half
of that is right, and it is right about the half that matters: differential
testing says `quantileDeterministic` / `quantilesDeterministic` really are
merge-order independent, so they should not be on the list at all - then the
alias follows automatically and no carve-out is needed.

`ReservoirSamplerDeterministic` retains a sample purely by
`hash & skip_mask == 0`, `merge` raises `skip_degree` to the maximum of the two
states and re-thins everything, and the final degree is the smallest one whose
retained count fits `max_sample_size` - a function of the hash multiset alone.
Verified over 1M random rows and over a duplicate-heavy set containing `nan` /
`inf` that direct evaluation, `max_threads` fan-out and `State`/`Merge` over 3,
7, 31, 997 and 9991 partitions all agree, including through the version-0 state
serialization that drops `skip_degree`.

The exact families stay listed, and the comment now records the counterexample:
`QuantileExact` selects with `::nth_element` over the concatenated array, and
that selection is order-dependent for values that compare equal but format
differently. Over 100000 rows alternating `-0.` and `0.`, `quantileExact(0.5)`
(and `*Low` / `*High`) print `-0` computed directly and `0` merged from three
partial states - a real `State`/`Merge` divergence, so those entries are
load-bearing.

The test gains the positive alias probe the review asked for:
`medianDeterministic` must now increment `ASTFuzzerOracleChecks`, which fails
if alias resolution ever reaches a neighbouring `quantile*` entry again.

Verified on a private local server: 3 consecutive runs of
`05111_oracle_skips_approx_top_k` match the reference, and the sibling oracle
tests `04256_04250`, `04658` and `05097` still pass.
alexey-milovidov and others added 5 commits September 7, 2026 08:52
A negative `probe` asserted only that `ASTFuzzerOracleChecks` did not move,
and `run_fuzzed` discards the client's exit status. That condition also holds
when the query never reached `QueryOracleChecker` at all: if a spelling such as
`approx_top_count` or `anova` stopped resolving as an aggregate alias - exactly
the `resolveAggregateAlias` behavior this test is meant to pin down - the query
would fail before the gate, `after == before` would still hold, and the probe
would still print `not checked`.

Each probe now first runs the same query with no fuzzer and no oracle and
requires it to succeed, which separates "the unsafe spelling was skipped by the
oracle" from "this spelling is broken". `FORMAT Null` is safe in that run
precisely because the oracle is off, so it cannot make the assertion vacuous and
the counter cannot move.

Verified against a private local server: the test is green 3/3 with the guard,
and replacing one probe's aggregate with a non-existent name makes the guard
report `is not a valid query` where the old test printed `not checked` and passed.
`CH Inc sync` is failing on `Stateless tests (amd_asan_ubsan, flaky check,
s3 storage, meta in keeper)` with `Test runs too long (> 180s)`. Public CI does
not run that configuration, and on the public `amd_asan_ubsan` flaky check the
test is comfortable (~137s average), so this is not a repeat of the earlier
eight-rounds regression — the shard is simply heavier. Its recorded runs were
146.1, 146.8, 165.8, 166.3, 171.0 and 186.5 seconds, so it sits right on the
limit and fails intermittently.

There a `clickhouse-client` startup costs roughly 2.7s and the test was making
about 60 of them, which is where the ~163s comes from. Cut them instead of
cutting assertions: send a probe's three fuzz rounds in one invocation, since
`ast_fuzzer_runs` applies per statement, and read the counter once per probe
instead of twice, since it is server-global and this test is `no-parallel`, so
each probe's reading is the next probe's baseline.

That removes three invocations per probe, 24 in total, for the same three
independent fuzz rounds per spelling and the same assertions. Expected around
100s on that shard and around 85s on the public one. The reference is
unchanged.
…e test

The `CH Inc sync` job reported `tests failed`, with a single red job -
`Stateless tests (amd_asan_ubsan, flaky check, s3 storage, meta in keeper)`:

    05111_oracle_skips_approx_top_k: [ FAIL ] 186.47 sec.
    Reason: Test runs too long (> 180s). Make it faster.

Across the seven repetitions that job runs, the test took 146-186 s, i.e. it
sat right on the per-test limit. The public `flaky check` on the same commit is
green: with metadata in Keeper and data on S3 every `clickhouse-client`
invocation costs seconds rather than milliseconds, so the run time is set by how
many invocations the test makes, not by the data it touches. Measured against a
local server the whole file takes 4.7-4.9 s, an inflation factor of ~32-38x.

Two changes, both aimed at the invocation count:

- All three rounds of one probe now go out as a single multi-statement
  invocation instead of three. Each statement is still fuzzed and oracle-checked
  on its own - a batch of three copies of a checkable query moves
  `ASTFuzzerOracleChecks` by three - so this removes only client start-up cost.
  The `before` snapshot of the counter moves into the validity-check invocation
  for the same reason; that run has the oracle off, so it cannot move the
  counter and cannot make the assertion vacuous.
- The file is split in two. `05140_oracle_skips_approx_top_k` keeps the
  `approx_top_*` family that the pull request is about, and the new
  `05141_oracle_skips_aggregate_aliases` takes the alias spellings that only a
  lookup through `AggregateFunctionFactory` can resolve, together with the
  positive controls that pin down that safe aliases stay checkable.

`05111` was also taken by a test that landed on `master` meanwhile, so the
numbers move to `05140` / `05141`.

Verified against a local server: 3/3 green for each file, 1.23-1.34 s for
`05140` and 1.89-2.14 s for `05141`, so ~51 s and ~77 s at the inflation factor
above - both with more than a 2x margin. Both files were also differential
tested to confirm the restructuring kept the probes non-vacuous: naming a
non-existent aggregate yields `bogus_agg is not a valid query` rather than a
silent `not checked`, and putting a checkable aggregate in a negative probe slot
yields `min_by checked 7 times`. The oracle siblings
`04256_04250_ast_fuzzer_oracle_tlp_aggregate`,
`04658_ast_fuzzer_oracle_tlp_aggregate_counter` and
`05097_ast_fuzzer_oracle_apply_aggregate` still pass.

Job report: ClickHouse/clickhouse-private#73021
Related: #118489

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Both sides attacked the same red - `05111_oracle_skips_approx_top_k` running
146-186 s against the 180 s per-test limit on the private
`s3 storage, meta in keeper` shard - and reached the same conclusion, that the
run time is client-invocation count and not query work. The two changes agree on
batching a probe's three fuzz rounds into one invocation and are kept as such.

Where they differ:

- The incoming commit carries each probe's counter reading over as the next
  probe's baseline. This side instead takes the baseline inside the probe's own
  validity-check invocation, which the incoming commit's own reasoning allows
  (that run has the oracle off, so it cannot move a server-global counter). Both
  cost three invocations per probe, so nothing is given up on time, and the
  self-contained form survives the file split below, where probes no longer form
  one uninterrupted chain. The incoming warning against raising the round count
  now that rounds are cheap is kept verbatim.
- This side additionally splits the file, so neither half is merely under the
  limit but comfortably so: 1.3 s and 2.0 s locally against the 4.7-4.9 s the
  single file took, i.e. roughly 51 s and 77 s at the shard's measured ~38x
  inflation, where batching alone lands at ~100 s.
- `05111` is now also taken by a test on `master`, so the numbers move to
  `05140` / `05141`; the incoming commit predates that merge.

3/3 green for both files after the merge.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync was reporting tests failed, with exactly one red job: Stateless tests (amd_asan_ubsan, flaky check, s3 storage, meta in keeper).

05111_oracle_skips_approx_top_k: [ FAIL ] 186.47 sec.
Reason: Test runs too long (> 180s). Make it faster.

Across that job's seven repetitions the test took 146.1, 146.8, 154.9, 165.8, 166.3, 171.0 and 186.5 s — it sat right on the per-test limit and failed intermittently. The public flaky check on the same commit is green: with metadata in Keeper and data on S3 every clickhouse-client invocation costs seconds rather than milliseconds, so the run time is set by how many invocations the test makes, not by the data it touches. Against a local server the whole file takes 4.7-4.9 s, an inflation factor of ~32-38x.

Fixed by cutting invocations rather than assertions, in two steps:

  • A probe's three fuzz rounds now travel in a single multi-statement invocation. Each statement is still fuzzed and oracle-checked on its own — a batch of three copies of a checkable query moves ASTFuzzerOracleChecks by three — so only client start-up cost goes away. The before snapshot moves into the validity-check invocation, which is sound because the oracle is off in that run and so it cannot move a server-global counter.
  • The file is split in two: 05140_oracle_skips_approx_top_k keeps the approx_top_* family, and 05141_oracle_skips_aggregate_aliases takes the alias spellings that only a lookup through AggregateFunctionFactory can resolve, plus the positive controls that pin down that aliases of safe aggregates stay checkable.

Result locally: 1.3 s and 2.0 s, i.e. roughly 51 s and 77 s at the shard's measured inflation — both with more than a 2x margin, where batching alone lands at ~100 s.

The restructuring was differential tested to confirm the probes are still non-vacuous: naming a non-existent aggregate yields bogus_agg is not a valid query rather than a silent not checked, and putting a checkable aggregate into a negative probe slot yields min_by checked 7 times. 3/3 green for both files, and the oracle siblings 04256_04250_ast_fuzzer_oracle_tlp_aggregate, 04658_ast_fuzzer_oracle_tlp_aggregate_counter and 05097_ast_fuzzer_oracle_apply_aggregate still pass.

Two more notes:

  • master was merged in. 05111 had meanwhile been taken by 05111_wasm_multi_memory_zero_max_auxiliary, hence the renumber to 05140 / 05141.
  • 266051578957 reached the same diagnosis independently and is merged in, not discarded. Its batching is kept, as is its warning against raising the round count now that rounds are cheap. Its other idea — carrying each probe's counter reading over as the next probe's baseline — costs the same three invocations per probe as taking the baseline inside the probe's own validity invocation, so the self-contained form was kept instead; it survives the file split, where the probes no longer form one uninterrupted chain.

Private sync PR: https://github.com/ClickHouse/clickhouse-private/pull/73021

alexey-milovidov and others added 2 commits September 7, 2026 13:52
Batching a probe's three fuzz rounds into one `clickhouse-client`
invocation quietly made them dependent: `executeMultiQuery` abandons the
rest of a multi-statement batch as soon as one statement raises
(`have_error && (buzz_house || !ignore_error)`), so a first round whose
mutation happened to produce an invalid query cancelled the two rounds
that exist precisely to cover that case. The probe could then pass
vacuously off a single unlucky attempt, which is exactly what the extra
rounds are insurance against.

Pass `--ignore-error` for the fuzzed batch. Measured on a private local
server with a deliberately invalid first statement followed by two
checkable ones: the batch moves `ASTFuzzerOracleChecks` by `0` without
the flag and by `7` with it.

Address review: #118489 (comment)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Every probe in the file used the raw alias spelling, so none of them
exercised the branch the change is actually about: alias resolution has
to run after each combinator strip, not once on the original name.
`array_concat_agg` only proves the *expansion* is stripped afterwards.
Verified rather than argued: with `isOracleUnsafeFunctionName` reduced to
a single up-front `resolveAggregateAlias` lookup, all five existing
probes stayed green while `min_byOrNull(v, v)` turned checkable in 7 of 8
runs, so the new probe is what catches that refactor.

`min_byOrNull` is not a registered name (`system.functions` knows
`min_by`, not `min_byOrNull`), so the factory can only recognise it once
`OrNull` has come off. `*OrNull` rather than `*If`: the fuzzer mutates an
`If` combinator's extra condition argument into something that no longer
type-checks often enough that `min_byIf` lost the regression in 5 of 8
runs.

The `safe aliases` control now carries the same `OrNull` combinator
(`BIT_OROrNull`), so the new probe cannot pass vacuously - a query whose
aggregate is a combinator-suffixed alias spelling is checkable in
principle, hence the zero delta is the gate rejecting `argMin`.

Address review: #118489 (comment)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both AI-review Majors on 2138ca94 are adopted; the verdict’s two items were the only unresolved threads and both are now replied to and resolved.

1. --ignore-error for the batched fuzz rounds (6a3ba027188f). The finding is right and it was measurable: executeMultiQuery abandons the rest of a multi-statement batch as soon as one statement raises (have_error && (buzz_house || !ignore_error)), so batching a probe’s three rounds into one invocation had quietly made them dependent — one unlucky first mutation cancelled exactly the rounds that exist to cover that case. On a private local server a batch whose first statement is deliberately invalid, followed by two checkable ones, moves ASTFuzzerOracleChecks by 0 without the flag and by 7 with it. run_fuzzed_rounds now passes --ignore-error in both files, with the reason recorded in the comment so the flag is not mistaken for noise.

2. A combinator-suffixed alias probe (620d14b36e0b). Also right, and demonstrated rather than argued: with isOracleUnsafeFunctionName reduced to a single up-front resolveAggregateAlias lookup, all five existing probes (min_by, array_agg, array_concat_agg, medianTDigest, anova) stayed green — the file genuinely could not distinguish that refactor from the current code, and array_concat_agg only proves the expansion is stripped afterwards. Added probe "min_byOrNull" "min_byOrNull(v, v), ..."; min_byOrNull is not a registered name (system.functions knows min_by, not min_byOrNull), so the factory can only recognise it once OrNull has come off. Against the resolve-once binary it turns checkable in 7 of 8 runs.

min_byIf was tried first, as suggested, and is a weaker detector: the fuzzer mutates the If combinator’s extra condition argument into something that no longer type-checks often enough that it missed the regression in 5 of 8 runs (deltas 2 2 0 0 0 0 0 6 versus 2 0 3 2 2 6 2 5 for *OrNull). Both are 0 on the correct binary, so this affects detection power only, never the green.

To keep the new probe from passing vacuously, the safe aliases control now carries the same combinator: BIT_AND(v), BIT_OROrNull(v), BIT_XOR(v), which is checked reliably (4 4 5 2 8 4). So the zero delta on min_byOrNull is the gate rejecting argMin, not the oracle declining combinator-suffixed alias spellings altogether.

3/3 green locally for both files; 05140 1.3 s and 05141 2.2 s, so the >2x margin on the private s3 storage, meta in keeper shard is unchanged. Style check green. No production code changed in this round — the QueryOracleChecker diff is exactly what it was on 2138ca94.

@azat

azat commented Sep 7, 2026

Copy link
Copy Markdown
Member

There is also similar fix - #118044
I will close it in favor this one

Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
alexey-milovidov and others added 5 commits September 9, 2026 13:49
`IFactoryWithAliases` already has exactly the lookup `resolveAggregateAlias`
was doing by hand: `getAliasToOrName` tries the case-sensitive alias map on
the raw name, then the case-insensitive one on the lowercased name, and
returns the name unchanged when neither has it. It was `protected`, so the
oracle checker open-coded the same two steps out of `isAlias` and `aliasTo`.
Make it public and call it instead - one lookup path shared with every other
factory, and the case-insensitive half can no longer drift out of sync with
the one the factory itself uses to resolve a query's function names.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Every alias probe so far spelled its alias the way it is registered, so all
of them resolve through the case-sensitive alias map alone and the file
stayed green whether or not the case-insensitive one was consulted - the
mixed-case spellings that only the second map can resolve, `StdDev_Pop` and
its like, could start reaching the oracle again unnoticed.

`STDDEV_POP` is registered as a case-insensitive alias of `stddevPop`, which
puts it in the case-sensitive map under exactly `STDDEV_POP` and in the
case-insensitive one under `stddev_pop`. `StdDev_Pop` therefore matches
neither the backstop set (which names `stddevPop`, and `StdDev_Pop`
lowercases to `stddev_pop`) nor the case-sensitive map, so nothing but the
case-insensitive alias lookup can reject it.

The `safe aliases` control now spells one of its aggregates `Bit_And` for
the same reason the last one carries `OrNull`: so the zero delta on the new
probe is the gate rejecting `stddevPop` and not the oracle declining
mixed-case alias spellings altogether.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The suggestion was to read the counter from the client's own
`--print-profile-events --profile-events-delay-ms=-1` output instead of from
`system.events`. Measured, that flag cannot see this event: it prints the
query's ~75 profile events and `ASTFuzzerOracleChecks` is never among them,
while the server-global counter moves by 3 or 4 for the same query. The
reason is ordering - `QueryOracleChecker` runs from the query's finish
callback (`BlockIO::onFinish`), and `TCPHandler::runImpl` sends the last
`ProfileEvents` packet inside `processOrdinaryQuery`, before it calls
`io.onFinish()`, so the increment happens after the client's last packet.

What the suggestion does buy is one fewer client invocation per probe, which
is exactly the cost that sets these tests' run time on the private
`s3 storage, meta in keeper` shard. The counter reading now travels in the
same multi-statement batch as the three fuzz rounds, printed last and read
off the tail: a statement's oracle checks run in that statement's own finish
callback, so all three rounds have been checked by the time the trailing
`system.events` read executes. `SETTINGS ast_fuzzer_runs = 0` keeps the
fuzzer off that read.

Measured over the whole file, `clickhouse-client` invocations drop from 14 to
10 for `05140` and from 29 to 20 for `05141`, so the margin under the 180 s
per-test limit grows by about a third. Both files still report every probe
`not checked` and both positive controls `checked`, and against a binary
without the alias resolution every negative probe - including the new
`StdDev_Pop` - turns `checked`, so nothing became vacuous.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Measuring how often each probe in `05141` actually detects the regression it
guards - by running it against a binary with no alias resolution at all -
turned up one outlier. Every other probe fires in 6 to 8 runs out of 8;
`anova` fired in 2 of 12.

The cause is its group argument. `(v % 3)::UInt8` is a `CAST` node, and
`QueryFuzzer` rewrites the target type of a `CAST` / `_CAST` /
`accurateCast*` call to a random type once in 30 nodes (`cast_functions` in
`QueryFuzzer.cpp`). A randomly retyped group argument makes `anova` fail to
resolve, so the round errors out before reaching the oracle gate - and a
round that never reaches the gate leaves the counter where it was, which is
exactly what the probe reads as success. Three occurrences meant three
chances per round of losing the round that way.

Spelling the same value `toUInt8(v % 3)` takes the node out of
`cast_functions` and the detection rate goes from 2/12 to 8/12. Note this was
a blind spot and never a false-failure risk: the rewrite can only turn a
round into an error, never into a checked query, so the probe could pass
vacuously but never fail on a correct binary.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 All four open threads are addressed, master is merged in, and one thing turned up along the way that was worth fixing.

1. getAliasToOrName instead of a hand-rolled lookup (6e187e404545, @azat). The helper is now public and resolveAggregateAlias is a one-line call to it. Not just less code: the hand-rolled version reached the case-insensitive map through isAlias(name) || isAlias(toLower(name)), i.e. the factory's own lookup spelled out by hand and therefore free to drift from it. Now the oracle resolves a spelling exactly the way the analyzer does.

2. A mixed-case alias probe (2bd84952b15a, AI review). STDDEV_POP is registered with Case::Insensitive, and registerAliasUnchecked puts it in both maps — aliases["STDDEV_POP"] and case_insensitive_aliases["stddev_pop"] — so the registered spelling resolves through the case-sensitive map alone and every existing probe stayed green whether or not the second map was consulted. StdDev_Pop matches neither that map nor the backstop set (which names stddevPop; StdDev_Pop lowercases to stddev_pop), so only the case-insensitive alias lookup can reject it. Against a binary with no alias resolution the new probe turns StdDev_Pop checked 3 times. The safe aliases control now spells one aggregate Bit_And so the new probe cannot pass vacuously, exactly as BIT_OROrNull does that job for min_byOrNull.

3. --print-profile-events cannot see this event; the invocation it saves is real (9426c1714b48, @azat). Measured: with --print-profile-events --profile-events-delay-ms=-1 the client prints the query's 75 event totals and ASTFuzzerOracleChecks is never among them, while the server-global counter moves by 3 or 4 for the same query (five runs: deltas 0 4 0 3 4, printed matches 0 0 0 0 0). It is an ordering property, not broken plumbing: QueryOracleChecker runs from the query's finish callback, and for a pulling pipeline TCPHandler::runImpl sends the last ProfileEvents packet inside processOrdinaryQuery, before it calls io.onFinish().

What the suggestion does buy is one fewer client invocation per probe, which is the cost that sets these tests' run time on the private s3 storage, meta in keeper shard. The counter reading now travels in the same batch as the three fuzz rounds, printed last and read off the tail — sound for the same reason the separate read was, since a statement's oracle checks run in that statement's own finish callback. Measured over the whole file, invocations drop 14 → 10 for 05140 and 29 → 20 for 05141, so the margin under the 180 s limit grows by about a third. SETTINGS ast_fuzzer_runs = 0 keeps the fuzzer off that trailing read; three consecutive reads return the same value, so it stays inert.

4. system.functions cannot drive the backstop set (@PedroTadim). Where the table has the answer the checker already reads it and keeps no list: hasNonDeterministicFunctionsImpl calls FunctionFactory::tryGet(...)->isDeterministic(), which is the same call system.functions makes to fill its deterministic column. Where the list exists, the table is silent — all 245 aggregates report deterministic = NULL, because StorageSystemFunctions only fills that column if constexpr (std::is_same_v<Factory, FunctionFactory>); and s3, numbers, url, generateRandom, viewExplain do not appear in system.functions at all, while system.table_functions has no notion of determinism. Worse, the column would answer the wrong question: indexHint and materialize report deterministic = 1 and must still be rejected, and topK / approx_top_k / sum are deterministic functions in every sense a factory knows. The property the set records is that the oracle's metamorphic rewrite diverges — see the thread for the numbers.

5. The anova probe was nearly blind (7d3afbdf1064). Since the last two rounds turned on non-vacuity, I measured how often each probe actually detects the regression it guards, by running it against a binary with no alias resolution at all. Every probe fires in 5 to 8 runs out of 8 — except anova, at 2 of 12. The cause is its group argument: (v % 3)::UInt8 is a CAST node, and QueryFuzzer rewrites a CAST / _CAST / accurateCast* target type to a random type once in 30 nodes, which makes anova fail to resolve, so the round errors out before reaching the gate — and a round that never reaches the gate leaves the counter where it was, which is what the probe reads as success. Spelling it toUInt8(v % 3) takes the node out of cast_functions: 2/12 → 8/12. This was a blind spot only, never a false-failure risk — the rewrite can turn a round into an error but never into a checked query.

While measuring I also confirmed which spellings the fuzzer's aggregate swap list can actually rewrite, since that is what the three-occurrences-per-probe rule exists for. startsWith(fn->name, entry) over swapAggrs matches medianTDigest (via median), approx_top_k and approx_top_sum, and nothing else in either file — so the repetition earns its keep for exactly those three and is harmless elsewhere.

CI. The one red job, Build profile diff, was a fleet-wide infrastructure window, not this branch: the CI-logs user lost SELECT on default.binary_sizes and the job died on Code: 497 … (ACCESS_DENIED). Every Build profile diff run between 2026-09-07 16:00 and 2026-09-08 01:00 UTC errored the same way and the job has been green fleet-wide since; the new run will pick that up.

master was merged in (0bc0fc06e305). 05140 and 05141 now share their number prefix with tests that landed on master meanwhile — as 05141_max_min_over_time_timeseries_functions and 05141_nondeterministic_functions_with_constant_arguments already do with each other — so I have not renumbered a third time.

"sum", "sumWithOverflow", "sumKahan", "sumCount",
/// Per-key sums over maps and arrays add the same floating-point values in
/// a merge-order-dependent order, exactly like `sum` above.
"sumMappedArrays", "sumMapWithOverflow",

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.

sumMap is still the one member of this family left oracle-checkable. sumMappedArrays, sumMapWithOverflow, and sumMapFiltered* all share the same AggregateFunctionMapBase<..., FieldVisitorSum> merge path as plain sumMap; mergeImpl combines the per-key values with applyVisitor(Visitor(...)) in src/AggregateFunctions/AggregateFunctionSumMap.cpp:246-264, so Float* values are just as merge-order-sensitive here as they are in sum.

Because neither this denylist nor checkTLPAggregate's non_associative_aggregates mentions sumMap, a query that already contains sumMap on floating values can still reach the sumMapState / sumMapMerge rewrite and reproduce the same false mismatch class this PR is fixing for the rest of the sumMap* family. Could we add plain sumMap here as well?

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 9, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Sep 10, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Sep 10, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Let's try again

Merged via the queue into master with commit 6d69b30 Sep 10, 2026
175 checks passed
@PedroTadim
PedroTadim deleted the oracle-approx-top-k branch September 10, 2026 14:42
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
@Algunenano

Copy link
Copy Markdown
Member

Reverting. The test is flaky

pull Bot pushed a commit to sjoerd2025/ClickHouse that referenced this pull request Sep 19, 2026
Re-land of ClickHouse#118489, which was reverted by ClickHouse#119957 because its test
05141_oracle_skips_aggregate_aliases was flaky. The revert reason was the test, never the
deny-list logic, so master is exposed to the false mismatch again: five occurrences of
"AST Fuzzer oracle mismatch: TLP Aggregate" naming approx_top_k since 2026-09-14, two of them
on master itself.

QueryOracleChecker compares a query's result against a metamorphic rewrite for exact row
equality, so it keeps a backstop set of aggregates whose State/Merge path legitimately diverges
from direct evaluation. topK and topKWeighted were listed; their space-saving counterparts
approx_top_k and approx_top_sum were not, even though QueryFuzzer's aggregate swap list offers
approx_top_k for any single-argument aggregate. Which elements survive the bounded counter
table, and the counts reported for them, depend on the order values arrive in and on how the
partial states merge, so the partitioned rewrite is entitled to disagree with the whole-table
reference. Aliases are resolved through AggregateFunctionFactory::getAliasToOrName rather than
enumerated, because listing each spelling by hand rots silently and one missing spelling is one
false mismatch.

Two things differ from ClickHouse#118489.

First, the 05141 flake is fixed at its cause. probe() runs the probe query once unfuzzed with
the oracle off, purely to read the client's exit status and so tell "this unsafe spelling was
skipped" from "this spelling is broken". That invocation redirected nothing, so any server error
on it reached the test's stderr, and clickhouse-test fails a test with non-empty stderr
regardless of stdout. Exactly one probed aggregate was partial:
AnalysisOfVarianceMoments::getFStatistic() throws BAD_ARGUMENTS "There is only one observation
in each group" when k == n, which the empty input satisfies with k = n = 0. A degenerate read of
the fixture therefore turned the anova gate into a leaked <Error> and failed the test. Both
recorded instances are that chain, both identifiable as the unfuzzed gate query by their
"(query 1, line 2)" position.

The gate's stderr is now discarded, in 05140 as well as 05141, since the two files carry the
same probe(). What made the fixture read degenerate is not established, and the fix deliberately
does not depend on knowing: a probe's validity gate must not depend on an aggregate's runtime
data preconditions. Measured with the fixture INSERT reduced to numbers(0), the pre-revert test
reproduces "Reason: having stderror" while this version passes with an empty stderr. The anova
probe is dropped rather than repaired because it is the only partial aggregate in the list, and
its mechanism class, a raw case-sensitive alias of a deny-listed aggregate, is covered
identically by min_by, array_agg, array_concat_agg and medianTDigest. Keeping it would have
meant either a UNION ALL shape the oracle is likely to reject outright, which makes the probe
vacuous, or a row-count assertion that re-reds the test on the very event the dependence is
being removed from.

Second, ClickHouse#118489 also removed quantileDeterministic and quantilesDeterministic from the set and
added a medianDeterministic(v, 1) positive control that depends on their absence. That
measurement does not hold: in the same amd_tsan job as the 05141 failure, master recorded a TLP
Aggregate mismatch on "SELECT medianDeterministic(v, 1) FROM oracle_alias_agg", and
oracle_alias_agg is 05141's own fixture, so the test was generating master oracle mismatches
through its own positive control. Those two entries are left as master has them today. The
re-landed alias resolution then rejects every median* spelling of a listed quantile* family,
which also makes that control mechanically impossible, so it is removed with the de-listing.

The over-rejection risk it covered is already covered by the "safe aliases" control
(Bit_And, BIT_OROrNull, BIT_XOR resolving to the associative and commutative groupBitAnd,
groupBitOr and groupBitXor), which exercises the raw, combinator-suffixed and mixed-case alias
shapes and must stay checkable.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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.

5 participants