Skip to content

AST fuzzer oracle: skip a mismatch only if the data changed between the reads - #119465

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:oracle-reference-stability-guard
Nov 6, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:oracle-reference-stability-guard

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117006 (comment)

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

AST fuzzer (amd_release, oracle) reported a TLP WHERE oracle mismatch, 2000 reference vs 3000
partitioned rows over a Buffer on a SummingMergeTree
(report);
@ alexey-milovidov asked for a separate fix PR
(comment). The TLP
arms are exhaustive, so +1000 rows means the data changed between the reads.

Each oracle compares separate executeQuery reads, so a merge, an insert or a mutation committed
between them makes it compare different data and blame the rewrite.

Before each query an oracle executes, the active parts of every MergeTree table that query reads
are recorded (also through views, and behind the proxy of a lazy_load_tables database). CTE
references are first replaced by their definitions and WITH clauses dropped, in view bodies too,
so no table is counted for a CTE named like it, an unused WITH alias, a clause the oracle strips
such as ORDER BY, or a name resolving to another table expression's alias (FROM s AS x JOIN x AS y). On a mismatch the oracle is skipped only if one of those lists changed. A table read only
inside an APPLY lambda, through a WITH alias, or as a bare IN t operand (it may name a column)
is not recorded, so a change there is reported, as on master. Parts are immutable and a part name is
never reused, so an unchanged list means all reads saw the same data: the mismatch is reported, also
when a re-run would not reproduce it (for example a non-deterministic result from JIT compilation).
The ASTFuzzerOracleMismatches increment moves into run_oracle, so a skipped mismatch is not
counted. Other engines, and the existing re-run check of Subquery wrap, are unchanged.

No test ships: arming it needs a server-global PAUSEABLE failpoint held across a fuzz loop.
Validated locally in both directions instead (below).

Local validation

infinite_sleep is a PAUSEABLE failpoint inside FunctionSleep::execute, so sleep(0) pauses a
read, and sleep is not screened by the oracle. Table s (k UInt32, v UInt32, w UInt32 ALIAS v + 1) ENGINE = MergeTree ORDER BY k, merges stopped, seed SELECT sleep(0), sleep(0), sleep(0), k, w FROM s WHERE k = 5 with --ast_fuzzer_runs=300 --ast_fuzzer_oracle=1 --ast_fuzzer_any_query=0. At every
pause the driver either inserts one part, or runs ALTER TABLE s MODIFY COLUMN w UInt32 ALIAS v + N
(the result changes, the part names do not), then SYSTEM NOTIFY FAILPOINT infinite_sleep.

binary INSERT at every pause ALTER at every pause
master Code: 906 TLP WHERE oracle mismatch, first attempt Code: 906, first attempt
previous version of this PR (re-run) not run no mismatch in 221 pauses
this PR skipped (logged), no Code: 906 Code: 906

Also skipped with this PR and reported without it: the same INSERT race on a table of a
lazy_load_tables = 1 database. The ALTER control is reported in the lazy_load_tables database
too, and also while an unread table t gains a part at every pause, for a CTE t over s, a
WITH [5] AS t in k IN t, an unused CTE over t, an unused WITH (SELECT count() FROM t) AS c,
ORDER BY (SELECT count() FROM t), a CTE t read inside an APPLY lambda, an unused CTE over t
inside a view, k IN t where t is also a column or an alias, and FROM s AS t JOIN t AS y
(previous versions skipped these). An INSERT into t read through
WITH t AS (SELECT ... FROM t) or under a nested CTE named t is skipped, and so is one into s
read as FROM s WHERE k IN (SELECT k FROM t AS s).

The in-tree AST fuzzer tests pass with random settings: 03823, 03833, 04305, 04344, 04658,
05227, 05288, 05338 5/5 each, 05339 1/1.


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

Version info

  • Merged into: 26.11.1.1577-master (included in 26.11 and later)

An oracle validates a fuzzed SELECT by executing a reference query and a
metamorphic rewrite of it as two separate executeQuery calls, then comparing
sorted row sets. Its premise is that both sides read the same relation.
makeOracleContext pins threads, caps and overflow modes, so a plan difference
is excluded, but nothing excluded a relation difference between two
consecutive executions. When the row set is a function of physical part layout
rather than of contents, the two reads observe different snapshots and the
oracle attributes the difference to the rewrite: a merge-collapsing engine
read without FINAL (SummingMergeTree, AggregatingMergeTree,
ReplacingMergeTree, CollapsingMergeTree), a concurrent INSERT into a plain
MergeTree, or an AggregateFunction state column with non-canonical
serialization.

Reported as a TLP WHERE mismatch on a Buffer over a SummingMergeTree, 2000
reference rows against 3000 partitioned rows. The TLP arms (p / NOT p /
p IS NULL) are exhaustive over every value the predicate can take, so
predicate evaluation can only move a row between arms, never add one; +1000
rows is exactly one insert unit, so the relation changed under the oracle.

checkSubqueryWrap was fixed for this class in 59efd8b by re-executing
the reference once on the mismatch path and skipping when it is not stable.
Eight other oracles compared without that guard. Generalize it into one shared
helper, probe each site with the same collector its original read used
(sorted rows, sorted unique rows for TLP GROUP BY, a scalar Field for NoREC),
and refold the inline version onto the helper so the invariant has one shape.
The probe precedes ASTFuzzerOracleMismatches at all nine sites, so a flaky
query no longer bumps the mismatch counter. std::nullopt counts as not
reproduced, and a probe that throws degrades to a skipped oracle, so every
path fails close. checkIdentityWhere's comparison lambda returns bool because
its three variants share one reference vector: an unreproducible reference
disqualifies all three, and a bare return inside a void lambda would have
returned from the lambda alone.

An engine screen was considered and rejected: it would stop checking those
engines altogether, and it cannot see the concurrent-INSERT or
AggregateFunction-state cases. This costs one extra execution on the mismatch
path only.

The trade, which the precedent already accepted, is that a wrong-results bug
that is itself non-deterministic now makes the oracle skip rather than report.
With no reproducible reference there is nothing to compare against. Subquery
wrap has carried this guard since 2026-07-13 and still reported 9 mismatches
in the last 30 days, the sampled ones genuine.

Validated locally in both directions with a failpoint rendezvous: pausing a
read of a merges-stopped SummingMergeTree at infinite_sleep and appending one
part per pause reproduces the reported message on the first attempt in 5 of 5
runs without the guard, and produces no mismatch in any run with it, at 10x to
25x the growth-event count that armed the unguarded binary, while
ASTFuzzerOracleChecks advances from 12 to 568. A genuine Subquery wrap
mismatch taken from CI, whose reference reads no storage, still throws with
the guard in place.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold against the code, then adjudicated. Nothing structural: nine mismatch sites, nine
probes, each re-reading with the same collector as the read it re-executes, all placed before the
mismatch counter.

⚠️ Asked for direct proof that a guarded oracle reaches the re-read and skips because the
reference changed, rather than never being reached. Answered by the A/B in the description rather
than by a test: unguarded, the reported TLP WHERE message appears on the first attempt in 5 of 5
runs; guarded, none, while ASTFuzzerOracleChecks advances 12 to 568; and a genuine Subquery wrap
mismatch whose reference reads no storage still throws. No existing counter separates "skipped by
the guard" from "passed", since ASTFuzzerOracleChecks increments before the comparison at all nine
sites.

💡 A dedicated unstable-reference skip counter was suggested and not taken: it would make the skip
observable but not the failpoint rendezvous deterministic, so a shipped test would hinge on winning
a race inside the mutation loop. Happy to add both if you would rather have them in-tree.

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [98dd7a6]

Summary: ✅


AI Review

Summary

The change suppresses AST-fuzzer oracle mismatches when recorded MergeTree part lists change, preserving reports of unstable wrong results when those lists stay constant. Request changes: dependency attribution can still hide genuine mismatches, while row-policy dependencies, pending mutations and committed visibility can change results without changing the recorded parts. Reviewed head: 98dd7a6374c9694a70ceb3e6965d5ae4385ac4f6.

Findings

⚠️ Majors

  • QueryOracleChecker.cpp:1194: Dependency expansion must preserve the analyzer's name precedence. ApplyWithSubqueryVisitor substitutes CTEs before considering columns or table aliases. With WITH arr AS (SELECT k FROM t) SELECT k FROM s WHERE k IN arr, a column s.arr wins during execution, but dependency collection records unread t. Likewise, WITH x AS (SELECT k FROM t) SELECT x.k FROM s AS x ALL INNER JOIN x AS y ON x.k = y.k WHERE x.k = 1 reads s twice through the alias, but collection substitutes the unused CTE. Changes to unrelated t can suppress genuine mismatches. Preserve resolved bindings or omit dependencies whose binding cannot be established. These are remaining instances of the existing CTE and IN-operand findings; the ordinary CTE, removed-clause, view-body and bare-operand cases have been addressed.

  • QueryOracleChecker.cpp:1715: Cached scalar values must not count as fresh table reads. makeOracleContext inherits ContextData::scalars, and QueryAnalyzer::evaluateScalarSubqueryIfNeeded reuses matching entries. After the fuzzed query SELECT k, (SELECT count() FROM t) FROM s WHERE k = 1, the Identity WHERE comparisons can use the same cached count without reading t. Collection still records t, so an insert or merge there can suppress a genuine mismatch over unchanged inputs. Account for scalar-cache hits while preserving dependencies for fresh and correlated subqueries. New inline finding.

  • QueryOracleChecker.cpp:1242: The fingerprint must include effective row-policy dependencies. Collection follows view definitions but never policy expressions, although the existing screening permits deterministic policy subqueries. A policy on s using k IN (SELECT k FROM allowed) can expose different rows after an insert into allowed, while only unchanged s is recorded. The resulting legitimate drift is reported as an oracle mismatch. Include transitive policy dependencies or reject comparisons that depend on them. Existing finding.

  • QueryOracleChecker.cpp:1237: Active parts do not capture pending mutations applied during reads. makeOracleContext retains apply_mutations_on_fly. A pending ALTER TABLE s UPDATE registered between reads changes returned values before replacement parts are materialized, leaving both regular and patch part names unchanged. MergeTreeData::createStorageSnapshot captures mutation state separately for this reason. Include that state or exclude this mode. Existing finding.

  • QueryOracleChecker.cpp:1239: Active parts do not capture committed visibility for UNIQUE KEY tables. UniqueKeyTxnCommit::InsertCommit::publish activates an overwrite's part before its transaction commits. A reference read before the commit and a variant after it return different values with identical active-part names; MergeTreeData::createStorageSnapshot uses a separate visibility snapshot to distinguish them. Track committed visibility or exclude these tables. The existing 04196_unique_key_read_skips_an_uncommitted_part.sh demonstrates this transition. Existing finding.

Missing context / blind spots
  • ⚠️ No local ClickHouse executable or build was available for additional runtime probes. The remaining cases were verified by tracing the collector, analyzer resolution, context caches and storage snapshots; focused runtime results would close this validation gap.
Tests
  • ⚠️ Extend the focused validation to prove that a genuine mismatch remains visible while only an unread CTE source or a cached scalar's source changes.
  • ⚠️ Validate drift through a row-policy subquery, a pending mutation with materialization stopped, and a UNIQUE KEY commit between reads. These require more than the ordinary insert and metadata-change controls described in the PR; a reproducible validation driver is sufficient for this developer-tool change.
Final Verdict

⚠️ Request changes. Correct dependency attribution, account for the missing read-state components or explicitly exclude their modes, and provide focused validation of the remaining cases.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @qoega, could you review this? It generalizes the reference-stability guard you added to checkSubqueryWrap in 59efd8be4ca73 to the other eight oracles, so a mismatch is reported only when a second execution of the reference read reproduces it.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 11, 2026
@qoega qoega self-assigned this Sep 11, 2026
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 98dd7a637 with master 2ad32ae94 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 074719710; 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

4 object files changed (+78.40 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/QueryOracleChecker.cpp.o 643.79 KiB 720.37 KiB +76.58 KiB (+11.90%)

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

8 translation units recompiled, 27 s compile time in total, 7 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Interpreters/QueryOracleChecker.cpp: 10.6 s

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9e6f653

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 2/6) / test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore flaky: the test's own NoTrashChecker asserts at test_cancel_backup.py:414 on an error its expect list does not cover; 7 occurrences across 7 distinct pull requests plus one master run in the last 30 days, and this diff is confined to the AST fuzzer oracle #119448 (mine, open)
Mergeable Check, PR aggregators reflecting the row above #119448 (mine, open)

Session id: cron:our-pr-ci-monitor:20260911-203047

@groeneai

Copy link
Copy Markdown
Collaborator Author

This PR also suppresses a false positive that is currently red on true master. Measured today.

04256_04250_ast_fuzzer_oracle_tlp_aggregate fails in Stateless tests (amd_tsan, s3 storage, sequential, 1/2) at master 28fd758670f1 (2026-09-14 15:55:56Z) with TLP Aggregate oracle mismatch on approx_top_k. Repro: the test's own fixture with ast_fuzzer_runs = 1000.

build Code: 906 hits
master 5/5
master + this PR 0/5
master + this PR, referenceReproduces stubbed to return true 5/5

The third arm attributes the suppression to that guard specifically rather than to any other effect of the patch. On the patched binary the same query still reports ASTFuzzerOracleChecks 27 / ASTFuzzerOracleMismatches 0, so the oracles keep running and only the false mismatch is gone.

Why the guard is a sound gate for this family and not a lucky one: approx_top_k is not reproducible even inside a single process. Eight consecutive executions of the reference read in one clickhouse local returned eight distinct results, on one active part, 200 rows, all values distinct, and likewise 8/8 distinct at max_threads 1, 4 and 16.

The same aggregate also trips Identity WHERE (NOT(NOT p)), which this PR patches too.

I considered the name-based alternative (skip aggregates the factory declares is_order_dependent) and am not opening it. Over 30 days of CI data, of the order-dependent aggregates the oracle's static list does not name, only approx_top_* has any observed mismatch at all, 0 rows for every other, so it would fix nothing this PR does not.

@qoega

qoega commented Sep 17, 2026

Copy link
Copy Markdown
Member

@groeneai update pr

@groeneai

groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

Updated. I merged current master (718e603a5d63) into oracle-reference-stability-guard; the new head is f287a41279c3.

The merge was clean and the fix content is unchanged, so the approval still applies to exactly what was reviewed: the PR diff against master is byte-identical to the approved head (same git patch-id, d2761557f0e3), still +51/-16 in src/Interpreters/QueryOracleChecker.{h,cpp}. Master had touched that file 11 times since my base, so I re-checked coverage after the merge: all 9 ASTFuzzerOracleMismatches sites are still gated, and the translation unit compiles clean on the new head.

The only red on the previous head was Integration tests (amd_tsan, 2/6) / test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore, which is not this diff: CIDB has 9 failures of that test in the last 30 days on 9 distinct heads, 6 of them unrelated pull requests, 2 true-master runs, and the one on my previous head; the most recent was 2026-09-16 03:59 UTC on an unrelated pull request. CI is running now on f287a41279c3, and I will post the finish ledger for that head here once it completes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f287a41

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 1/8) / test_max_bytes_ratio_before_external_distinct[server] flaky; 4 carriers over 30 days, 0 on true master, first seen 2026-09-03, and 3 distinct carriers on 2026-09-17 alone. This diff only touches the AST fuzzer oracle's reference-read guard, which has no path to the max_bytes_ratio_before_external_* server settings. a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Mergeable Check, PR aggregators reflecting the row above, no independent failure a fix task is created (the same one; these clear when the row above clears)

Everything else on this head is green: 176 of 177 checks passed or skipped, including all
7 AST fuzzer flavours, all 4 BuzzHouse flavours, Build profile diff and the full build matrix.

Session id: cron:our-pr-ci-monitor:20260917-113202

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for test_max_bytes_ratio_before_external_distinct[server] created: #120751

@groeneai groeneai mentioned this pull request Sep 21, 2026
1 task done
@groeneai

Copy link
Copy Markdown
Collaborator Author

Two more carriers for this guard's class, and one of them is on true master. Measured today.

Since 05141_oracle_skips_aggregate_aliases re-landed (2026-09-19 03:24:48Z), CIDB holds 5
AST Fuzzer oracle mismatch% FAIL rows. Four come from that one fixture (by log_comment),
across two oracles and both architectures:

when ref job oracle
2026-09-21 10:18 #121244 edcccb669b1b Stateless (arm_binary, sequential) TLP Aggregate
2026-09-23 13:26 #120973 d822bd8930b8 Stateless (amd_debug, sequential) Identity WHERE (NOT(NOT p))
2026-09-24 04:27 master f61f67b35e7c Stateless (arm_release, sequential) Identity WHERE (NOT(NOT p))
2026-09-25 08:53 #115048 91bc6c882e8e Stateless (arm_binary, sequential) TLP Aggregate

The fifth is 05097 on #112355, which #121897 covers. These rows are job level: log_parser.py
lifts them out of the server log, so the fixture's own result stays OK and the red lands on a
contributor who touched nothing nearby.

I cannot yet say whether these four are the unreproducible-reference class this PR guards, and I
am not claiming they are. What I ruled out:

  • Not the aggregates. groupBitAnd/groupBitOr/groupBitXor are associative and commutative
    with correct neutral elements (AggregateFunctionBitwise.cpp: -1 for AND, 0 for OR/XOR,
    mergeImpl is update), so the deny-list is right to omit them.
  • Not a randomized setting. The 4-way intersection of the failing runs' non-default settings is
    exactly the clickhouse-test baseline: no randomized setting survives it, and
    use_query_condition_cache, use_query_cache, optimize_move_to_prewhere and
    query_plan_optimize_prewhere sit at default in all four.
  • Not reproducible locally. On a debug master build both pairs agree at default settings and
    again under a full replay of the 2026-09-21 run's non-default settings.

So this PR is also the discriminator for the family: once it is in, a surviving report proves the
disagreement is stable rather than a read that does not reproduce.

One aside I hit while triaging, unrelated to this diff and not a request to change it: of the nine
mismatch messages, only checkTLPWhere prints the differing rows. The other eight print the two
queries and the row counts alone, so a CIDB occurrence of those cannot be diagnosed without a
local reproduction, which is what stopped me above.

…he reads

The previous version of this change re-ran the reference on a mismatch and
skipped when the re-run differed. A re-run that differs does not prove that
the data changed: a non-deterministic wrong result (for example from JIT
compilation) also differs between runs, and that version hid it.

Instead, each oracle records every MergeTree table the query reads, including
through views and `IN t`, with its active parts (regular and patch), before
its first read, and on a mismatch skips only when that list is different
afterwards. Parts are immutable and a part name is never reused, so an
unchanged list means every read saw the same data, and the mismatch is
reported even when a re-run would not reproduce it. A merge, an insert or a
mutation committed between the reads changes the list.

The check and the `ASTFuzzerOracleMismatches` increment move into
`run_oracle`, so the counter does not count a skipped mismatch.
`checkSubqueryWrap` keeps its existing re-run check.

Validated locally with a pause on `infinite_sleep` inside the oracle's reads:
- an INSERT at every pause (a new part): master reports a TLP WHERE oracle
  mismatch on the first attempt; with this change the mismatch is logged as
  skipped and no Code: 906 is thrown while the oracles keep running;
- an ALTER of the ALIAS column the query reads at every pause (the result
  changes, the parts do not): reported by master and by this change, and
  not reported by the previous version of this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title AST fuzzer oracle: do not report a mismatch when the reference read is not reproducible AST fuzzer oracle: skip a mismatch only if the data changed between the reads Oct 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 731a1e1: the re-run is gone, and a mismatch is skipped only if the active parts of a MergeTree table the query reads changed between the reads. With a failpoint pause inside the oracle's reads, an ALTER of the ALIAS column the query reads (the result changes, the parts do not) is now reported; the previous version of this PR hid it in all 221 pauses. An INSERT at every pause is still skipped. The description has the details.

groeneai and others added 3 commits October 19, 2026 21:11
`ASTColumnsApplyTransformer` keeps `lambda` and `parameters` outside
`children`. Every recursive screen in this file now walks them through
`forEachChild` (master, ClickHouse#122055); `collectReadParts` still walked
`children` only, so a table read inside an `APPLY` lambda, e.g.
`SELECT * APPLY (x -> (SELECT count() FROM t)) FROM s`, was missing from
the part snapshot and a mismatch caused by a new part of `t` was
reported instead of skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
In a database with `lazy_load_tables = 1` the catalog hands out a
`StorageTableProxy` for a `MergeTree` table for its whole life, so the
direct `dynamic_cast<const MergeTreeData *>` never matched: no parts were
recorded and a mismatch caused by an insert into such a table was
reported. `castStorage<MergeTreeData>(storage, DeferredTable::Load)` looks
through the proxy; `Load` because the oracle reads the table anyway.
Required by the `storage_casts` style check that master added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +1175 to +1176
const StorageID resolved = context->tryResolveStorageID(StorageID{table_id->getDatabaseName(), table_id->shortName()});
if (auto storage = resolved ? DatabaseCatalog::instance().tryGetTable(resolved, context) : nullptr)

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.

⚠️ Resolve CTE bindings before attributing part changes

This resolves every table-shaped identifier through the catalog, even when the query resolves it to a CTE. For example, with a physical MergeTree table t, WITH t AS (SELECT 1 AS k) SELECT k FROM t WHERE k = 1 reads only the constant CTE, but this collector records the physical table's parts. If that unrelated table merges while an oracle finds a genuine mismatch, parts_after != parts_before suppresses it despite the oracle's input being unchanged. Unused CTE bodies and subqueries in the ORDER BY removed by stripOrderAndLimit can similarly add unrelated dependencies.

Collect the dependencies of the queries actually executed, with scope-aware CTE resolution, rather than treating every identifier in the original AST as a storage read. Please cover a CTE shadowing an existing table when validating that genuine mismatches remain visible.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in db4c1fc: the collector now walks a copy of the query in which ApplyWithSubqueryVisitor replaced each CTE reference (and each IN operand naming a WITH alias) by its definition, so a CTE named like a table, or an unused CTE, no longer counts that table.

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.

The ordinary CTE case is fixed, but the original attribution issue remains for CTE references inside APPLY. At src/Interpreters/QueryOracleChecker.cpp:1231, ApplyWithSubqueryVisitor walks only children; an ASTColumnsApplyTransformer keeps its lambda outside that list. For example, with physical MergeTree tables s and t:

WITH t AS (SELECT k FROM s)
SELECT * APPLY (x -> (SELECT count() FROM t))
FROM s WHERE k = 1

The query reads only s, but expansion leaves the lambda's FROM t untouched. removeWithElements then removes the outer CTE, and the collector's forEachChild reaches that identifier and records the unrelated physical t. An insert into that table can still suppress a genuine mismatch. The expansion needs to reach hidden APPLY members with the enclosing bindings intact.

The removed-ORDER BY case from the original comment also remains: src/Interpreters/QueryOracleChecker.cpp:2907 collects from the original query, so SELECT k FROM s WHERE k = 1 ORDER BY (SELECT count() FROM t) records t even for the TLP comparisons that delete that clause. Those dependencies need to come from the queries the individual oracle executes.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in ed5e331: each executor now records the parts of the tables the query it runs reads, so a clause an oracle strips no longer counts, and APPLY members, which the WITH expansion does not reach, are not walked.

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.

The removed-ORDER BY case is fixed, but unused CTE bodies still add unread tables when they are inside a view. At src/Interpreters/QueryOracleChecker.cpp:1200, the collector descends directly into the stored view AST, bypassing expandWithElements and its removeWithClauses step. For example, with MergeTree tables s and t:

CREATE VIEW v SQL SECURITY INVOKER AS
WITH unused AS (SELECT k FROM t)
SELECT k, w FROM s;

SELECT k, w FROM v WHERE k = 1;

This reads only s, but the collector visits the unused definition and records t. An insert into t can still suppress a genuine mismatch over unchanged s. InterpreterCreateQuery expands CTE references without removing the WITH list, and StorageView stores that list in inner_query, so creation does not eliminate this case. Apply the dependency normalization to each reached view body as well.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 98dd7a6: view bodies now get the same WITH expansion before their tables are recorded.

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.

The view-body case is fixed, but the original attribution issue remains when a table alias shadows a CTE. At src/Interpreters/QueryOracleChecker.cpp:1194, ApplyWithSubqueryVisitor substitutes CTEs before getTableExpressionAliases runs. With MergeTree tables s and t:

WITH x AS (SELECT k FROM t)
SELECT x.k
FROM s AS x ALL INNER JOIN x AS y ON x.k = y.k
WHERE x.k = 1

QueryAnalyzer::tryResolveIdentifier resolves the second source through the table alias x before consulting CTEs, so both sides read s. The visitor instead replaces that source with the CTE body, and the collector records the unread t. An insert into t can therefore still suppress a genuine mismatch over unchanged s. The alias filter runs after the identifier has already become a subquery, so it cannot correct this binding. Dependency expansion needs to preserve the analyzer's alias-before-CTE precedence.

Comment thread src/Interpreters/QueryOracleChecker.cpp Outdated
Comment on lines +1186 to +1189
else if (storage->getName() == "View")
{
const auto metadata = storage->getInMemoryMetadataPtr(context, /* bypass_metadata_cache = */ false);
collectReadParts(metadata->getSelectQuery().inner_query, context, parts, depth + 1);

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.

⚠️ Include tables read by row policies in the snapshot

Only view bodies are followed here; a table's effective row-policy expression is never visited. The earlier referencesUnscreenedDefinitionAnywhere explicitly permits deterministic policy subqueries, so these queries reach the oracle. For example, give s a policy USING k IN (SELECT k FROM allowed) with both tables using MergeTree, then run SELECT k FROM s WHERE k = 1. An insert into allowed between the reference and partitioned reads can change which rows of s are visible, but the collector records only s, whose parts stay unchanged. The resulting legitimate read drift is still reported as AST_FUZZER_ORACLE_MISMATCH.

Traverse effective policy expressions for every reached table/view, including their transitive table dependencies, and include this case in the validation.

Comment on lines +1181 to +1184
for (const auto & part : merge_tree->getDataPartsVectorForInternalUsage(
{MergeTreeData::DataPartState::Active},
{MergeTreeData::DataPartKind::Regular, MergeTreeData::DataPartKind::Patch}))
parts.push_back(part->name);

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.

⚠️ Account for pending on-the-fly mutations

Unchanged part names do not imply unchanged read data when the session has apply_mutations_on_fly = 1; makeOracleContext preserves that setting. With merges stopped, another session can register an ALTER TABLE s UPDATE v = 2 WHERE k = 1 between the two oracle reads. The second read applies the newly pending mutation while the first did not, yet both snapshots here contain exactly the same regular and patch part names. This still produces a false mismatch. MergeTreeData::createStorageSnapshot captures a separate mutations snapshot precisely because the part list does not describe this state; the existing 03047_on_fly_mutations_basics.sh also exercises changed results without materializing new parts.

Include the applicable pending mutation state in the fingerprint, or explicitly skip oracle comparisons in this mode, and validate a mutation registered between reads before its replacement part is committed.

…ITH elements

With a physical `MergeTree` table `t`, `WITH t AS (SELECT k, w FROM s) SELECT ... FROM t`
reads only `s`, but `collectReadParts` resolved the identifier `t` through the catalog and
recorded the physical table's parts. A part change on that unread table then skipped a mismatch
whose reads all saw the same data. The same over-recording happened for `k IN t` naming a
`WITH` literal alias and for the body of an unused CTE.

`check` now walks a copy of the query in which `ApplyWithGlobalVisitor` (with
`enable_global_with_statement`) and `ApplyWithSubqueryVisitor` replaced each CTE reference and
each `IN` operand naming a `WITH` alias by its definition, the substitution the query's own
`WITH` processing does, so the scoping rules (`WITH t AS (SELECT * FROM t)` reads the physical
`t`, a nested select sees enclosing names only with `enable_global_with_statement`, a subquery's
own `SETTINGS`) are the engine's. The then unused `WITH` elements are dropped from the copy. A
`TOO_BIG_AST` from the expansion stops the checks for that query, like any other error of
`check`. `collectReadParts` is unchanged.

Validated with a failpoint pause inside the oracle's reads (`infinite_sleep`, seeds with
`sleep(0)`, `--ast_fuzzer_runs=300 --ast_fuzzer_oracle=1`):
- an ALIAS ALTER of `s.w` (result changes, parts do not) plus an insert into the physical `t` at
  every pause, with `t` a CTE over `s`, a `WITH [5] AS t` literal in `k IN t`, or an unused CTE
  reading `t`: the previous head skipped them (0 reported over 890, 734 and 541 pauses); this
  commit reports `Code: 906` within the first two attempts.
- an insert at every pause into the table the query really reads, through the CTE body, a
  self-referencing `WITH t AS (SELECT k, w FROM t)`, an outer `FROM t` whose nested subquery
  shadows `t`, or (with `enable_global_with_statement = 0`) a nested `IN (SELECT k FROM t)` under
  an outer CTE `t`: skipped, never reported. A scope-less name set reported the last three.
- the earlier arms are unchanged: an insert into `s` and into `s2` read as `x IN s2` in an
  `APPLY` lambda are skipped, the ALIAS ALTER control is reported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +1187 to +1189
for (const auto & part : merge_tree->getDataPartsVectorForInternalUsage(
{MergeTreeData::DataPartState::Active},
{MergeTreeData::DataPartKind::Regular, MergeTreeData::DataPartKind::Patch}))

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.

⚠️ Track committed visibility for UNIQUE KEY tables

An unchanged active-part list does not imply unchanged rows for a UNIQUE KEY table. UniqueKeyTxnCommit::InsertCommit::publish makes the new part active before UniqueKeyTxnManager::commitTransaction commits it; MergeTreeData::createStorageSnapshot deliberately filters these parts using a separate visibility snapshot.

For example, start with (k, v) = (1, 1) and pause an overwrite with (1, 2) at unique_key_insert_pause_before_commit. Both parts are already active when parts_before is collected. The reference SELECT v FROM s WHERE k = 1 returns 1; let the overwrite commit before the partitioned read, which returns 2. parts_after contains the same names, so this legitimate data change is reported as AST_FUZZER_ORACLE_MISMATCH. The existing 04196_unique_key_read_skips_an_uncommitted_part.sh exercises precisely this active-before-visible transition, and the fuzzer enables this feature.

Include the table's committed visibility state in the fingerprint, or exclude UNIQUE KEY tables from these comparisons until that state is accounted for. Validate a commit between the oracle reads while the active-part names remain unchanged.

The part snapshot was taken from the fuzzed query, so a table named only
in a clause an oracle drops (the `ORDER BY`, `LIMIT` and `SETTINGS` that
`stripOrderAndLimit` removes) was recorded, and a part change in that
table skipped a genuine mismatch on the tables the oracle really reads. Each executor now parses the query it is about
to run, expands its `WITH` elements and records the parts of the tables
that query reads; on a mismatch only those are compared again. This also
narrows the skip to tables that changed after the query reading them
started.

The collector no longer walks `APPLY` lambdas and parameters: the `WITH`
expansion (`ApplyWithSubqueryVisitor`) does not reach them, so a table
name there may be a CTE, and `WITH t AS (SELECT k FROM s) SELECT *
APPLY (x -> (SELECT count() FROM t)) FROM s` recorded the physical `t`.
A table read only inside an `APPLY` lambda is now not recorded, so a
concurrent insert into it is reported, as on master.

The expanded copy also drops its `WITH` clauses rather than only the
CTE declarations, so an unused `WITH (SELECT count() FROM u) AS c` no
longer records `u`. A table read only through a used `WITH` alias is
not recorded either; a scalar subquery there is usually answered from
the scalars the oracle contexts copy from the fuzzed query's context.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/QueryOracleChecker.cpp Outdated
func && functionIsInOrGlobalInOperator(func->name) && func->arguments && func->arguments->children.size() > 1)
{
if (const auto * identifier = func->arguments->children[1]->as<ASTIdentifier>())
collectReadParts(identifier->createTable(), context, parts, depth);

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.

⚠️ Distinguish value identifiers from table reads on the right of IN

Expanding WITH does not make every remaining right-hand identifier a table name. For example, with s (k UInt32, arr Array(UInt32)) and an unrelated MergeTree table named arr, SELECT k FROM s WHERE k IN arr reads only s: QueryAnalyzer::resolveExpressionNode resolves the column before attempting table resolution. The same applies to expression aliases.

This branch nevertheless converts arr to an ASTTableIdentifier and records the unrelated table's parts. If that table inserts or merges while the oracle finds a genuine mismatch over unchanged s, readPartsChanged returns true and suppresses the finding. The new guard therefore hides wrong results even without any CTE.

Resolve the operand in its query scope before attributing it to storage, or omit the dependency when a table binding cannot be established. Please validate a column/table name collision; 04506_in_function_array_column_right_argument.sql already documents the column semantics.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 98dd7a6: a bare IN operand is no longer recorded, and neither is a FROM name that is the alias of another table expression of the same FROM (FROM s AS x JOIN x AS y).

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.

The bare-operand branch is gone, but the original column-versus-table attribution issue still occurs through expandWithElements at src/Interpreters/QueryOracleChecker.cpp:1194. With s (k UInt32, arr Array(UInt32)) and an unrelated MergeTree table t:

WITH arr AS (SELECT k FROM t)
SELECT k FROM s WHERE k IN arr

QueryAnalyzer::resolveExpressionNode resolves arr as the column before attempting table/CTE resolution. However, ApplyWithSubqueryVisitor::visit replaces it with the CTE subquery unconditionally (src/Interpreters/ApplyWithSubqueryVisitor.cpp:258), so the collector still records unread t. An insert into t can suppress a genuine mismatch even though both reads use only unchanged s. Omitting bare operands must also prevent this pre-expansion from introducing a table dependency for an operand bound to a value.

Three ways the part snapshot still recorded a table the oracle's query
does not read, so a part change there skipped a genuine mismatch:

- A view body was walked as stored. `CREATE VIEW` keeps the `WITH` list,
  so `WITH unused AS (SELECT k FROM t) SELECT k, w FROM s` recorded `t`.
  View bodies now get the same `WITH` expansion as the query.
- A bare `IN` operand was recorded as a table, but the analyzer resolves
  it as a column or an alias first: `k IN arr` with a column `arr` reads
  the column. Such operands are no longer recorded; a table read only as
  `x IN t` is then not recorded, so a change there is reported, as on
  master.
- A `FROM` name resolves to the alias of another table expression of the
  same `FROM` before the database catalog: in `FROM s AS x JOIN x AS y`
  both sides read `s`. A name that is such an alias is no longer
  recorded; aliases of other `FROM` clauses do not apply.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

ASTPtr read_ast = expandWithElements(ast, context);
Strings parts;
collectReadParts(read_ast, context, parts);

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.

⚠️ Do not attribute scalar-cache hits to fresh table reads

This collects tables inside scalar subqueries even when execution uses an inherited cached value. makeOracleContext copies ContextData::scalars, makeQueryContext preserves it, and QueryAnalyzer::evaluateScalarSubqueryIfNeeded returns the cached scalar on a matching query-tree hash.

For example, after the successful fuzzed query SELECT k, (SELECT count() FROM t) FROM s WHERE k = 1 has populated that cache, the Identity WHERE reference and variants can use the same cached count without reading t. The collector nevertheless snapshots t; an insert or merge there during the comparison makes readPartsChanged suppress a genuine mismatch over unchanged inputs. This violates the new guard's requirement that the changed table actually supply data to the compared reads.

Account for scalar substitution/cache hits when collecting dependencies, while retaining dependencies for fresh or correlated subqueries. Validate that changing only a cached scalar's source cannot suppress a mismatch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@qoega a question before I change this further. The tables an oracle query reads are found from its AST, and over four review rounds the bot has kept finding names that the analyzer resolves differently, so a table is recorded that the oracle's queries do not read. The latest: a CTE that the analyzer resolves to a table alias or to a column first (1, 2), and a scalar subquery whose value the oracle's queries take from the fuzzed query's scalar cache (3).

Such a table can hide a mismatch only if its parts change between the oracle's first read and the mismatch. The same already holds for every table the query does read, since the skip does not check that the change caused the mismatch. If no recorded table changes, the mismatch is reported, so the JIT case stays visible.

Is this approximation acceptable to you, or would you prefer no skip at all? In that case I will close this PR.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed?

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Yes. On master (39b9f2d5aed) only Subquery wrap re-checks its reference; the other oracles still report a mismatch when a write lands between their reads. I reproduced it today on a debug build of that commit: an INSERT into the MergeTree table while the oracle is paused between its reads (failpoint infinite_sleep on sleep(0)) gives TLP WHERE oracle mismatch! Reference query (40 rows) ... Partitioned query (80 rows) on the first attempt. On this PR's head the same driver skips it (measured 2026-10-20).

Latest CI case I measured: AST fuzzer (amd_release, oracle), 2026-10-28: a fuzzer-created Buffer table flushed a part into t_sparse_reload__fuzz_1 between two Identity WHERE reads (3 parts, then 4).

#117187 does not cover it: OracleExec::isStable (re-read the reference, skip if it differs) is used only by its five new oracles. A plain re-read is what @ qoega objected to for the existing ones on 2026-10-19, so this PR compares the parts lists instead; my question on whether that approximation is acceptable is still open.

The last CI run on this head is from 2026-10-20, and several master PRs have changed this file since, so it needs a fresh run before a merge. If you would rather fold this into the oracle series, I will close it.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm ok with this. The remaining threads can be fixed as follow-ups.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 6, 2026
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks. I'll address the remaining threads in a follow-up PR and link it here.

Merged via the queue into ClickHouse:master with commit 51ab070 Nov 6, 2026
179 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 7, 2026
@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov one question before I write the follow-up for the remaining threads.

Threads 1-3 (a table alias or a column shadowing a CTE, a cached scalar subquery) come from finding the tables from the AST: the guard records a table the oracle's queries do not read. I tried taking them from a separate analysis of each oracle query instead, but that still differs from what the execution reads: it has to redo the AST preparation of executeQuery, and it analyzes a view differently from the planner's read of it. The exact source is the plan executeQuery builds, and its storages are only in the private resources of QueryPipeline. Which do you prefer?

  1. Add a QueryPipeline getter for the storages of the plan (like QueryPipelineBuilder::getResources), and run the oracle's queries through the low-level executeQuery, so the guard records exactly what is read.
  2. Keep the current approximation. A skip still needs a part change in such a table during the oracle's reads, and a mismatch without one is always reported.

Threads 4-6 (row policies, on-the-fly mutations, UNIQUE KEY commits) only make a mismatch be reported, as before #119465, and I would leave them as is.

@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 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-fuzzing Fuzzers: BuzzHouse (the query generator in the client), the AST fuzzer (QueryFuzzer), and the lib... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants