Skip to content

Fix false AST fuzzer oracle mismatch on approx_top_k (re-land) - #120508

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/reland-oracle-approx-top-k
Sep 19, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/reland-oracle-approx-top-k

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

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

Stop the AST fuzzer's TLP Aggregate oracle reporting false mismatches on approx_top_k and on alias
spellings of aggregates it already skips.

Description

QueryOracleChecker keeps a backstop set of aggregates whose State/Merge rewrite legitimately
diverges from direct evaluation, so the oracle skips them. topK was listed; its space-saving
counterparts approx_top_k/approx_top_sum were not, and no alias of any member resolved.
QueryFuzzer offers approx_top_k for any single-argument aggregate, so the oracle compared results
entitled to differ.

#118489 fixed that; #119957 reverted it because its test 05141 was flaky, not because of the
deny-list. Four such false mismatches have landed since, two on master itself. This re-lands
#118489 with two differences.

05141 no longer depends on a query that can throw. probe()'s validity gate runs one unfuzzed
query purely to read its exit status, but redirected nothing, so a server error on it reached the
test's stderr, which fails the test whatever stdout says. anova was the only partial aggregate
probed: getFStatistic() throws BAD_ARGUMENTS once the read yields no more rows than groups, the
empty read included, so no fixture rules it out. The gate is now stderr-safe and the anova probe is
gone; min_by, array_agg, array_concat_agg and medianTDigest cover the same resolution path,
and analysisOfVariance stays listed. Measured with the fixture emptied: the pre-revert test fails
having stderror, this one passes.

The quantileDeterministic de-listing is not re-landed. In the same job as that 05141 failure,
master recorded a mismatch on medianDeterministic(v, 1) over oracle_alias_agg - 05141's own
fixture and positive control. Both entries stay listed; that control is gone.

50 randomized runs of each test are 100/100 green and stderr-clean, and mutation controls for the
listed names, the alias lookup, its per-stage placement and the flake each redden. Both
historical 05141 failures show a degenerate fixture read under s3 storage, sequential; that cause
is not established and this change no longer depends on it.

Requested by @ alexey-milovidov on
#104076 and
#107108.
Report for 10c12dba.


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

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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 17, 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; 9 findings, 1 from the gate and 8
from my own cold pass; bounded: 1 full pass + 1 fix round + 1 delta recheck). No source change was
needed, so this is the reviewed tree as the implementation left it.

# Sev Finding Verdict Evidence / action
1 ⚠️ A negative probe can print not checked in a run where no fuzzed round reached the guard, because the three rounds are separately randomized and their errors are suppressed (05140/05141 probe()) DISAGREE Mechanism accepted, severity not. Measured live on every mutation arm: dropping the two set entries reddens 05140 with all three probes checked; dropping alias resolution reddens both files; resolving the alias once up front reddens exactly min_byOrNull; dropping case-insensitive resolution reddens exactly StdDev_Pop. Per-probe rate measured over 10 repeats against the mutated binary: 9/10 and 8/10, so the residual is ~10-20% per probe per run, not a probe that cannot fail. Nine independent probes, and the sequential group runs in 10+ configurations per PR. The residual failure mode is also self-revealing: a regression that slips re-reddens CI with the same false mismatch. See the note below the table
2 ⚠️ The PR body claimed five false mismatches on master since 2026-09-14 AGREE, fixed in the PR body The five-row count came from a 14-day window and included the 2026-09-14 10:58 medianDeterministic row, which predates the revert and has a different signature. Re-measured for the population the sentence names: four rows since the revert merged, two with head_ref = master
3 💡 The changelog entry was left as the template's ... AGREE, fixed in the PR body Filled with a one-sentence entry naming the change
4 💡 The body asserted the flake was "fixed at its cause" and, three paragraphs later, that the cause is not established AGREE, fixed in the PR body The heading now states what the diff does: 05141 no longer depends on a query that can throw
5 💡 05140's validity gate was made stderr-safe too, which the fix plan did not ask for DISAGREE Kept. It is a byte-identical copy of the 05141 gate whose leak produced the revert, and the redirect touches neither the exit status the branch reads nor stdout, so a spelling that stops resolving still reddens through the is not a valid query reference line (observed with the redirect in place). Leaving the sibling unguarded would make "does not reintroduce the flake" true of only one of the two files added here
6 💡 Four em-dashes in added lines DISAGREE All four are in prose restored verbatim from #118489; the file already carries 83 on master, and every line this PR authors, both test files included, is pure ASCII. Rewriting them would break byte-equality with the commit being re-landed for no user-visible gain
7 💡 Removing the medianDeterministic control drops the only check that alias resolution does not over-reject a neighbouring quantile* member DISAGREE Forced: with quantileDeterministic listed again that control would print never checked. Not live either way, since medianExactWeightedInterpolated resolves to quantileExactWeightedInterpolated, which the set does not contain and which matches no combinator suffix, so it stays checkable. General over-rejection stays covered by the safe aliases control, and that is the spelling to use if the family-specific control is wanted back
8 💡 Both tests carry no-parallel DISAGREE Inherited verbatim from #118489, with the reason in the header: the proof event ASTFuzzerOracleChecks is server-global, and the per-query alternative was measured not to carry it because the increment lands in the query's finish callback, after the last ProfileEvents packet
9 💡 Alias resolution takes a single step, so an alias of an alias would not reach the canonical name DISAGREE No such chain exists: 48 registered aggregate aliases, none whose target is another alias name. The failure direction would be a retained check, never a false mismatch

On finding 1, for the oracle's owners to rule on rather than for me to decide inside a re-land: the
probes assert a zero delta on ASTFuzzerOracleChecks, which is also satisfied when a round never
reached the checker. A strictly stronger shape is a dedicated skip counter, incremented where the
unsafe-name screen rejects a query, with each probe asserting a positive delta on it. I did not do it
here because it adds a user-visible system.events entry inside QueryOracleChecker.cpp, beyond the
re-land, in code #117187 relocates to OracleGate.cpp. Happy to follow up separately if wanted.

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-slot-10:20260917-042800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, two. Flake: pre-revert 05141 with the fixture INSERT set to numbers(0) fails Reason: having stderror every run. Deny-list: dropping approx_top_k/approx_top_sum from the set turns 05140 into approx_top_k checked 1 times. Neither is a "~1%" observation.
b Root cause explained? Yes, two independent chains. (1) isOracleUnsafeFunctionName matched only the written spelling, so approx_top_* was absent and every alias of a listed name was invisible. (2) probe()'s validity gate redirected nothing, and anova throws BAD_ARGUMENTS when k == n (which the empty input satisfies), so a degenerate fixture read leaked <Error> into the test's stderr.
c Fix matches root cause? Yes. The deny-list is where the oracle decides a query is comparable at all, and the aggregate genuinely is not merge-order stable. No widened bound, no no-random-* tag, no dataset reduction, no log-parser mute; the flake fix removes a dependence instead of guarding a symptom.
d Test intent preserved / new tests added? Yes. Both tests still redden on a missing deny-list entry and on broken alias resolution, and their positive controls still fire (safe aliases checked, exact aggregates checked). Two probes are removed because they cannot survive: anova (the only partial aggregate; its class is covered by min_by, array_agg, array_concat_agg, medianTDigest) and medianDeterministic (mechanically impossible now that quantileDeterministic stays listed).
e Both directions demonstrated? Yes. Same binary, same emptied fixture: pre-revert 05141 FAILS having stderror, this one PASSES. For the deny-list: 5 live CIDB mismatch rows without the fix; 467 oracle checks and 0 mismatches with it.
f Fix is general across code paths? Yes. Aliases resolve through the factory's own getAliasToOrName rather than an enumerated list. isOracleUnsafeFunctionName is the single site testing the set, and all nine oracles (checkTLPWhere, checkNoREC, checkTLPDistinct, checkTLPGroupBy, checkTLPHaving, checkDQP, checkTLPAggregate, checkIdentityWhere, checkSubqueryWrap) reach it through the shared screen. The gate defect was hunted in its sibling: 05140's probe() carried the same unredirected gate and is fixed too.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Probed shapes: canonical, case-sensitive alias, case-insensitive alias in a third casing (StdDev_Pop), alias under a combinator (min_byOrNull), and alias whose expansion carries a combinator (array_concat_agg to groupArrayArray to groupArray). Family completeness confirmed at the registration site: exactly approx_top_k, approx_top_sum, and the alias approx_top_count. Every probed aggregate was exercised over empty, one-row-per-group and normal reads.
h Backward compatible? (maintainer-approved exception only) Yes, vacuously. No setting default, new setting, or serialization change, so no SettingsChangesHistory.cpp entry is owed. The oracle runs only under ast_fuzzer_oracle, which is off by default and EXPERIMENTAL-tier. IFactoryWithAliases.h gains no code: an existing inline member moves from protected: to public:.
i Invariants and contracts preserved? Yes. A non-alias returns unchanged, so nothing safe becomes unskippable (asserted by the safe aliases control). The raw spelling is tested before and separately from the canonical one, so an entry named by its alias still matches. Membership is retested at every stripping stage. 2>/dev/null is confined to the validity gate: run_fuzzed_rounds already had it, and the fixture and teardown invocations stay loud.

Session id: cron:clickhouse-impl-slot-5:20260917-032300

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1c1dd6b]

Summary: ✅


AI Review

Summary

This PR teaches QueryOracleChecker to reject the approx_top_* family and unsafe aggregate aliases before running the oracle, and it strengthens the new stateless tests with dedicated ASTFuzzerOracleTLPAggregateChecks controls so they prove the TLP Aggregate path is reachable without reintroducing the earlier stderr flake. I did not find remaining correctness, coverage, or PR-metadata issues in the current revision.

Final Verdict

✅ No new findings.

LLVM Coverage Report

⚠️ No coverage measurement for commit 1c1dd6b: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 17, 2026
Both new tests read `ASTFuzzerOracleChecks`, which all nine oracle paths
increment. Their positive controls therefore proved only that some oracle ran,
not that `checkTLPAggregate` was reachable for the fixture, so every skip probe
could have stayed green with that path out of reach. Add a second positive
control per file reading the dedicated `ASTFuzzerOracleTLPAggregateChecks`
event, as 04658_ast_fuzzer_oracle_tlp_aggregate_counter.sh already does.

The skip probes keep the all-paths counter. The denylist they pin is the screen
shared by all nine oracles, and that counter is measurably the more sensitive
instrument for it: with the screen disabled in a diagnostic build, 90 fuzzed
rounds per spelling gave a per-round detection rate of

  spelling                      all-paths   TLP Aggregate only
  approx_top_k                       51%          40%
  approx_top_sum                     55%          35%
  approx_top_count                   54%          40%
  array_agg                          89%          37%
  min_byOrNull                       92%           0 of 90
  Bit_And, BIT_OROrNull, BIT_XOR     100%          1 of 90

`checkTLPAggregate` skips any aggregate that already carries a combinator, so
`min_byOrNull` and the `BIT_OROrNull` control cannot reach it by construction;
moving them onto the dedicated counter would have retired those assertions
silently. The new controls therefore name combinator-free spellings.

Verified on the reviewed binary (build id 77f68f3884dcadb8): 50 of 50 runs
green, max 2.73s per run. With `checkTLPAggregate` stubbed to return false,
both tests fail on exactly the new line ("TLP Aggregate path never checked")
while every skip probe and both all-paths controls stay green.
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1c1dd6b94 with master 718e603a5 (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

1315 translation units recompiled, 6990 s compile time in total, 1315 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -125.1 s (-2%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/Functions/FunctionsNumericIndexedVector.cpp 73.2 s 56.7 s -20.4 s (-26%)
src/Functions/modulo.cpp 51.6 s 39.6 s -14.7 s (-27%)
src/Functions/FunctionsConversion_reg.cpp 40.0 s 28.2 s -13.9 s (-33%)
src/Functions/divide.cpp 29.9 s 23.2 s -8.3 s (-26%)
src/Functions/plus.cpp 29.6 s 23.1 s -8.1 s (-26%)
src/Functions/minus.cpp 27.4 s 21.4 s -7.4 s (-26%)
src/Functions/greatest.cpp 26.6 s 20.7 s -7.3 s (-26%)
src/Functions/multiply.cpp 26.3 s 20.5 s -7.2 s (-26%)
src/Functions/avg2.cpp 24.6 s 19.2 s -6.8 s (-26%)
src/Functions/moduloOrNull.cpp 26.4 s 21.4 s -6.4 s (-23%)
src/Processors/QueryPlan/JoinStepLogical.cpp 23.5 s 18.4 s -6.3 s (-25%)
src/Functions/midpoint.cpp 24.0 s 19.0 s -6.2 s (-25%)
src/Functions/bitShiftRight.cpp 17.2 s 12.8 s -5.3 s (-29%)
src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp 18.9 s 14.8 s -5.1 s (-26%)
src/Processors/Formats/Impl/Parquet/Reader.cpp 19.2 s 15.1 s -5.1 s (-25%)

Job report

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit e67c4f6 Sep 19, 2026
177 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 2026
@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-testing Test content only (no production code). labels Nov 22, 2026
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 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-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.

4 participants