Skip to content

Add TLP and NoREC correctness oracles to the server-side AST fuzzer - #99980

Merged
fm4v merged 48 commits into
masterfrom
ast-fuzzer-oracle
Aug 29, 2026
Merged

fm4v merged 48 commits into
masterfrom
ast-fuzzer-oracle

Conversation

@qoega

@qoega qoega commented Mar 18, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a lifetime bug in ColumnAggregateFunction::convertToValues that could produce incorrect results or an exception for -State aggregates combined with -OrDefault / -OrFill under WITH TOTALS, ROLLUP, or CUBE. The bug was found by the TLP and NoREC correctness oracles this PR adds to the server-side AST fuzzer (internal testing infrastructure, controlled by the new experimental ast_fuzzer_oracle setting, with a dedicated CI job running the oracle-enabled fuzzer against the release build).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Not a user-facing feature — this is internal testing infrastructure.


Summary

Integrates two metamorphic testing oracles from the SQLancer project into the built-in server-side AST fuzzer:

  • TLP WHERE (Ternary Logic Partitioning): for a query with WHERE p, verifies that SELECT ... FROM t produces the same sorted result set as SELECT ... WHERE p UNION ALL SELECT ... WHERE NOT p UNION ALL SELECT ... WHERE isNull(p).

  • NoREC (Non-optimizing Reference Engine Construction): verifies that SELECT count() FROM t WHERE cond equals SELECT countIf(cond) FROM t.

Instead of generating queries from scratch (as SQLancer does), the oracles check queries that the AST fuzzer already produces and executes successfully. Applicable queries must be simple SELECTs (no JOINs, DISTINCT,
GROUP BY, HAVING, LIMIT, QUALIFY, window/aggregate functions) with a WHERE clause against a real table. Non-deterministic functions are detected and skipped.

On mismatch, throws LOGICAL_ERROR which crashes the server — making bugs immediately visible in CI.

CI integration:

  • New job "AST fuzzer (amd_release, oracle)" in PR checks, using the release (RelWithDebInfo) build.
  • Enabled via AST_FUZZER_ORACLE=1 environment variable which applies ast_fuzzer_runs=1 and ast_fuzzer_oracle=1 as server default profile settings.

Testing done:

  • Oracle verified with 1000+ passes on non-empty tables (200–500 rows).
  • Found a real correctness bug during testing: WHERE (x > 0) AND -2147483648 incorrectly returns 0 rows on MergeTree (INT_MIN truncated to UInt8 → 0 in the filter path).

Note

Medium Risk
Adds new oracle-execution paths and a new ast_fuzzer_oracle setting inside executeQuery, plus new CI jobs/config; although gated behind an experimental setting, it touches core query execution and introduces new failure/exit-code handling that could affect CI stability.

Overview
Introduces an experimental ast_fuzzer_oracle mode that runs a new QueryOracleChecker after each successfully executed fuzzed SELECT, applying multiple metamorphic correctness checks (TLP variants, NoREC, DQP, identity predicate rewrites, and subquery wrapping) and throwing AST_FUZZER_ORACLE_MISMATCH on mismatches.

Extends fuzzing/CI plumbing to support this mode: the AST fuzzer now preserves oracle-friendly query structure (oracle_mode), the client/fuzzer job detects oracle mismatches via a dedicated exit code with better log artifact upload, and PR/Master workflows add a new "AST fuzzer (amd_release, oracle)" job plus fuzzer config tweaks to enable the setting during that run.

Reviewed by Cursor Bugbot for commit 840494d. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9ba15e5]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
04256_04250_ast_fuzzer_oracle_tlp_aggregate FAIL cidb IGNORED
Unknown error FAIL cidb IGNORED

AI Review

Summary

Adds server-side AST-fuzzer correctness oracles, CI wiring, and a real ColumnAggregateFunction::convertToValues bug fix with regression tests. The production fix looks sound, but the oracle path still has three contract gaps that can either leak state into fuzzQuery or let the checker validate query shapes it promised to skip, and the PR metadata still advertises this as a pure testing change.

PR Metadata
  • 💡 Changelog category is incorrect. The diff includes a user-visible bug fix in ColumnAggregateFunction::convertToValues (src/Columns/ColumnAggregateFunction.cpp:186-193) plus regression tests, so Build/Testing/Packaging Improvement understates the merged behavior. Replace it with Bug Fix (user-visible misbehavior in an official stable release).
  • 💡 For that category, a changelog entry is required. The current entry is specific and user-readable, so it can stay as-is once the category is corrected.
Findings
  • ⚠️ Major: [src/Interpreters/executeQuery.cpp:3432-3435] oracle_mode is written into the process-global QueryFuzzer singleton and never restored. fuzzQuery reuses the same singleton without setting oracle_mode (src/Functions/fuzzQuery.cpp:97-99, src/Functions/fuzzQuery.cpp:130-131), so one ast_fuzzer_oracle=1 query changes later fuzzQuery results until some other AST-fuzzer run flips the flag back. Suggested fix: scope oracle_mode to one fuzz invocation (save/restore under the existing mutex, or pass it into fuzzMain instead of storing it on shared state).
  • ⚠️ Major: [src/Interpreters/QueryOracleChecker.cpp:898-925,2493-2529] The fail-closed source gate still only sees raw ASTTableIdentifiers and a storage name equal to Distributed. A View or alias wrapper over system.* or a Distributed table therefore still passes even though repeated reads are not safe for equality oracles. That can raise false AST_FUZZER_ORACLE_MISMATCH exceptions on query shapes the checker claims to skip. Suggested fix: unwrap view/alias-style relations to their underlying query/storage before deciding safety, or conservatively reject those wrapper engines in oracle mode.
  • ⚠️ Major: [src/Interpreters/QueryOracleChecker.cpp:1929-2051] checkTLPAggregate still only accepts select items whose AST hash is either a top-level aggregate or the literal GROUP BY expression. Common grouped forms like SELECT number % 2 AS g, count() ... GROUP BY g or SELECT toString(g), count() ... GROUP BY g therefore never reach the aggregate oracle, even though the PR now advertises grouped-aggregate coverage. Suggested fix: resolve GROUP BY aliases and select-time projections through the _g_N mapping, or explicitly narrow the contract and add an alias-based regression test proving the limitation is deliberate.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  • scope QueryFuzzer::oracle_mode to a single fuzz invocation;
  • make the oracle fail closed for wrapper relations over system.* and Distributed sources;
  • either support grouped-aggregate aliases/projections in checkTLPAggregate or narrow the contract and cover that narrower behavior with a focused test;
  • fix the PR Changelog category to Bug Fix (user-visible misbehavior in an official stable release).

LLVM Coverage Report

Measured on commit 9ba15e5.

Metric Baseline Current Δ
Lines 88.50% 88.40% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 80.80% 80.70% -0.10%

Changed lines: Changed C/C++ lines covered: 722/1331 (54.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Mar 18, 2026
@qoega
qoega force-pushed the ast-fuzzer-oracle branch from 20ca543 to f6ae5c5 Compare March 19, 2026 13:06
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
@qoega
qoega force-pushed the ast-fuzzer-oracle branch from 1725578 to 8e85b2f Compare April 21, 2026 14:32
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Common/QueryFuzzer.cpp Resolved
@qoega

qoega commented May 5, 2026

Copy link
Copy Markdown
Member Author

qoega added a commit that referenced this pull request May 5, 2026
…cache`

CI run #99980 (`5d720a3a05f`) confirmed the oracle is firing on PR
checks. The single mismatch reported was a false positive on
`SELECT elapsed, query FROM system.processes` — the reference and
wrapped variant each take a fresh snapshot of currently-running queries
and naturally disagree. Skip any query whose `FROM` references the
`system` or `INFORMATION_SCHEMA` databases at the gate in
`QueryOracleChecker::check`, before any oracle runs.

Also remove the `<use_query_condition_cache>0</use_query_condition_cache>`
line from `oracle-fuzzer-tweaks-users.xml`. The CI fuzzer should keep
exercising the QCC code path so the cache poisoning we observed earlier
can be reproduced and reported as a real bug rather than masked at the
fuzzer side.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator

@qoega — investigated. Short answer: not a new bug introduced by this PR, and not an oracle finding. It's the chronic MSan-in-aggregate-HashTable-serialization class (STID 1486-XXX), with this specific sub-variant (1486-2c70) being a fresh stack but the same root pattern.

Stack signature

WARNING: MemorySanitizer: use-of-uninitialized-value
#0 DB::writeVarUInt                     src/IO/VarInt.h:18
#1 HashTable<...>::write                src/Common/HashTable/HashTable.h:1362
#2 AggregateFunctionCombinatorArgMinArgMax<true>::serialize
                                        src/AggregateFunctions/Combinators/AggregateFunctionCombinatorsArgMinArgMax.cpp:192
#3 AggregateFunctionOrFill<false>::serialize
                                        src/AggregateFunctions/Combinators/AggregateFunctionOrFill.h:263
#4 ColumnAggregateFunction::updateHashWithValue
                                        src/Columns/ColumnAggregateFunction.cpp:452
#5–8 ColumnsHashing::hash128 → DistinctTransform::buildFilter
#9   DistinctTransform::transform       src/Processors/Transforms/DistinctTransform.cpp:240

The "Member fields were destroyed" half of the report shows the HashTable was already torn down via TotalsHavingTransform::transform → finalizeChunk → ~ColumnAggregateFunction → AggregateFunctionDistinct::destroy → ~HashTable() — i.e. classic use-of-destructed-state through a parallel ColumnAggregateFunction that aliases the same arena entries.

It's not in your oracle code

Every frame is engine-side (DistinctTransform / TotalsHavingTransform / aggregate combinators). No QueryOracleChecker / QueryFuzzer / runOracle frames. The crashing query was a regular AST-fuzzer-generated query, not a TLP/NoREC rewrite — TLP/NoREC explicitly skip queries with DISTINCT, GROUP BY, HAVING, aggregates, etc., so they wouldn't have produced an argMin/argMaxIfDistinct(orFill) pattern.

CIDB cross-PR for STID 1486-XXX (90 days)

pull_request hits last seen check_name STID
#93384 (nihalzp, cramersV window optimization) 5 2026-04-10 Stateless tests (amd_msan, flaky check) 1486-388c (CrossTab/CramersV branch)
#99980 (this PR) 1 2026-05-05 AST fuzzer (amd_msan) 1486-2c70 (argMinArgMax/distinct/orFill branch)
master 0 — — —

Two existing closed issues (#92045, #90926) have other 1486-XXX sub-variants (segfault and UBSan respectively). 0 hits on master in 90d for this stem — the class only surfaces under unusual aggregate combinator combinations that fuzzer / flaky-check rerun storms tend to find.

Classification

  • Known chronic class (1486-XXX family — uninitialized HashTable cells written through HashTable::write → writeVarUInt from inside an aggregate combinator's serialize()).
  • New sub-variant for this stack (1486-2c70 = argMinArgMax+distinct+orFill on top of TotalsHaving + Distinct): first ever occurrence, but mechanically identical to the CramersV variant on Optimize cramersV, cramersVBiasCorrected, theilsU, and contingency when used with window functions #93384.
  • Not introduced by this PR. Neither the oracle code nor QueryFuzzer.cpp changes are on the stack. The engine bug is pre-existing.
  • Not surfaced by your oracles. The crashing query has DISTINCT + aggregate-with-Distinct combinator + WITH TOTALS, none of which are eligible for TLP/NoREC rewrite.

Recommendation

Don't block this PR on it. Re-trigger the AST fuzzer (amd_msan) job — at 1 hit / 60d under the regular fuzzer, it'll almost certainly pass. The underlying engine bug deserves a separate tracking issue ("MSan use-of-uninitialized-value when serializing aggregate-function HashTable state through argMin/argMaxIfDistinct(orFill) combined with WITH TOTALS + DISTINCT") — happy to file it if you want.

If anything, this is mild evidence the new oracle infra is healthy: the only fuzzer-amd_msan failure on the PR is a chronic engine pattern and not anything your oracle code is doing.

Session: cron:clickhouse-ci-task-worker:20260505-211500

Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Core/Settings.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.h Resolved
qoega added a commit that referenced this pull request May 7, 2026
When the FROM clause is `(... UNION ALL ...)` whose branches have
mismatched column types, the resulting subquery exposes
`Variant(...)` columns. The same predicate then evaluates to
different counts depending on whether it sits directly on the union
output, behind an intermediate `SELECT *`, or is pushed into the
individual branches before the type unification — and the oracle's
reference-vs-rewrite comparison can't tell those alternatives apart
from a real correctness bug. Reject such queries at the gate in
`QueryOracleChecker::check`.

Found by the oracle in PR #99980 CI: NoREC oracle reported a 433-vs-107
mismatch on `SELECT * FROM (SELECT c, b, a FROM _s1 UNION ALL SELECT
DISTINCT a, b, c FROM _s1 PREWHERE …) WHERE 100 > a`. The two paths
take genuinely different routes through Variant comparison; without
agreed semantics we can't claim either is "the" right answer.

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

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@qoega

qoega commented May 17, 2026

Copy link
Copy Markdown
Member Author

It waits for #104767 to be merged

Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread programs/client/FuzzLoop.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
qoega added a commit that referenced this pull request May 19, 2026
Multiple small follow-ups from the review of PR #99980.

  * `executeQuery.cpp` — narrow the `try { executeASTFuzzerQueries }` rethrow
    from any `LOGICAL_ERROR` to `AST_FUZZER_ORACLE_MISMATCH` so unrelated
    internal `LOGICAL_ERROR`s from fuzzed queries no longer abort the run.
  * `QueryOracleChecker.cpp` — exclude `sum` / `sumWithOverflow` from the
    aggregates allowed in `checkTLPAggregate`. Floating-point addition is
    non-associative, so the `sumState`/`sumMerge` rewrite can legitimately
    produce a rounded value different from direct `sum` over `Float32`/
    `Float64` arguments, which surfaced as flaky `oracle mismatch`.
  * `QueryOracleChecker.cpp` — cap oracle-context result size with
    `max_result_rows=10M` and `max_result_bytes=10MB` instead of leaving
    both at `0` (unbounded). Avoids materialising arbitrarily large
    `WriteBufferFromOwnString` outputs before the post-check.
  * `QueryOracleChecker.{h,cpp}` — change `executeAndCollectSortedRows` and
    friends to return `std::optional<std::vector<String>>`. Returning `{}` on
    overflow conflated "true empty result" with "skipped due to size";
    callers now see `std::nullopt` and skip the oracle rather than risk a
    false pass when both sides truncate to empty.
  * `QueryOracleChecker.cpp::checkIdentityWhere` — forbid `LIMIT` entirely
    (not just `LIMIT` without `ORDER BY`). With non-unique sort keys the
    reference and rewritten predicates can legitimately pick different
    rows among ties, producing false mismatches.
  * `QueryOracleChecker.h`, `Settings.cpp` — update the class-level docstring
    and the user-facing `ast_fuzzer_oracle` description so they list the
    current oracle suite (TLP WHERE/DISTINCT/GROUP BY/HAVING/Aggregate,
    NoREC, DQP, Identity WHERE, Subquery wrap) instead of the original
    "TLP and NoREC".
  * `QueryFuzzer.cpp` — fix "And we only fuzzing" typo.
  * `tests/queries/0_stateless/04256_04250_ast_fuzzer_oracle_tlp_aggregate`:
    new stateless test exercising `checkTLPAggregate` with and without
    `GROUP BY` so the `State`/`Merge` rewrite path is covered.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
@qoega

qoega commented Aug 31, 2026

Copy link
Copy Markdown
Member Author

We have conflicts all the time in public and private so low chance to merge it at all. We waited for weekend to resolve it and we had 10+ full green commits in this branch that just had conflicts

alexey-milovidov added a commit that referenced this pull request Sep 2, 2026
…exit code

The revert also dropped a generic harness improvement from #99980: attaching
`fuzzer.log`, `server.log`, `stderr.log` and the sanitizer artifacts whenever
`fuzzer_exit_code` is non-zero, not only when the job is marked failed. Exit
codes 137 and 143 from the `FUZZ_TIME_LIMIT` timeout wrapper are classified as
successful, so without this the timed-out runs looked like clean green jobs with
no logs to inspect. Restore the `is_failed or fuzzer_exit_code != 0` condition.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…cache`

CI run ClickHouse#99980 (`5d720a3a05f`) confirmed the oracle is firing on PR
checks. The single mismatch reported was a false positive on
`SELECT elapsed, query FROM system.processes` — the reference and
wrapped variant each take a fresh snapshot of currently-running queries
and naturally disagree. Skip any query whose `FROM` references the
`system` or `INFORMATION_SCHEMA` databases at the gate in
`QueryOracleChecker::check`, before any oracle runs.

Also remove the `<use_query_condition_cache>0</use_query_condition_cache>`
line from `oracle-fuzzer-tweaks-users.xml`. The CI fuzzer should keep
exercising the QCC code path so the cache poisoning we observed earlier
can be reproduced and reported as a real bug rather than masked at the
fuzzer side.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
When the FROM clause is `(... UNION ALL ...)` whose branches have
mismatched column types, the resulting subquery exposes
`Variant(...)` columns. The same predicate then evaluates to
different counts depending on whether it sits directly on the union
output, behind an intermediate `SELECT *`, or is pushed into the
individual branches before the type unification — and the oracle's
reference-vs-rewrite comparison can't tell those alternatives apart
from a real correctness bug. Reject such queries at the gate in
`QueryOracleChecker::check`.

Found by the oracle in PR ClickHouse#99980 CI: NoREC oracle reported a 433-vs-107
mismatch on `SELECT * FROM (SELECT c, b, a FROM _s1 UNION ALL SELECT
DISTINCT a, b, c FROM _s1 PREWHERE …) WHERE 100 > a`. The two paths
take genuinely different routes through Variant comparison; without
agreed semantics we can't claim either is "the" right answer.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Multiple small follow-ups from the review of PR ClickHouse#99980.

  * `executeQuery.cpp` — narrow the `try { executeASTFuzzerQueries }` rethrow
    from any `LOGICAL_ERROR` to `AST_FUZZER_ORACLE_MISMATCH` so unrelated
    internal `LOGICAL_ERROR`s from fuzzed queries no longer abort the run.
  * `QueryOracleChecker.cpp` — exclude `sum` / `sumWithOverflow` from the
    aggregates allowed in `checkTLPAggregate`. Floating-point addition is
    non-associative, so the `sumState`/`sumMerge` rewrite can legitimately
    produce a rounded value different from direct `sum` over `Float32`/
    `Float64` arguments, which surfaced as flaky `oracle mismatch`.
  * `QueryOracleChecker.cpp` — cap oracle-context result size with
    `max_result_rows=10M` and `max_result_bytes=10MB` instead of leaving
    both at `0` (unbounded). Avoids materialising arbitrarily large
    `WriteBufferFromOwnString` outputs before the post-check.
  * `QueryOracleChecker.{h,cpp}` — change `executeAndCollectSortedRows` and
    friends to return `std::optional<std::vector<String>>`. Returning `{}` on
    overflow conflated "true empty result" with "skipped due to size";
    callers now see `std::nullopt` and skip the oracle rather than risk a
    false pass when both sides truncate to empty.
  * `QueryOracleChecker.cpp::checkIdentityWhere` — forbid `LIMIT` entirely
    (not just `LIMIT` without `ORDER BY`). With non-unique sort keys the
    reference and rewritten predicates can legitimately pick different
    rows among ties, producing false mismatches.
  * `QueryOracleChecker.h`, `Settings.cpp` — update the class-level docstring
    and the user-facing `ast_fuzzer_oracle` description so they list the
    current oracle suite (TLP WHERE/DISTINCT/GROUP BY/HAVING/Aggregate,
    NoREC, DQP, Identity WHERE, Subquery wrap) instead of the original
    "TLP and NoREC".
  * `QueryFuzzer.cpp` — fix "And we only fuzzing" typo.
  * `tests/queries/0_stateless/04256_04250_ast_fuzzer_oracle_tlp_aggregate`:
    new stateless test exercising `checkTLPAggregate` with and without
    `GROUP BY` so the `State`/`Merge` rewrite path is covered.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…lock to 26.6

The `ast_fuzzer_oracle` setting was registered in the `26.5` `addSettingsChanges`
block, but the setting was actually introduced after the 26.5 baseline that
`02995_new_settings_history.sh` uses. The test correctly flags it as missing:

    PLEASE ADD THE NEW SETTING TO SettingsChangesHistory.cpp: ast_fuzzer_oracle WAS ADDED

The test's join against `system.settings_changes` only accepts entries whose
`version` is strictly greater than 26.5, so the existing 26.5-block entry was
ignored.

Move the entry into the 26.6 block (where it belongs since it's a new addition
post-26.5). No behaviour change; pure registration-bookkeeping fix.

Closes the `02995_new_settings_history` failure on PR ClickHouse#99980.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `Stateless tests (amd_tsan/amd_msan, flaky check)` jobs rerun every test
100x and assert that the server.log is free of `<Error>` lines. Our
`04256_04250_ast_fuzzer_oracle_tlp_aggregate.sql` invokes the AST fuzzer
(`ast_fuzzer_runs = 1`) on the input queries; the fuzzer produces random
mutations and some of them are nonsense — e.g. `min(...)` with the wrong
arity, FINAL on a MergeTree that doesn't support it, syntax errors. Each
nonsense query writes a `<Error>` line and the flaky check fails the test
with reason "having stderror" even though the test itself passes.

The sibling test `03833_server_ast_fuzzer.sql` solves the same problem with
`SET send_logs_level = 'fatal';`. Apply the same SET so error logs from
fuzzer-produced garbage stay below the threshold.

PR ClickHouse#99980, commit ed7b9d1 flaky-check failures.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
* `QueryFuzzer::addOrReplacePredicate` (ClickHouse#99980 comment 2): the
  oracle-mode guard against dropping `WHERE`/`HAVING` was too coarse —
  it fired at any AST depth. Only the *topmost* query's predicates are
  load-bearing for the oracle's TLP partitioning and TLP HAVING tests;
  sub-query `WHERE`/`HAVING` are fine to fuzz away. Gate on
  `current_ast_depth <= 1` (same condition the existing EXPLAIN-conversion
  branch a few lines down uses).

* `executeQuery.cpp` ASTFuzzer finish callback (comment 3): drop the
  trailing `catch (...)` block. The `catch (const Exception &)` handler
  above it already rethrows oracle mismatches and falls through to
  `tryLogCurrentException` for everything else, and ClickHouse code
  paths consistently throw `DB::Exception`, so the catch-all was
  duplicating the same `tryLogCurrentException` call.

* `QueryOracleChecker::hasNonDeterministicFunctions` (comment 4): stop
  relying solely on a hand-maintained name list. Look every
  `ASTFunction` up through `FunctionFactory::tryGet` and consult
  `IFunctionBase::isDeterministic` (the same `system.functions.is_deterministic`
  source other call sites in the codebase use — see `QueryResultCache`,
  `MutationsNonDeterministicHelpers`). Also consult
  `UserDefinedSQLFunctionFactory` (SQL UDFs — opaque, treated as
  non-deterministic) and `UserDefinedExecutableFunctionFactory`. The
  static `non_deterministic_functions` set stays as a backstop for two
  cases the factory cannot reach: table functions (`file`/`url`/`s3`/
  `numbers`/...) and aggregates whose `State`/`Merge` rewrite diverges
  from direct evaluation (`any`/`topK`/`quantile*`/`sum` on floats/...).
  The signature gained a `ContextPtr` argument; all 9 call sites now
  pass the oracle `context` they already have.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ROUP BY depth gate

Three more PedroTadim review items (PR ClickHouse#99980, 2026-05-28 13:00Z review pass):

* `QueryOracleChecker.cpp` aggregate blocklist: add `argMin`, `argMax`,
  `groupConcat`. The bot flagged that these are order-dependent on
  ties — the `State`/`Merge`, DQP and subquery-wrap rewrites can
  legitimately pick a different "arg" value or concatenation order
  than direct evaluation, so exact row equality is wrong and would
  surface as a false `AST_FUZZER_ORACLE_MISMATCH`.

* `executeQuery.cpp` AST-fuzzer outer try/catch (line 2209 in the
  multi-run loop): drop the trailing `catch (...)`. The `catch (const
  Exception &)` above it already rethrows oracle mismatches and falls
  through to the same `reset_transactions()` + `LOG_TRACE` +
  `notifyQueryFailed` shape, and ClickHouse code paths throw
  `DB::Exception`, so the catch-all was a duplicate. Same fix shape as
  the inner finish-callback handler in the previous review round.

* `QueryFuzzer.cpp` random-GROUP-BY mutation: the previous gate was
  `!oracle_mode` at any depth, but the issue is only the topmost
  query — adding GROUP BY to a sub-query just changes the row count of
  the inner result, which the outer SELECT-list (the one the oracle
  checks) has to handle anyway. Allow at `current_ast_depth > 1`, same
  shape as the WHERE/HAVING depth gate added in the previous round.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Pre-merge cleanup of four outstanding review comments on PR ClickHouse#99980:

* `tryPopulateTable` was 60+ lines of dead code (cursor[bot] comment on
  what was line 1812). The only call site has been commented-out for
  weeks because the random `INSERT … FROM generateRandom` injection
  produced its own false-positive mismatches (different row counts
  between reference and partitioned queries). Drop the method, its
  header declaration, and the commented-out call. The fuzzer's seed
  `populate.sql` already provides table content.

* `checkTLPAggregate` aggregate blocklist: extend the approximate
  quantile family to cover the plural-result variants (`quantilesTDigest`,
  `quantilesGK`, `quantilesTiming`, `quantilesDD`, …) and the exact /
  weighted / exclusive-inclusive / interpolated names that share the
  same approximate `State`/`Merge` merge path. clickhouse-gh[bot] noted
  these names appear in the fuzzer dictionary and would otherwise let
  the oracle compare an aggregate against its own metamorphic rewrite
  with legitimately-different rounded values.

* `checkIdentityWhere` now also rejects bare `OFFSET` (without
  `LIMIT`). Same order-tie family as `LIMIT` / `LIMIT BY` already
  rejected above: for non-unique `ORDER BY` keys, the rewritten WHERE
  may legitimately reorder tied rows so the same `OFFSET` skips a
  different prefix.

* cursor[bot]'s DQP `enable_optimize_predicate_expression` no-op
  finding was already addressed in `bfb099db5ee` — no change needed.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Three correctness bot findings on PR ClickHouse#99980:

* Window-function-without-ORDER-BY scan in `checkSubqueryWrap` and
  `checkIdentityWhere` only walked `select.select()`, missing
  `QUALIFY row_number() OVER () = 1` and named `WINDOW w AS (...)`
  definitions. Add `hasWindowFunctionWithoutOrderByAnywhere` that
  scans select / qualify / window slots, and use it at both gates.

* `checkTLPGroupBy` deduplicated both sides (`SortedUniqueRows`) on
  the assumption that the SELECT list equals the GROUP BY columns. If
  the projection is non-injective (e.g. `SELECT g % 2 ... GROUP BY g`),
  two distinct groups can render to the same output row; dedupe then
  hides a dropped group on the partitioned side and the oracle passes
  spuriously. Require every SELECT-list expression to be exactly a
  GROUP BY expression (by `getTreeHash` equality) before running the
  oracle — otherwise skip.

* `checkTLPHaving` switched from `SortedUniqueRows` to
  `SortedRows`. TLP HAVING partitions complete groups by the HAVING
  predicate; the three branches are disjoint at the group level so
  `UNION ALL` preserves bag multiplicity. Deduplicating would let a
  wrong result pass when different groups produce identical output
  rows (e.g. `SELECT count() FROM t GROUP BY g HAVING count() > 0`
  returning `{10, 10}` — if the partitioned rewrite drops one group
  both sides become `{10}` after dedupe).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-build Pull request with build/testing/packaging improvement 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.

7 participants