Repository navigation
Conversation
|
Workflow [PR], commit [c6410bb] Summary: ❌
AI ReviewSummaryReviewed PR #117187 at Findings❌ Blockers
💡 Nits
Tests
Final VerdictStatus: ❌ Block Handle matcher projections safely, restore changed-source suppression and complete determinism screening, and address the remaining fixture/error-handling and validation gaps above. Previously dismissed concerns are retained only in this summary; their threads were not reopened or duplicated. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+319.54 KiB total), 6 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units15 translation units recompiled, 44 s compile time in total, 9 of them have a recent master baseline. Symbol sizes
|
…ruth) + DDL-enablement pins
Phase 0 (step 3) of the oracle-suite architecture (tmp/oracle_plans/ARCHITECTURE.md):
move the settings makeOracleContext neutralizes into one authoritative table,
src/Interpreters/QueryOracles/OracleSettings.{h,cpp} (oraclePinnedSettings /
isPinnedByOracleContext), and rewrite makeOracleContext to iterate it. Behaviour-
preserving for the nine existing oracles (smoke + TLP-aggregate counter tests pass),
plus two new pins required for the upcoming fixture oracles:
- readonly = 0 (a leaked SET readonly=1 denies fixture DDL from the setting path)
- implicit_transaction = 0 (DDL under an implicit transaction throws NOT_IMPLEMENTED)
Shared MAX_ORACLE_OUTPUT_SIZE / MAX_ORACLE_RESULT_ROWS move to the new header. Wire
the new Interpreters/QueryOracles object library into src/CMakeLists.txt.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…inistic Both read across rows in physical block order (offset neighbours / a running state), so any oracle rewrite that reorders, repartitions or reblocks the input (TLP partitions, NoREC, DQP setting toggles, multi-threaded reads) changes their per-row output legitimately. Left out of QueryOracleChecker's non_deterministic_functions denylist, they could produce a false oracle mismatch, so add them alongside the existing rowNumberInBlock / runningDifference entries. Co-Authored-By: Claude Opus 4.8 <[email protected]>
check() ran each of the nine oracles inside an identical try/catch block that re-threw AST_FUZZER_ORACLE_MISMATCH and swallowed every other error with the same log line — ~150 lines of copy-paste that any new oracle had to duplicate. Replace them with a single run_oracle(name, fn) lambda that applies the guard uniformly; the per-oracle log wording and the outer mismatch-settings annotation are preserved, so behavior is unchanged. Verified: the existing oracle stateless tests still pass and the oracles still fire (generic and TLP-aggregate ProfileEvents still increment). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…zzing Live fuzzing of master surfaced four classes of false oracle mismatch — each a construct whose result is not stable across the oracle's metamorphic rewrites, so the reference and the rewrite legitimately differ: * approx_top_k / approx_top_sum (alias approx_top_count) use the same bounded Filtered-Space-Saving structure as topK: merging the partial states from the TLP UNION-ALL partition split drops different candidates than a single pass, so the approximate result differs. Added to non_deterministic_functions next to topK (stripAggregateCombinators maps the *State/*Merge forms back). * Buffer-engine tables split rows between an in-memory buffer and the backing table with a background flush thread, so two reads can return different rows. Generalised referencesDistributedTableAnywhere to a non_deterministic_table_ engines set covering both Distributed and Buffer. * ANY / RightAny joins pick an arbitrary matching right row, so which row survives is plan-dependent. Generalised hasAsofJoinAnywhere to also gate them. * JSONDynamicPaths / JSONSharedDataPaths(WithTypes) / isDynamicElementInShared- Data expose the physical dynamic-vs-shared storage split of a JSON column, decided per part/block under max_dynamic_paths, not part of the logical value; a rewrite that re-materialises the column reports a different split. Verified: a zero-mismatch soak (60-100 fuzzed runs each) over every construct, while an eligible control query still exercises the oracle (ProfileEvent checks delta 117 vs 0 for the gated seeds). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nywhere A GROUP BY totals/subtotal modifier synthesises a grand-total or subtotal row that is a global aggregate, not a per-input-row value, so it is not distributive over the WHERE/HAVING partition split the metamorphic oracles perform: each partition re-scans the source and recomputes (or drops) the totals row, so it legitimately differs from the reference. The per-oracle guards already reject a top-level `group_by_with_totals`, but a modifier hidden in a CTE or subquery (whose outer query the oracle rewrites) slipped past them. Fuzzing surfaced this as a TLP WHERE mismatch on `... FROM (SELECT ... GROUP BY g WITH TOTALS) WHERE NULL > cnt`: the totals row read (0,500) directly but (0,0) through the split. Add a recursive `hasGroupByTotalsModifierAnywhere` gate at the top of check(). Verified: zero mismatches over a 60-run soak and a 0 check-counter delta for the WITH TOTALS seed, while an eligible non-totals query still exercises the oracle. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…cle counters
Replace the hand-written per-oracle try/catch loop in QueryOracleChecker::check with
a data-driven dispatch over an ordered OracleRegistry, so adding an oracle is one
registry line instead of editing the shared dispatch region (the foundation the
planned oracle suite needs to land one file at a time).
- New IOracle interface (OracleTraits{name, event} + run) and OracleRegistry (explicit
ordered registration in the constructor). Phase-0 CheckMethodOracle adapters wrap the
nine existing check* methods via member pointers.
- Add one ProfileEvent per oracle (TLP WHERE / NoREC / TLP DISTINCT / TLP GROUP BY /
TLP HAVING / DQP / Identity WHERE / Subquery wrap; TLP Aggregate already existed),
incremented by the adapter when the oracle performs a comparison. The umbrella
ASTFuzzerOracleChecks counter is unchanged. The bespoke internal TLP-Aggregate
increment is removed in favour of the uniform adapter path.
- The check* methods become public so the registry can bind member pointers.
Behaviour-preserving: all nine oracles still fire (verified via the new per-oracle
counters), the TLP-aggregate counter path the 04658 test relies on still increments,
and a mismatch soak over WHERE/DISTINCT/aggregate shapes stays clean.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…omparison layer Move the oracle sub-query execution and result-shaping out of QueryOracleChecker into a single OracleExec class (QueryOracles/): makeOracleContext + the crash-safe ReadBuffer/WriteBuffer executeQuery path + row splitting/shaping, exposed as executeRows (SortedBag/SortedSet/Ordered shapes + settings overlay), executeScalar, tryExecuteRows (error-observing), executeStatement (fail-close DDL), and isStable (re-execution guard). Add OracleCompare with equal + the shared symmetric-diff diffSummary walk. QueryOracleChecker's executeAndCollectSortedRows / executeAndCollectSortedUniqueRows / executeWithSettings / executeScalar become thin forwarders to OracleExec, and makeOracleContext / splitIntoRows move there, so the existing check* methods are unchanged and new oracles get one shared, sound execution+comparison API (single comparison policy: same-serializer TabSeparated text equality). Behaviour-preserving: all nine oracles still fire (verified via per-oracle counters) and a mismatch soak over WHERE/DISTINCT/aggregate shapes stays clean. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…log resolvers Introduce QueryOracles/OracleGate with the shared, reusable gating primitives the planned oracles need (additive — no existing gating changed yet): - GateRelax bitmask (AllowArrayJoinClause / AllowGroupingModifiers / AllowDistinct / AllowLimit / AllowPrewhere / AllowWindow, the IdenticalTextBothSides combination, and the Bespoke marker) for the forthcoming relaxable isSafeForOracle. - resolveSingleTableStorage: the one "exactly one physical MergeTree-ish table in FROM" resolver (subsumes the per-task single-table helpers). - referencesTableMatching with a ResolveMatch tri-state (Yes/No/Unresolvable) so callers pick their own safety direction on catalog-resolution failure (uniform "failure steers to skip"). - hasTotalOrderKey: the one uniqExact-tuple total-order precheck for positional/representative comparison (subsumes the independently-invented uniqueness prechecks), via one scalar query. The relaxable isSafeForOracle refactor lands with its first consumer (the ARRAY-JOIN / grouping-modifier oracles), where it can be verified against real shapes. Co-Authored-By: Claude Opus 4.8 <[email protected]>
First new oracle on the IOracle/OracleRegistry + OracleExec/OracleCompare foundation. GROUP BY keys form a set, so permuting them (GROUP BY a, b -> GROUP BY b, a) cannot change the grouping and must yield the identical result multiset; a divergence is a real multi-key grouping or aggregation bug (two-level aggregation, aggregator key ordering). Gated by the standard isSafeForOracle plus >=2 keys and no order-sensitive grouping modifier; compares SortedBag via OracleExec::executeRows with an OracleExec::isStable guard, and reports via OracleCompare. Registered as one line in OracleRegistry with its own ProfileEvent (ASTFuzzerOracleGroupByKeyPermutationChecks). Validated locally: 221 comparisons over diverse multi-key grouping shapes (count/sum/avg/groupArray/uniqExact, expression keys) with zero mismatches. Co-Authored-By: Claude Opus 4.8 <[email protected]>
`SELECT DISTINCT <exprs> FROM ...` must return the identical result set as `SELECT <exprs> FROM ... GROUP BY <exprs>` — both deduplicate the projected tuples, but via different execution paths (DistinctStep vs the aggregator), so a divergence is a real bug. Bespoke gate (isSafeForOracle rejects DISTINCT by design): DISTINCT required, no grouping / aggregates / LIMIT family / PREWHERE / asterisk / ARRAY JOIN / window / non-determinism. The rewrite drops DISTINCT and adds GROUP BY over the alias-stripped SELECT expressions; compares SortedBag via OracleExec with an isStable guard, reports via OracleCompare. Validated locally: 533 comparisons over varied projections (expressions, Nullable columns, function calls) with zero mismatches. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add per-oracle "proof it ran" counter tests (modelled on 04658) for the GROUP BY key permutation and DISTINCT-via-GROUP-BY oracles: each retries a fuzzed eligible seed until the oracle's dedicated ProfileEvent increments, so the test fails if the oracle path can never fire. Co-Authored-By: Claude Opus 4.8 <[email protected]>
On a single MergeTree-family table, PREWHERE is a transparent read-time optimization of WHERE: `SELECT ... WHERE p` and `SELECT ... PREWHERE p` must return the identical result multiset. A divergence is a real PREWHERE bug (a historically bug-prone area). Uses the new resolveSingleTableStorage gate (single physical MergeTree table, no JOIN/subquery/TF) plus the non-determinism / ARRAY JOIN / alias guards; moves WHERE into PREWHERE and compares SortedBag via OracleExec with an isStable guard. Validated locally: 299 comparisons over varied predicates/shapes with zero mismatches. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Data-skipping indexes only prune granules that cannot match, so they must never change the result: running byte-identical SQL with use_skip_indexes=0 vs use_skip_indexes=1 must return the identical multiset. A difference is a real granule-pruning bug. Gated to a single MergeTree-family table with a WHERE (nothing to prune otherwise); both sides run the same stripped text (SETTINGS stripped so the query cannot override the overlay), compared SortedBag via OracleExec with an isStable guard. Validated locally: 293 comparisons over minmax/set-indexed tables with zero mismatches. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Toggle one result-invariant optimizer/cache setting off vs on over byte-identical SQL and require the identical result multiset. These settings are pure optimizations/caches that must never change results, so a divergence is a real bug. First batch (not overlapping checkDQP's list): use_query_condition_cache, query_plan_optimize_lazy_materialization, query_plan_optimize_prewhere. One flip is chosen per candidate; both sides run the same stripped text (SETTINGS stripped so the query cannot override the overlay), compared SortedBag via OracleExec with an isStable guard. Validated locally: 646 comparisons across the three flips over varied shapes, zero mismatches. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ant flips Add JIT-compilation (compile_expressions / compile_aggregate_expressions / compile_sort_description), read-time (read_in_order_use_virtual_row / optimize_distinct_in_order) and plan-shape (query_plan_merge_filters / query_plan_remove_unused_columns) settings to the sweep. Each is a pure optimization/cache that must be value-identical to its off state. Validated: 357 comparisons across all ten flips over varied shapes (incl. Float64 aggregates and uniqExact), zero mismatches. Co-Authored-By: Claude Opus 4.8 <[email protected]>
OracleFixture (QueryOracles/) is the single RAII owner of oracle-created tables: scratch mode allocates collision-free names, execute() runs CREATE/INSERT/DDL through OracleExec (fail-close), and the destructor DROPs every allocated table (SYNC, reverse order) unless preserve() keeps them for triage. valid() gates out environments that cannot host fixtures (system db, Replicated db). This is the keystone the DDL-based oracle families need. First fixture oracle: codec round-trip (task_28). Codecs are lossless, so identical data stored under CODEC(NONE) vs Delta/Gorilla/ZSTD must read back identical; a difference is a real codec bug. Self-seeded (ignores the fuzzed query), rate-limited. Validated locally: 15 codec checks with zero mismatches and zero leftover fixture tables (RAII create/seed/drop lifecycle confirmed). Co-Authored-By: Claude Opus 4.8 <[email protected]>
7186f18 to
ef47d35
Compare
…ing in QueryOracleChecker.cpp Fixes check_cpp.sh violations (per-oracle events declared+used in OracleRegistry.cpp). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…Ok for catch_all check The oracle's gate, fixture, and probe helpers deliberately swallow exceptions so an oracle's own internal failure can never propagate into the fuzzed query or become a false mismatch (fail-close). The style check's catch_all rule flags bare catch(...) that neither log, rethrow, nor carry an 'Ok' comment. Add such comments documenting why each swallow is safe. Comment-only change; no behavior change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Quick review:
|
# Conflicts: # src/Interpreters/QueryOracleChecker.cpp
…oracles `JSONDynamicPaths`, `JSONDynamicPathsWithTypes`, `JSONSharedDataPaths`, `JSONSharedDataPathsWithTypes` and `isDynamicElementInSharedData` report where a value is stored (its own subcolumn or shared data), which is a property of the column, not of the value. The hash join emits a required right key as a copy of the left key (`copyLeftKeyColumnToRight`), so the same right key has a different layout below and above the join, and NoREC compared a filter pushed below the join with `countIf` evaluated above it (`AST fuzzer (amd_release, oracle)` on PR ClickHouse#120579). The engine does the same for `isConstant`, which the oracles already skip because it is not deterministic. Add the five names to the backstop set. Also make `namesNonDeterministicRegularFunction` consult that set for a name that resolves to a regular function: the bare-name screen (a function passed by name to a higher-order function, or a `{param:Identifier}` holding one) read only `isDeterministic()`, so set members such as `materialize` passed in `arrayMap(materialize, arr)` form. Gating the lookup on `FunctionFactory::tryGet` keeps columns named like a table or aggregate function in the set (`url`, `sum`) checked. Marking the five non-deterministic instead was rejected: a sorting or partition key using one of them, which is accepted today, would then be rejected, and an existing table keyed on one would stop loading. ClickHouse#117187 carries the same five entries inside a larger oracle refactor. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…extraction Commit d2ea91b attached each oracle sub-query in `QueryOracleChecker::{executeAndCollectSortedRows,executeScalar,executeWithSettings}` to `ThreadGroup::createForQuery(oracle_context)` via a nested `ThreadGroupSwitcher` (`allow_existing_group=true`), so that code which reads the query context from the thread (distributed plan stage tasks and `ReadFromDistributedPlanSource`) sees the oracle's pins — `max_rows_to_read=0`, `max_threads=1`, etc. — rather than the fuzzed query's 100000-row 'break' cap. The follow-up refactor 0c44048 moved those three methods into `OracleExec::{executeRows,executeScalar,executeStatement}` but dropped the `switchToThreadGroupOf` call and its helper. With the switcher gone, `make_distributed_plan=1` stage tasks silently inherit the fuzz context's `max_rows_to_read=100000` again, so the trivial-count reference returns 900k rows while the distributed-plan variant stops at ~100k — the exact `05339_ast_fuzzer_oracle_distributed_plan_read_cap.sh` regression the earlier fix guarded. Reinstate the helper in `OracleExec.cpp` and call it at the top of `executeRows`, `executeScalar` and `executeStatement`, after the overlay settings loop and before `executeQuery` runs. No code shape changes. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Pushed Root cause. Commit What broke it. The follow-up refactor The fix. Reinstates the helper in API-drift check against the current tree:
|
|
🕵️ Thanks for 3f87869, that should fix The merge of master in 3f43d5b dropped protections that master already had, and the other 2026-10-31 bot findings are still open. Compared with
Each of these was a fix for a false positive, so please take master's version of these parts when resolving the merge, rather than re-deriving them. From my earlier comment: |
The OracleExec/OracleCompare/OracleSettings extraction reverted five eligibility screens, reintroducing false mismatches/skips flagged in review. Restore them: - `oraclePinnedSettings`: re-add `allow_dynamic_type_in_join_keys = false`. A hash join compares a `Dynamic` key by type (unlike `equals`), so a `TLP WHERE` relocation of an equality into join keys could change results. [P1] - `isOracleUnsafeFunctionName`: read order dependence from the aggregate registration (`AggregateFunctionFactory::tryGetProperties(...).is_order_dependent`, excluding window functions) instead of a partial name list, so `groupArraySample`, `groupFormat`, `flameGraph`, `hierarchicalKMeans` are screened again. [P1] - `hasNonDeterministicJoinAnywhere`: resolve `join_default_strictness` for `Unspecified` (non-`LATERAL`, non-cross) joins and screen `Semi` alongside `Asof`/`Any`/`RightAny`, so a plain `LEFT JOIN` under `join_default_strictness='ANY'` and a `SEMI` join are rejected. [P2] - `referencesUnscreenedDefinitionAnywhere`: apply the join, non-strippable inline setting, nested thread setting, and `WITH TOTALS` screens to stored definitions (view bodies, column defaults, row policies); the outer AST only names the object, so screening it alone cannot compensate. [P1] - `checkTLPAggregate`: clone `agg_func->parameters` onto the generated `-Merge` call, so e.g. `uniqUpTo(10)(x)` merges with the right threshold instead of the default, keeping parameterized-aggregate TLP coverage. [P2] Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed
One question — your On the still-unused set from your earlier review — CI retriggered on the restore commit. |
|
@qoega resolve the conversations when they are done |
master evolved the monolithic `QueryOracleChecker` while this branch extracted it into `QueryOracles/` modules (`OracleExec`, `OracleRegistry`, `OracleExec::isStable`, ...). The only conflicted file was `src/Interpreters/QueryOracleChecker.cpp`. Resolution, by concern: - Non-deterministic function set: took master's getter form (`nonDeterministicFunctions` / `nonDeterministicFunctionsLower`) and made the whole file consistent with it (the merge had left a half-converted file-scope `non_deterministic_functions_lower` variable alongside getter call sites). master's set plus the `is_order_dependent` registration guard in `isOracleUnsafeFunctionName` is the curated, known-good coverage. - Reference-stability guard: kept this branch's design and dropped master's. This branch guards the two-reads-disagree false-positive family with `OracleExec::isStable` (per-oracle dynamic re-execution) plus the static `referencesUnscreenedDefinitionAnywhere` screen. master's centralized `recordReadParts` / `readPartsChanged` part-tracking does the same job a different way, so it is superseded here. Removed the whole now-dead cluster (`recordReadParts`, `readPartsChanged`, `collectReadParts`, `expandWithElements`, `getTableExpressionAliases`, `removeWithClauses`, `namesNonDeterministicRegularFunction`, the `read_parts` member) and the `Setting` externs only it used, since an unused anonymous-namespace function fails the `-Werror` build. - Execution wrappers: kept them as thin forwarders to `OracleExec` (the merge had restored master's inline body for `executeAndCollectSortedRows`); reverted them to `static` in the header (they touch no member now). - Dispatch: kept this branch's `OracleRegistry` loop. Not ported: master's `QUERY_WAS_CANCELLED_BY_CLIENT` rethrow in the dispatch ladder. It is orthogonal to the conflict and would add a new error-code extern and a skip-vs-propagate behavior this branch's reviewed dispatch does not have; leave it for a dedicated follow-up if wanted. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Addresses review feedback that pinning `max_threads = 1` for oracle sub-queries is bad for parallel query execution. The pin (and `max_insert_threads` / `max_final_threads` / `output_format_parallel_formatting`) was added as an early mitigation for a nested-pipeline-teardown heap-use-after-free ASan/TSan caught. The root cause was that an oracle sub-query ran on the *caller's* (fuzzed query) thread group: a lifetime/ownership mismatch between the nested pipeline's workers and the group they were tracked under. The later, principled fix (`d2ea91b8acf` / restored in `3f8786906fd`) runs every sub-query on `ThreadGroup::createForQuery(oracle_context)` under an RAII `ThreadGroupSwitcher`, and the blocking `executeQuery` drains and joins the pipeline before that switcher is destroyed, so the window the pin guarded no longer exists. With the pin removed, the dependent `hasNestedThreadSettings` screen (which only existed to stop a nested `SETTINGS max_threads = ...` from overriding the pin and reopening that race) is likewise no longer needed, so it and its two call sites are removed; the other stored-definition screens are kept. Running oracle sub-queries at the default thread count is also deliberate coverage: the single-thread pin blinded the oracle to every parallel-execution bug. The amd_tsan build and `05339_ast_fuzzer_oracle_distributed_plan_read_cap` in CI validate the thread-group handling; the change is trivially revertible if a teardown race resurfaces. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… same-text oracles `checkPrewhereEquivalence`, `checkSkipIndexEquivalence` and `checkSettingFlipSweep` normalize the seed through `stripOrderAndLimit` before comparing, but did not reject the range-limit shapes that normalization silently drops, nor unordered window functions. A query like `SELECT * FROM t WHERE p ORDER BY k LIMIT 1` was therefore validated as the unbounded `SELECT * FROM t WHERE p`, counting a "successful" check on a different observable query than the one that ran (and never exercising the top-N / read-in-order path); an unordered `row_number()` could likewise renumber rows across the two executions and raise a false mismatch. Add the same guards the other re-execution oracles (`checkSubqueryWrap`, `checkIdentityWhere`) already apply: reject `LIMIT` / `OFFSET` / `LIMIT BY` / `LIMIT AFTER` / `LIMIT UNTIL`, and skip when `hasWindowFunctionWithoutOrderByAnywhere`. Also extend `checkDistinctViaGroupBy`'s existing limit guard, which rejected `LIMIT` / `LIMIT BY` / `OFFSET` but not `LIMIT AFTER` / `LIMIT UNTIL`. Addresses review comments on no-op / different-query counting in these oracles. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… and JIT setting-flip no-ops Three review fixes to the self-seeded oracles: - Codec round-trip control table: the `plain` table had no codec clauses, so it inherited the server/table default codec instead of `CODEC(NONE)` that its comment, log line, and mismatch text claim. On an installation with a non-empty default codec it compared "default codec vs explicit codecs" and could miss a bug shared with the default. Give its columns explicit `CODEC(NONE)`. - Codec round-trip one-sided failure: both reads went through the throwing `executeRows`, so a real regression where the `CODEC(NONE)` reference reads fine but the codec table throws while (de)compressing propagated as a non-mismatch exception and the dispatch downgraded it to a skip — the oracle disappeared on exactly the interesting seed. Read both sides with the error-observing `tryExecuteRows` and raise `AST_FUZZER_ORACLE_MISMATCH` when the codec side fails while the reference succeeds. - Setting-flip sweep JIT no-ops: `compile_aggregate_expressions` was armed for any query with `GROUP BY` even without an aggregate function; gate it on `hasAggregates` instead. And both JIT flips left `min_count_to_compile*` at the default 3, so the first execution of a unique fuzzed query never reached compiled code and the flip was a no-op; lower the matching threshold on both sides so flipping the flag exercises the compiled path. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ring `OracleFixture::armDropsForCreate` decided ownership with `sql.contains(name)`. Fixture names share a prefix and differ only by a trailing sequence number, so a successful `CREATE TABLE __oracle_fx_x_10 ...` also matched the allocated name `__oracle_fx_x_1` and armed a `DROP` for a table this instance never created — deleting, for example, a `preserve()`d repro left behind for triage after a restart. Match `name` only when it appears as a whole identifier token (non-identifier characters, or a string boundary, on both sides). Co-Authored-By: Claude Opus 4.8 <[email protected]>
`OracleExec::executeStatement` ran fixture `CREATE` / `INSERT` / `DROP` with
`QueryFlags{.internal = true}` only. `internal` makes `InterpreterCreateQuery`
skip the privilege check (`getRequiredAccess` returns an empty list), so a
caller allowed to enable the experimental fuzzer settings could create the
persistent fixture tables by running a successful `SELECT`, without a
`CREATE TABLE` grant.
Set `user_initiated = true` as well (as `QueryFlags` documents: `internal`
alone must never be treated as permission to skip access checks). The fixture
DDL is now checked against the caller's privileges; a missing grant throws and
the fail-close path skips the oracle, so no table is created.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
`hasWindowFunctionWithoutOrderByAnywhere` scanned only the top-level SELECT list, QUALIFY and WINDOW clauses, so an unordered `row_number()` / `rank()` / `dense_rank()` hidden in a FROM subquery or CTE — e.g. `SELECT DISTINCT rn, x FROM (SELECT row_number() OVER () AS rn, x FROM t)` — reached the re-execution oracles (`checkIdentityWhere`, `checkSubqueryWrap`, `checkPrewhereEquivalence`, `checkSkipIndexEquivalence`, `checkSettingFlipSweep`). Two independent executions can then assign different row numbers and raise a false `AST_FUZZER_ORACLE_MISMATCH` on a correct server. Also scan the FROM clause: `hasWindowFunctionWithoutOrderBy` already recurses into children, so handing it `select.tables()` reaches the window inside nested SELECTs. This only ever skips more queries (an unordered window is unstable regardless of the enclosing query), so it cannot introduce a false mismatch. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…e monolith The branch's previous master merge used a stale `origin/master`, so the PR still conflicted with the real current master. Merge current `origin/master` and re-resolve the two conflicted files (`QueryOracleChecker.cpp`/`.h`), keeping the branch's extracted `QueryOracles/` architecture and porting the genuinely-new master changes: - Ported `hasRowLimitInDistributedPlan` / `hasRowLimitAnywhere` and the `make_distributed_plan` setting extern, and wired the gate into `check` and the stored-definition screen (master #130656: a nested `LIMIT` under a distributed plan feeds one stream per source task, so the oracle's rewritten reads keep different rows — a false `TLP Aggregate` mismatch). - Ported the new `SHUFFLE` screen in the unstable-identifier gate (`SHUFFLE` returns rows in random order, a random subset with `LIMIT`). - Kept the branch's `referencesNonDeterministicEngineAnywhere` (covers `Distributed`/`Buffer`, superseding master's `referencesDistributedTableAnywhere`) and dropped master's duplicate top-level `WITH TOTALS` skip (the branch already has `hasGroupByTotalsModifierAnywhere`). - Dropped master's `recordReadParts`/`readPartsChanged`/`read_parts` from the header (superseded by `OracleExec::isStable`, as in the earlier merge). Co-Authored-By: Claude Opus 4.8 <[email protected]>
The Fast test build failed with:
QueryOracleChecker.cpp: error: unused function 'substitutedNameParts' [-Werror,-Wunused-function]
`substitutedNameParts` (resolve a `{name:Identifier}` query-parameter into table
name parts) has had no caller on this branch since the OracleExec extraction:
`isSafeForOracle` rejects any query containing an `ASTQueryParameter` outright,
so the resolve helper is dead here (master still uses it, but only on the
monolith path this branch replaces). Remove it.
Verified by compiling `QueryOracleChecker.cpp`, `OracleExec.cpp`,
`OracleSettings.cpp` and `OracleFixture.cpp` against current master locally.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
| for (const auto & expr : sel.select()->children) | ||
| { | ||
| auto key = expr->clone(); | ||
| key->setAlias(""); /// GROUP BY keys are the raw expressions, not `expr AS x` |
There was a problem hiding this comment.
[Blocker] Check that projection nodes support aliases before clearing them
A valid query such as SELECT DISTINCT COLUMNS('^a$') FROM t passes the projection gate above: its projection is an ASTColumnsRegexpMatcher, rather than an ASTAsterisk. That class, and the list/qualified matcher variants, inherit IAST::setAlias, which always throws LOGICAL_ERROR, including for an empty alias. This call therefore raises a logical exception for a valid seed and aborts debug/sanitizer builds before the dispatch can catch it.
Check for ASTWithAlias before calling setAlias, as the aggregate oracle already does when assigning grouping-key aliases, or reject matcher projections. Please cover a DISTINCT COLUMNS(...) query over a matching column.
| } | ||
| catch (const Exception & e) | ||
| { | ||
| if (e.code() == ErrorCodes::AST_FUZZER_ORACLE_MISMATCH) |
There was a problem hiding this comment.
[Blocker] Preserve the changed-source guard when replacing the dispatch
The refactor removes recordReadParts/readPartsChanged, so this handler now reports a mismatch even when the compared queries read different source versions. For example, TLP WHERE can read both (k=1, v=1) and (k=1, v=2) from a ReplacingMergeTree for its reference, then a normal background merge leaves only the latter row before the partitioned query runs. For SELECT k, v FROM t WHERE v > 0, the oracle then compares two rows with one and reports a correctness failure on a healthy server. Concurrent inserts or mutations have the same problem on other supported engines.
The existing oracles do not use the new isStable helper, and one repeated reference read would not replace source-version tracking for every comparison. Retain the per-oracle source-change suppression, or provide an equivalent snapshot/version check shared by all execution helpers.
| if (coded_out.overflow) | ||
| return false; | ||
|
|
||
| if (coded_out.error_code || !coded_out.rows) |
There was a problem hiding this comment.
[Major] Exclude cancellation and resource errors from codec mismatches
An error on the second read does not necessarily identify a codec failure. Oracle contexts inherit the fuzz context's progress callback, which throws QUERY_WAS_CANCELLED_BY_CLIENT after a disconnect. If that happens after the plain-table read succeeds, tryExecuteRows records the cancellation and this branch converts it into AST_FUZZER_ORACLE_MISMATCH, preserving both tables and reporting a false correctness failure. An inherited memory_tracker_fault_probability can likewise inject MEMORY_LIMIT_EXCEEDED into only the second read.
Treat cancellation, resource exhaustion, and injected failures as an inconclusive probe and skip them; retain mismatch reporting for reproducible codec failures. Add coverage that distinguishes an environmental failure from a decompression error.
| /// Parallelism is deliberately NOT pinned. An earlier revision pinned `max_threads` | ||
| /// (and the sibling parallelism knobs) to 1 to dodge a nested-pipeline-teardown | ||
| /// heap-use-after-free TSan caught. The root cause was the nested sub-query running on | ||
| /// the caller's (fuzzed query) thread group; `OracleExec::switchToThreadGroupOf` now runs | ||
| /// every sub-query on `ThreadGroup::createForQuery(oracle_context)` under an RAII | ||
| /// `ThreadGroupSwitcher`, so its workers are owned and joined under the sub-query's own | ||
| /// group, and the blocking `executeQuery` drains the pipeline before that switcher is | ||
| /// destroyed — the window the pin guarded no longer exists. Pinning single-thread also |
There was a problem hiding this comment.
[Major] Demonstrate that parallel teardown is safe before removing its guards
The stated justification does not establish that the previously observed use-after-free is fixed: the base implementation already called switchToThreadGroupOf before executing each oracle query, alongside the single-thread and parallel-formatting pins. The extracted helper preserves that switch, while this change removes all those pins and the nested-thread-setting screen. ThreadGroupSwitcher changes thread-group association; it does not itself own or join pipeline workers.
Please retain the guards until the worker-lifetime fix is identified, or include focused ASan/TSan evidence covering parallel oracle execution and exceptional/cancelled pipeline teardown. The current counter tests and the distributed read-cap test do not demonstrate that this lifetime race is closed.
Extends the server-side AST fuzzer correctness oracle (added in #99980) into a maintainable,
data-driven framework and adds the first batch of new oracles. This is the foundation the rest of the
suite builds on.
Framework:
IOracle+ orderedOracleRegistryreplace the hand-written per-oracle try/catch ladder inQueryOracleChecker::check(adding an oracle is one registry line), with one ProfileEvent per oracle.OracleExec/OracleCompare: the single execution+comparison layer (executeRows withSortedBag/SortedSet/Ordered shapes, executeScalar, tryExecuteRows, executeStatement, isStable;
same-serializer TabSeparated equality + diffSummary).
makeOracleContextmoves here.OracleGate: shared catalog resolvers (resolveSingleTableStorage,referencesTableMatching,hasTotalOrderKey) and theGateRelaxbitmask.OracleFixture: RAII owner of oracle-created tables (create/seed/drop, preserve-on-mismatch).oraclePinnedSettings: single source of truth for the neutralizing settings pinned on nestedoracle sub-queries; adds
readonly=0/implicit_transaction=0so fixture DDL is executable.joins, JSON storage-introspection funcs, WITH TOTALS/ROLLUP/CUBE/GROUPING SETS anywhere,
neighbor/runningAccumulate).
New oracles: GROUP BY key permutation, DISTINCT-via-GROUP-BY, PREWHERE equivalence, skip-index
equivalence, setting-flip sweep (result-invariant optimizer/cache flips), codec round-trip. Each is
soak-validated (>=200 fuzzed comparisons, 0 false positives). Plus stateless counter tests.
Supersedes #117189 (per-oracle dispatch collapse; folded here) and #117347 (non-deterministic gates;
folded here) — both closed via branch delete. This is PR 1/4 of the full oracle-suite series.
Related: #99980
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Not for changelog (internal AST-fuzzer testing infrastructure).
cc @groeneai
Workflow [PR]
Sync PR [sync-upstream/pr/117187]