Skip to content

AST fuzzer oracle suite (1/4): framework + core correctness oracles - #117187

Open
qoega wants to merge 47 commits into
masterfrom
oracle-pinned-settings
Open

qoega wants to merge 47 commits into
masterfrom
oracle-pinned-settings

Conversation

@qoega

@qoega qoega commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

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 + ordered OracleRegistry replace the hand-written per-oracle try/catch ladder in
    QueryOracleChecker::check (adding an oracle is one registry line), with one ProfileEvent per oracle.
  • OracleExec / OracleCompare: the single execution+comparison layer (executeRows with
    SortedBag/SortedSet/Ordered shapes, executeScalar, tryExecuteRows, executeStatement, isStable;
    same-serializer TabSeparated equality + diffSummary). makeOracleContext moves here.
  • OracleGate: shared catalog resolvers (resolveSingleTableStorage, referencesTableMatching,
    hasTotalOrderKey) and the GateRelax bitmask.
  • OracleFixture: RAII owner of oracle-created tables (create/seed/drop, preserve-on-mismatch).
  • oraclePinnedSettings: single source of truth for the neutralizing settings pinned on nested
    oracle sub-queries; adds readonly=0/implicit_transaction=0 so fixture DDL is executable.
  • Gates the false-positive constructs found by fuzzing (approx_top_k/sum, Buffer engine, ANY/RightAny
    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):

  • Build/Testing/Packaging Improvement

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]

@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c6410bb]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 4/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

AI Review

Summary

Reviewed PR #117187 at c6410bb69a397b38093f6695c53a6728677d3d96, including the full diff, execution helpers, new oracles, tests, and all prior discussion. The PR adds a shared AST-fuzzer oracle framework and six correctness oracles. A valid COLUMNS projection now raises LOGICAL_ERROR, and removing source-version checks reintroduces false mismatches during ordinary background changes. These block approval; several earlier resolved concerns also remain in the current code.

Findings

❌ Blockers

  • Non-aliasable projections reach IAST::setAlias. QueryOracleChecker.cpp:2677: SELECT DISTINCT COLUMNS('^a$') FROM t passes the asterisk-only exclusion, but matcher nodes inherit the implementation that always throws LOGICAL_ERROR. Debug/sanitizer builds abort before the catch handler. Check for ASTWithAlias, or reject all unsupported matcher forms before constructing grouping keys.

  • Comparisons no longer reject changed source data. QueryOracleChecker.cpp:3277: deleting recordReadParts/readPartsChanged makes normal merges, inserts, and mutations appear to be wrong results. For example, a ReplacingMergeTree merge between the reference and partitioned reads changes two versions into one row. Existing oracles have no replacement stability check. Restore shared source-version validation around each comparison.

  • Executable expressions still bypass determinism screening. QueryOracleChecker.cpp:478–495 [dismissed by author -- https://github.com/AST fuzzer oracle suite (1/4): framework + core correctness oracles #117187#discussion_r4433362385]. The walker still visits only children and ordinary ASTFunction names. SELECT * APPLY (x -> rand64()) FROM t WHERE id > 0, bare APPLY function names, and function identifiers passed to higher-order functions remain unscreened, allowing false mismatches on independent evaluations. Restore the member traversal and name checks; the aggregate scanner's separate APPLY handling does not cover this walker.

⚠️ Majors

  • Parallel teardown safety remains unproven. OracleSettings.cpp:76–85: the base already switched oracle thread groups while retaining the guards against the documented use-after-free. The extraction preserves that switch, which does not itself join workers, but removes the parallelism/formatting pins and nested thread-setting guard. Identify the lifetime fix and provide focused ASan/TSan evidence for exceptional and cancelled parallel teardown, or retain the guards.

  • Environmental errors become codec failures. QueryOracleChecker.cpp:3078: a disconnect after the plain read, or an injected MEMORY_LIMIT_EXCEEDED on the coded read, becomes AST_FUZZER_ORACLE_MISMATCH and preserves the tables. Classify cancellation, resource, and injected errors as inconclusive rather than codec defects.

  • Unordered windows remain eligible in nested queries. QueryOracleChecker.cpp:2573–2576, 2655–2662 [dismissed by author -- https://github.com/AST fuzzer oracle suite (1/4): framework + core correctness oracles #117187#discussion_r3981703300]. The grouping-permutation and DISTINCT oracles still screen windows only in the outer projection. An inner row_number over an unordered window can legitimately assign different values across plans; repeating the reference does not establish equivalence of the variant. Apply recursive window screening, including WITH definitions. The shared helper also omits select.with, leaving that carrier uncovered in its callers.

  • Skip-index coverage still counts inapplicable predicates. QueryOracleChecker.cpp:2798–2818, 2873 [dismissed by author -- https://github.com/AST fuzzer oracle suite (1/4): framework + core correctness oracles #117187#discussion_r3927282559]. Identifier overlap still admits WHERE cityHash64(x) = 1 for a minmax index on x, although the index cannot prune that predicate. Require applicability or execution evidence before counting this as skip-index coverage.

  • Four new registrations have no committed activation tests. OracleRegistry.cpp:97–101 [dismissed by author -- https://github.com/AST fuzzer oracle suite (1/4): framework + core correctness oracles #117187#discussion_r3971358657]. No tests reference the dedicated events for PREWHERE, skip-index, setting-flip, or codec checks. Their gates and setup swallow execution errors, so a permanently skipped oracle can pass CI. Add minimal tests proving each registration performs a comparison.

  • Fixture cleanup is not assured for partial grants. OracleFixture.cpp:47–74, 84–91 [dismissed by author -- https://github.com/AST fuzzer oracle suite (1/4): framework + core correctness oracles #117187#discussion_r4433362380]. A caller with CREATE TABLE but without INSERT/DROP TABLE passes the gate, creates both tables, then fails insertion and cleanup. Every eligible run can leave persistent scratch tables. Check privileges for the complete lifecycle before creating either table, with a partial-grant regression case.

  • Encoder failures still disappear during seeding. QueryOracleChecker.cpp:3058 [dismissed by author -- https://github.com/AST fuzzer oracle suite (1/4): framework + core correctness oracles #117187#discussion_r4173187947]. A successful plain insert followed by a coded-side compression failure still returns false through fixture.execute, discarding the oracle and its reproduction tables. Observe seed outcomes too, distinguishing codec defects from environmental failures.

💡 Nits

  • The Build/Testing/Packaging Improvement category fits, but its required entry is replaced with “Not for changelog.” Suggested entry: “Extend the server-side AST fuzzer with a shared correctness-oracle framework and checks for grouping key order, DISTINCT, PREWHERE, skip indexes, optimizer settings, and compression codecs.” Alternatively, select Not for changelog.
  • Dedicated CI already reports clang-tidy failures for missing [[nodiscard]] annotations and the redundant pin-name conversion: shard 1/4, shard 4/4. No inline findings duplicate those diagnostics.
Tests
  • ⚠️ The current-head functional and sanitizer jobs were skipped; no ClickHouse binary is available in this review job. The conclusions above are from source tracing, not executed reproductions. Successful targeted CI results are needed for matcher projections, changed-source suppression, recursive windows, fixture permissions, and codec error classification.
  • ⚠️ The claimed soak validation does not demonstrate safety after removing the parallel teardown guards. Provide a focused sanitizer regression or retain those guards.
Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3f43d5b92 with master 802411f22 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

5 object files changed (+319.54 KiB total), 6 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/QueryOracles/OracleExec.cpp.o new 113.52 KiB +113.52 KiB
src/CMakeFiles/dbms.dir/Interpreters/QueryOracles/OracleGate.cpp.o new 45.57 KiB +45.57 KiB
src/CMakeFiles/dbms.dir/Interpreters/QueryOracles/OracleFixture.cpp.o new 44.23 KiB +44.23 KiB
src/CMakeFiles/dbms.dir/Interpreters/QueryOracles/OracleRegistry.cpp.o new 41.03 KiB +41.03 KiB
src/CMakeFiles/dbms.dir/Interpreters/QueryOracles/OracleSettings.cpp.o new 40.50 KiB +40.50 KiB

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

15 translation units recompiled, 44 s compile time in total, 9 of them have a recent master baseline.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 14.00 MiB 14.12 MiB +128.00 KiB (+0.89%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 14.00 MiB 14.12 MiB +128.00 KiB (+0.89%)

Job report

qoega and others added 16 commits September 1, 2026 07:41
…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]>
@qoega
qoega force-pushed the oracle-pinned-settings branch from 7186f18 to ef47d35 Compare September 1, 2026 08:35
@qoega qoega changed the title AST fuzzer oracle: introduce oraclePinnedSettings (single source of truth) + DDL-enablement pins AST fuzzer oracle suite (1/4): framework + core correctness oracles Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Sep 1, 2026
qoega and others added 2 commits September 1, 2026 09:02
…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]>
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
@PedroTadim

Copy link
Copy Markdown
Member

Quick review:

  • The 05141_oracle_skips_aggregate_aliases and 05140_oracle_skips_approx_top_k tests fail on this PR.
  • Nothing calls GateRelax / hasRelax, referencesTableMatching, hasTotalOrderKey, tryExecuteRows or isPinnedByOracleContext
  • Check the bot comments

# Conflicts:
#	src/Interpreters/QueryOracleChecker.cpp
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
alexey-milovidov pushed a commit to ylw510/ClickHouse that referenced this pull request Nov 2, 2026
…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]>
@qoega

qoega commented Nov 4, 2026

Copy link
Copy Markdown
Member Author

Pushed 3f8786906fd to restore the thread-group switch that was dropped during the OracleExec/OracleCompare extraction.

Root cause. Commit d2ea91b8acf ("Run AST fuzzer oracle oracle sub-queries on a thread group of their own context") attached each oracle sub-query in QueryOracleChecker::{executeAndCollectSortedRows, executeScalar, executeWithSettings} to ThreadGroup::createForQuery(oracle_context) via a nested ThreadGroupSwitcher(..., allow_existing_group=true). That made code which reads the query context from the thread (distributed-plan stage tasks and ReadFromDistributedPlanSource) see the oracle's pins — max_rows_to_read = 0, max_threads = 1, the per-variant DQP settings — rather than the fuzzed query's max_rows_to_read = 100000 + read_overflow_mode = break cap that executeQuery sets on the fuzz context (src/Interpreters/executeQuery.cpp:3871). The regression test 05339_ast_fuzzer_oracle_distributed_plan_read_cap.sh was added in the same commit as the guard.

What broke it. The follow-up refactor 0c440484856 ("AST fuzzer oracle: extract the OracleExec / OracleCompare execution+comparison layer") moved the three methods into src/Interpreters/QueryOracles/OracleExec.cpp as OracleExec::{executeRows, executeScalar, executeStatement} and replaced the originals with one-line forwarders — but did not carry the switchToThreadGroupOf call across, and the helper was dropped entirely. git grep 'ThreadGroup\|switchToThreadGroupOf' -- src/Interpreters/QueryOracles/ src/Interpreters/QueryOracleChecker.cpp on the branch tip returns no hits. make_distributed_plan = 1 stage tasks then inherit the fuzz context's 100 k cap again; trivial-count reference returns 900 k rows while the DQP variant stops at ~100 k. That is the exact 15/10/12-per-retry oracle mismatch 05339 flags in the four failing stateless jobs.

The fix. Reinstates the helper in OracleExec.cpp (anonymous namespace, verbatim from d2ea91b8acf) and calls auto thread_group_switcher = switchToThreadGroupOf(oracle_context); at the top of executeRows, executeScalar and executeStatement, right after the overlay setSetting loop and before executeQuery runs. No code-shape changes elsewhere. 12 insertions, 1 file.

API-drift check against the current tree:

  • ThreadGroup::createForQuery(ContextPtr) — unchanged (src/Common/ThreadStatus.h:143).
  • ThreadGroupSwitcher(ThreadGroupPtr, ThreadName, bool allow_existing_group = false) — unchanged (src/Common/ThreadGroupSwitcher.h:32).
  • ThreadName::AST_FUZZER → "ASTFuzzer" — unchanged (src/Common/setThreadName.h:17).

05339 is correctly catching its own regression — left in place as the guard.

@PedroTadim

Copy link
Copy Markdown
Member

🕵️ Thanks for 3f87869, that should fix 05339 and the false TLP WHERE/TLP Aggregate mismatches on the previous head; CI has not run on it yet.

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 origin/master, the PR head no longer has:

  • the allow_dynamic_type_in_join_keys = false pin in oraclePinnedSettings;
  • the is_order_dependent check from the function factory for aggregates such as groupArraySample;
  • the join_default_strictness resolution and the SEMI guard in the join screen;
  • the ASTColumnsApplyTransformer lambda and function-name traversal in the determinism screen;
  • the aggregate parameters copied onto the generated -Merge call (uniqUpTo(10) becomes uniqUpToMerge with the default 5);
  • the nested-settings, join and totals screens on view bodies, defaults and row policies.

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: GateRelax/hasRelax, hasTotalOrderKey, tryExecuteRows, isPinnedByOracleContext and referencesTableMatching (outside its own recursion) are still unused. Please either use them in this PR or move them to the PR of the series that does.

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]>
@qoega

qoega commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Pushed b237f757510 ("AST fuzzer oracle: restore screens dropped by the OracleExec extraction"). Covers your 11-05 12:02 list — mapping the restored screens to your points:

Your item Commit bullet
allow_dynamic_type_in_join_keys = false pin in oraclePinnedSettings oraclePinnedSettings [P1]
is_order_dependent check for groupArraySample-class aggregates isOracleUnsafeFunctionName reads AggregateFunctionFactory::tryGetProperties(...).is_order_dependent (excl. window functions); groupArraySample, groupFormat, flameGraph, hierarchicalKMeans screened [P1]
join_default_strictness resolution + SEMI guard hasNonDeterministicJoinAnywhere resolves Unspecified → default strictness and screens Semi alongside Asof/Any/RightAny [P2]
aggregate parameters on generated -Merge call checkTLPAggregate clones agg_func->parameters so uniqUpTo(10)(x) merges with its threshold [P2]
nested-settings/join/totals screens on view bodies / defaults / row policies referencesUnscreenedDefinitionAnywhere applies join + non-strippable-inline-setting + nested-thread-setting + WITH TOTALS screens to stored definitions [P1]

One question — your ASTColumnsApplyTransformer lambda + function-name traversal in the determinism screen item isn't a dedicated bullet in the commit message. The identifier is present in src/Interpreters/QueryOracleChecker.cpp at the tip, and the is_order_dependent-from-registration change touches the surrounding traversal, so my read is that the lambda lives on through the rewrite. Is that sufficient, or did you have a separate lambda site in mind that should be its own restore? Happy to send a follow-up if there's a specific spot that regressed.

On the still-unused set from your earlier review — GateRelax/hasRelax, hasTotalOrderKey, tryExecuteRows, isPinnedByOracleContext, referencesTableMatching outside its own recursion — we'll decide use-here vs move-to-sibling-PR in the next push and flag the choice here.

CI retriggered on the restore commit.

@clickhouse-gh clickhouse-gh Bot added comp-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... and removed comp-testing Test content only (no production code). labels Nov 19, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@qoega resolve the conversations when they are done

qoega and others added 9 commits November 24, 2026 17:01
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`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment on lines +76 to +83
/// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... pr-build Pull request with build/testing/packaging improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants