Repository navigation
Fix the AST fuzzer aborting on a degenerate predicate such as and() - #112139
PedroTadim merged 5 commits into
Conversation
`QueryFuzzer::permutePredicateClause` delegates the flattening of an AND/OR/XOR
tree to `extractPredicates` with `op` set to the node's own name. Because the
name matched `op`, `extractPredicates` took its first branch, iterated
`func->arguments->children` and returned, appending nothing when that list is
empty. Control returned with an empty `predicates` list and tripped
`chassert(!predicates.empty())`, aborting the server.
A bare `and()` is a parseable AST (`Function and (children 1) / ExpressionList`
with zero children) and is only rejected later by the analyzer, so the fuzzer
aborts while mutating the query, long before execution. Such a node reaches the
fuzzer from the input corpus, so an empty extraction is a legitimate input
rather than an invariant violation: `extractPredicates` now keeps a degenerate
logical call as an opaque leaf and the assertion is removed.
The same condition also removes an unbounded mutual recursion. When `arguments`
is null the old guard `func->name == op && func->arguments` fell through to the
branch that calls `permutePredicateClause` on the very same node. The parser
always attaches an `ExpressionList`, so that path is hardening rather than an
observed crash; the plausible route is the function-name swap in `fuzz`, which
picks from `{"and", "or", "xor"}` without checking `arguments`.
`QueryFuzzer` is reached only from the client `--query-fuzzer-runs` loop, the
server-side `ast_fuzzer_runs` setting and `fuzzQuery`/`StorageFuzzQuery`, so no
production query path is affected. The cost of the abort is a lost fuzzing
session plus a red check and a CI database failure row on an unrelated pull
request.
The new test drives the three distinct callers of `permutePredicateClause` that
a degenerate node can reach, using `fuzzQuery` with explicit seeds so each case
is deterministic; every statement aborts on an unpatched binary.
Co-Authored-By: Claude Opus 5 <[email protected]>
Follow-up to the previous commit on this branch, which stopped the AST fuzzer from aborting on a degenerate logical call such as `and()`. That commit's stateless test asserts only that `fuzzQuery` returns rows, and `FuzzQuerySource::createColumn` falls back to emitting the unfuzzed base query, so an inert fuzzer still satisfies it. The abort oracle it provides does pin the removal of `chassert(!predicates.empty())`, but neither of the two guards that make the empty extraction impossible was pinned: dropping the degenerate-leaf `predicates.emplace_back(node)` in `extractPredicates`, or the degenerate early return in `permutePredicateClause`, left the suite green. `src/Common/tests/gtest_query_fuzzer_degenerate_predicate.cpp` calls the two private helpers directly, so each guard has its own assertion and no dependence on the fuzzer's random draw. `extractPredicates` must contribute exactly one opaque leaf for a degenerate node, and the same for a logical `ASTFunction` whose `arguments` is null (the shape that used to recurse on itself); `permutePredicateClause` must return that node unchanged, or `not` of it, never a fresh logical call wrapping it. Reverting either guard fails exactly the assertions for that guard and no others; reverting both fails all three. The gtest fixtures reach the helpers through the in-tree friend-class idiom, as `LRUFileCachePriority` and `TemporaryDataOnDisk` already do. The stateless test loses its `no-llvm-coverage` tag. Its rationale was that `fuzzQuery` drives the process-global `QueryFuzzer` whose accumulated state varies run-to-run, which is true of the scalar `fuzzQuery` function and of `03834_fuzz_query_function`, but not of the table function used here: `FuzzQuerySource` owns a per-source `QueryFuzzer` seeded from its `random_seed` argument, and `getGlobalASTFuzzer` has no caller under `src/Storages` or `src/TableFunctions`. The output is byte-identical across repeated runs and across an intervening load of 500 global-fuzzer calls, so there is nothing non-deterministic to skip. `04141_fuzz_query_max_query_length` is the same-form precedent and carries `no-fasttest` only. The remaining `no-fasttest` is load-bearing for a different reason, now stated in the test: fast builds are `NDEBUG` without sanitizers, so `chassert` expands to `(void)sizeof(...)` and the statements would pass vacuously. The comment on the new `extractPredicates` branch said extraction from a degenerate node "yields nothing" three lines above the code that appends a leaf. It now says the call contributes exactly one opaque leaf, which is the reason the extraction can no longer come back empty. The previous commit message described the test as covering every caller of `permutePredicateClause` a degenerate node can reach. That is not right: there are four call sites, the test drives a degenerate node through three of them, and the fourth, `fuzzMandatoryPredicate`, is covered by construction because the fix is in the shared callee. The failure was observed on an unrelated pull request, ClickHouse#112014, whose diff is two `ci/` Python files. It is linked below as the source of the CI report only, not as the cause. Related: ClickHouse#112014 CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112014&sha=ecda8174cacd8b3ea74e244c0c1231390fcef152&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review — 2 rounds, 10 findings, 9 AGREE / 0 DISAGREE (click to expand)Before opening this pull request I ran two rounds of independent review: a cold read of the Per-round counts, derived from the review ledgers: round 1 — 7 findings (3 from the second model, Round 1 — sent back (❌ = fixed before publication)❌ The stateless test could not see either guard. ❌ The ❌ The commit message omitted the CI report URL and the link to the pull request where the failure ❌ An in-code comment contradicted the line below it — it said extracting from a degenerate node ❌ An exhaustiveness claim was too strong — "the three distinct callers" understated the four Round 2 — clean, publishedThe second model returned 0 findings, having read every changed function, traced every caller and The cold read produced 4 findings, none of them in the shipped code: ❌ Merge order against #111406. The new early return calls the existing ❌ The description did not name the unit test, which is the only oracle for either guard and 103
Verified cleanThe restructure is behaviour-preserving for every non-degenerate input: Session id: cron:clickhouse-review-slot-9:20260727-142300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-44:20260727-130300 |
|
cc @PedroTadim @qoega — could you review this? A zero-argument logical call such as |
| @@ -16,6 +16,12 @@ | |||
| #include <Common/randomSeed.h> | |||
|
|
|||
|
|
|||
| /// Fixtures of src/Common/tests/gtest_query_fuzzer_degenerate_predicate.cpp, which drives the | |||
| /// private predicate helpers directly. | |||
| class QueryFuzzer_ExtractPredicatesKeepsDegenerateLeaf_Test; | |||
There was a problem hiding this comment.
@groeneai you don't need the gtest, leave the stateless test only
There was a problem hiding this comment.
Done in feb92ee -- the gtest and the friend declarations are gone, so src/Common/QueryFuzzer.h is byte-identical to master again, and 04651_fuzzer_degenerate_logical_predicate is the only test.
One thing worth recording, since it is the coverage the gtest was carrying. The stateless test does pin the defect as a whole: with both guards removed the mutated QueryFuzzer.cpp is byte-identical to master's, and all four statements abort. What it cannot do is isolate the two guards individually. With the chassert gone, dropping either one alone degrades output silently instead of aborting -- dropping the early return rebuilds and() as and(and()), dropping the opaque-leaf append collapses and(and()) back to and() -- and FuzzQuerySource::createColumn emits the unfuzzed base query on its fallback path, so count() > 0 holds either way. I measured that: with the assert deleted, dropping either guard leaves all four statements at rc=0.
That is fine by me if it is fine by you -- it is your code and a unit test for a fuzzer internal is a reasonable thing not to want. If you would rather keep some of it, the two cheaper options are a single gtest assertion instead of three, or leaving it as is and accepting that a future refactor of either guard will not be caught by a test. Happy either way; no need to reply if you are content with the current state.
|
Workflow [PR], commit [9176dfe] Summary: ✅
AI ReviewSummaryThis PR hardens Final VerdictStatus: ✅ Approve |
| @@ -3885,17 +3885,25 @@ void QueryFuzzer::extractPredicates(const ASTPtr & node, ASTs & predicates, cons | |||
| { | |||
| if (const auto * func = node->as<ASTFunction>()) | |||
| { | |||
| if (func->name == op && func->arguments) | |||
| if (func->name == "and" || func->name == "or" || func->name == "xor") | |||
There was a problem hiding this comment.
@groeneai please keep if (func->name == op && func->arguments) just add the if (!func->arguments || func->arguments->children.empty()) check
There was a problem hiding this comment.
Done in feb92ee -- if (func->name == op && func->arguments) is back exactly as it was, with the empty-list check nested inside it.
Your literal suggestion works as written, and it is worth saying why, because the null half now lands somewhere else. With the outer condition restored, a node whose arguments is null fails that condition and falls through to the and/or/xor branch below, which calls permutePredicateClause on the same node -- and the early return there catches it, so the recursion is broken one hop deeper than in my previous version rather than not at all. I checked that the early return really is what closes it: remove it, drive an ASTFunction{name = "and", arguments = nullptr} through permutePredicateClause, and it segfaults on a stack overflow. So inside extractPredicates the plain func->arguments->children.empty() you asked for is sufficient, and I dropped the !func->arguments || disjunct there as redundant.
Re-verified after the change: all four statements of the stateless test abort on a pristine master build and pass here, 50/50 randomized runs pass, and 03031, 03834, 04141, 04202 plus the existing QueryFuzzer unit tests are green with no reference changes.
Follow-up to the review on ClickHouse#112139. - `extractPredicates` keeps its original `if (func->name == op && func->arguments)` condition; the degenerate-argument-list check is nested inside it rather than restructuring the branch order. - Removed `src/Common/tests/gtest_query_fuzzer_degenerate_predicate.cpp` and the friend declarations it needed, so `src/Common/QueryFuzzer.h` is untouched again. `04651_fuzzer_degenerate_logical_predicate` is the only test now. With the outer condition restored, a node whose `arguments` is null no longer reaches the degenerate branch in `extractPredicates`; it falls through to the call into `permutePredicateClause`, whose own early return breaks the recursion there. Verified by removing that early return and driving an `ASTFunction{name = "and", arguments = nullptr}` through it: stack overflow, SIGSEGV. All four statements of the stateless test still abort on a pristine master build and pass here. Removing both guards reproduces master exactly (the mutated file is byte-identical to master's). 50/50 randomized runs of the new test pass, as do `03031_table_function_fuzzquery`, `03834_fuzz_query_function`, `04141_fuzz_query_max_query_length`, `04202_storage_fuzzquery_engine` and the existing `QueryFuzzer` unit tests. Related: ClickHouse#112014 CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112014&sha=ecda8174cacd8b3ea74e244c0c1231390fcef152&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
Four statements cover three distinct callers, not one each: seeds 7 and 35 both reach the recursive `extractPredicates` path.
CI finish ledger — feb92eeEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
None of the three is caused by this PR's diff, which changes Session id: cron:our-pr-ci-monitor:20260728-023000 |
Follow-up to the review on ClickHouse#112139. - `extractPredicates` keeps its original `if (func->name == op && func->arguments)` condition; the degenerate-argument-list check is nested inside it rather than restructuring the branch order. - Removed `src/Common/tests/gtest_query_fuzzer_degenerate_predicate.cpp` and the friend declarations it needed, so `src/Common/QueryFuzzer.h` is untouched again. `04651_fuzzer_degenerate_logical_predicate` is the only test now. With the outer condition restored, a node whose `arguments` is null no longer reaches the degenerate branch in `extractPredicates`; it falls through to the call into `permutePredicateClause`, whose own early return breaks the recursion there. Verified by removing that early return and driving an `ASTFunction{name = "and", arguments = nullptr}` through it: stack overflow, SIGSEGV. All four statements of the stateless test still abort on a pristine master build and pass here. Removing both guards reproduces master exactly (the mutated file is byte-identical to master's). 50/50 randomized runs of the new test pass, as do `03031_table_function_fuzzquery`, `03834_fuzz_query_function`, `04141_fuzz_query_max_query_length`, `04202_storage_fuzzquery_engine` and the existing `QueryFuzzer` unit tests. Related: ClickHouse#112014 CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112014&sha=ecda8174cacd8b3ea74e244c0c1231390fcef152&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
Related: #112014
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112014&sha=ecda8174cacd8b3ea74e244c0c1231390fcef152&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
The AST fuzzer aborts itself when it mutates a query containing a zero-argument logical call such as
and():Root cause.
permutePredicateClauseaccepts any node namedand/or/xorand delegates theflattening to
extractPredicateswithop == func->name. Because the name matchesop,extractPredicatestook its first branch — iteratefunc->arguments->childrenand return — whichappends nothing when that list is empty. Control returned with an empty
predicateslist and thechassertfired.and()is a parseable AST (Function and (children 1) / ExpressionListwith zerochildren); it is only rejected later by the analyzer, so the fuzzer aborts while mutating, long
before execution.
An empty extraction from a fuzzer input is a legitimate input, not an invariant violation, so this
fixes the flattening function rather than guarding its caller:
extractPredicatestreats adegenerate logical call as an opaque leaf, and the
chassertis removed.The early return in
permutePredicateClausealso closes an unbounded-recursion path. A node with anull
argumentsfails thefunc->name == op && func->argumentsguard and falls through to thebranch that calls
permutePredicateClauseon that very same node; the early return breaks thecycle. It is load-bearing rather than defensive: with it removed, driving an
ASTFunction{name = "and", arguments = nullptr}throughpermutePredicateClausesegfaults on astack overflow. The shape itself is hardening — the parser always attaches an
ExpressionList, so Icould not exhibit it from SQL; the plausible route is the function-name swap in
fuzz, which picksfrom
{"and", "or", "xor"}without checkingarguments.This is a bug in the fuzzing tool, not in query execution.
QueryFuzzeris reached only from theclient
--query-fuzzer-runsloop, the server-sideast_fuzzer_runssetting, andfuzzQuery/StorageFuzzQuery— there is no production query path. The impact is that the fuzzingsession is lost and a red check plus a CI database failure row are produced on an unrelated pull
request. Only builds with
chassertenabled are affected.Reproducer (deterministic,
fuzzQuerywith an explicit seed):Before the fix this aborts the server with the stack above; after it, it completes. The new test
04651_fuzzer_degenerate_logical_predicatedrives a degenerate node intopermutePredicateClausethrough three different callers —
addOrReplacePredicate, the recursive call insideextractPredicates, and the JOINONpath — and all four of its statements abort on an unpatchedbinary. The fix is in the shared callee, so the fourth call site (
fuzzMandatoryPredicate, reachedfrom lightweight
DELETE/UPDATEandALTERpredicates) is covered by construction even though nostatement targets it. The pre-existing
fuzzQuerytests (03031,03834,04141,04202) and theQueryFuzzerunit tests were re-run because the fix changes fuzzer output for degenerate inputs; allpass with no reference changes.
On the coverage that test provides: removing both guards makes all four of its statements abort, so
it pins the defect and the fix as a whole. It does not isolate the two guards individually — with the
chassertgone, dropping either one alone degrades output silently (a dropped operand, or anand(and())self-wrap) rather than aborting, andFuzzQuerySource::createColumnfalls back toemitting the unfuzzed base query, so an inert fuzzer still returns rows. A unit test covering each
guard separately was dropped from this pull request at the reviewer's request.
One merge-order note: the new early return calls the existing
tryNegateNextPredicate, which#111406 renames to
fuzzPredicate. The two branchesmerge with no textual conflict, but the merged result would not compile, because that guard would hold
the only remaining call to the old name. Whichever lands second needs the one-line rename there;
nothing else overlaps, and that pull request changes neither
extractPredicatesnor the assertion.No related open issue found.
Version info
26.8.1.248(included in26.8and later)