Repository navigation
Add TLP and NoREC correctness oracles to the server-side AST fuzzer - #99980
Conversation
|
Workflow [PR], commit [9ba15e5] Summary: ❌
AI ReviewSummaryAdds server-side AST-fuzzer correctness oracles, CI wiring, and a real PR Metadata
Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 9ba15e5.
Changed lines: Changed C/C++ lines covered: 722/1331 (54.24%) · Uncovered code |
20ca543 to
f6ae5c5
Compare
1725578 to
8e85b2f
Compare
|
@groeneai is the failure like that known? Or changes in AST Fuzzer trigger new bugs? |
…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]>
|
@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 The "Member fields were destroyed" half of the report shows the HashTable was already torn down via It's not in your oracle code Every frame is engine-side (DistinctTransform / TotalsHavingTransform / aggregate combinators). No CIDB cross-PR for STID 1486-XXX (90 days)
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
Recommendation Don't block this PR on it. Re-trigger the 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 |
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]>
|
This was fixed by #105146. Let's update the branch. |
|
It waits for #104767 to be merged |
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]>
|
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 |
…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.
…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]>
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]>
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]>
…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]>
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]>
* `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]>
…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]>
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]>
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a lifetime bug in
ColumnAggregateFunction::convertToValuesthat could produce incorrect results or an exception for-Stateaggregates combined with-OrDefault/-OrFillunderWITH TOTALS,ROLLUP, orCUBE. 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 experimentalast_fuzzer_oraclesetting, with a dedicated CI job running the oracle-enabled fuzzer against the release build).Documentation entry for user-facing changes
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 thatSELECT ... FROM tproduces the same sorted result set asSELECT ... 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 condequalsSELECT 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_ERRORwhich crashes the server — making bugs immediately visible in CI.CI integration:
AST_FUZZER_ORACLE=1environment variable which appliesast_fuzzer_runs=1andast_fuzzer_oracle=1as server default profile settings.Testing done:
WHERE (x > 0) AND -2147483648incorrectly returns 0 rows on MergeTree (INT_MIN truncated toUInt8→ 0 in the filter path).Note
Medium Risk
Adds new oracle-execution paths and a new
ast_fuzzer_oraclesetting insideexecuteQuery, 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_oraclemode that runs a newQueryOracleCheckerafter each successfully executed fuzzed SELECT, applying multiple metamorphic correctness checks (TLP variants, NoREC, DQP, identity predicate rewrites, and subquery wrapping) and throwingAST_FUZZER_ORACLE_MISMATCHon 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]