Skip to content

AST fuzzer oracle: screen the definitions a read evaluates, not only the query text - #118484

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:ast-fuzzer-oracle-screen-stored-definitions
Sep 13, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:ast-fuzzer-oracle-screen-stored-definitions

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #91358

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 mismatch over 03322_initial_query_start_time_check's view tmp (report); @ alexey-milovidov asked for a separate fix PR (comment).

The oracle screened the query as written: check() walked its AST for non-deterministic functions and tested a named table only for engine and database. tmp's body evaluates now() on every read, and a query naming a view carries just an ASTTableIdentifier, so the arms read two states of one relation rather than a wrong result. Only the hidden spelling slipped through: now() already reports isDeterministic() == false.

I add one predicate, called once in check(), for all nine oracles. It resolves each name as a read does, then screens what that read evaluates with the existing predicates: a view's inner query, every column default expression (a read evaluates one for any column the part does not store, transitively reaching an EPHEMERAL one), and the row policy filter the read applies for the current user. What it cannot read fails closed: a MaterializedView, whose read is forwarded to a target resolved at read time, and a DEFINER view, which runs its body as another user whose policies this screen does not resolve. It also handles two spellings that hide a name: a forwarding engine (Alias, Merge, Buffer) and IN t.

Validation: 03322 under the oracle fails 8 of 40 runs before, 0 of 40 after; ablation builds redden its thirteen screened cases one at a time, and its five controls stay green. A screen can only skip a check, never fail one: 891 of 14527 stateless files create an object it rejects, 393 newly.

Still unscreened: an engine reading a query or source outside its metadata, and a session's additional_result_filter/additional_table_filters, owned by the settings gate (with rand(): 16 mismatches in 20 runs, 0 without).

Coverage census, and what a read can still evaluate unscreened

By grep over tests/queries/0_stateless (14527 files), an upper bound: creating a screened
object is not reading it under an eligible query.

Rejected because Files
creates a MATERIALIZED VIEW, or an Alias/Merge/Buffer/Distributed table 834
a column default expression is non-deterministic 48
a view's SQL SECURITY is DEFINER 15
a view body is non-deterministic 7
a row policy filter is non-deterministic 3
union 891
of which newly rejected here 393

340 of the 393 come from the MaterializedView rule; recovering them by screening a plain view's
target was reviewed here and left out.

joinGet/dictGet argument 0 also names a relation, and is not screened: every function those two
predicates match is non-deterministic (43 dictGet*/joinGet*, dictHas, dictIsIn,
naiveBayesClassifier*), so the query is already skipped whichever spelling names it: over clean
fixtures, 0 oracles in 15 runs for either spelling of either function, and 14 of 20 for a control.

Two residuals, neither a definition this metadata holds:

  • A refresh target named directly. Its own definitions are screened, but a refresh rewrites or
    exchanges its contents between the two arms. Answering that needs a RefreshSet lookup, a
    different question from what this metadata holds.
  • An engine whose read evaluates something outside its exposed metadata: Executable
    runs private input queries plus a script per read, TimeSeries builds a query over
    its targets, and Dictionary, File, S3, URL, Kafka and 5 more read outside the server.
    None override readsFromOtherTables. That is 13 families over about 220 files, so naming two or
    three here would read as closing the class without doing so; the bounded form is a storage
    capability, changing what the oracle checks suite-wide.

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

The oracle eligibility screen classified a query as written. It walked the
query's own AST for non-deterministic functions and resolved referenced tables
only to test the engine name and the database, so a query naming a view carried
just an ASTTableIdentifier and the view's body was never inspected.

A view body and an ALIAS column expression are re-evaluated on every read, so
the reference arm and the rewritten arm observed two different states of one
relation and the oracle reported a mismatch that was not a wrong result. The
carrier in the reported failure is 03322_initial_query_start_time_check's `tmp`,
a view whose body evaluates now(). now() already reports isDeterministic() ==
false, so the same expression written inline was rejected; only the spelling
hidden behind a name slipped through.

Screen a View's stored inner query and each ALIAS column expression with the
three existing whole-query predicates, recursing for a view over a view and
failing closed on anything unprovable. Reusing the existing predicates is
deliberate: it keeps the verdict independent of whether a construct is spelled
inline or hidden behind a name, instead of inventing a second determinism policy
for the hidden spelling.

Resolve each identifier the way a read resolves it, with
Context::tryResolveStorageID rather than by forcing the current database. Two
reachable spellings need it. A temporary view lives in the session namespace, so
a current-database lookup returns nothing and its body would go unscreened. A
fuzzer-generated {name:Identifier} placeholder has empty name parts until
substitution, which StorageID rejects, and that now fails closed like every
other unprovable case here instead of continuing the walk.

Classify by what a read evaluates, not by the engine's own name, where the two
differ: readsFromOtherTables() covers Alias, Merge and Buffer, whose metadata
and reads forward to a target that is not named in this AST. StorageView and
StorageMaterializedView do not override it, so the View branch and the
MaterializedView exclusion below are untouched.

A table can also be named without ever becoming an ASTTableIdentifier. `IN t`
means `IN (SELECT * FROM t)`, and argument 0 of joinGet and of dictGet name a
table and a dictionary, but MarkTableIdentifiersVisitor performs that rewrite
during analysis, on a clone, after check() has already run, so the operand this
walk sees is still a plain ASTIdentifier and the table branch passes over it.
Synthesise the identifier analysis would have synthesised and re-enter the walk,
which keeps one screen for all three spellings. The pure name predicates from
Interpreters/misc.h are used rather than checkFunctionIsInOrGlobalInOperator,
which dereferences the argument list and throws when the arity is not two; both
are ordinary on a fuzzer-mutated AST. A name that cannot be read as a table name
fails closed, which matters because the fuzzer substitutes {name:Identifier}
placeholders into this operand: measured on the reported carrier, letting one
through produced a false TLP WHERE mismatch roughly once in 450 fuzzed queries.

The call sits in check(), the single entry point, so all nine oracles are
covered. That is the right layer because this class was observed through two
different oracles (TLP WHERE and DQP) on two unrelated pull requests, which
makes it a defect of the gate rather than of any one oracle.

isView() is not used as the predicate because it is also true for
MaterializedView, whose read goes to its target table rather than to its stored
SELECT. hasSelectQuery() is not used as the guard either: it tests select_query,
a field StorageView never sets, so the screen would have been silently vacuous.

A MaterializedView whose target is Distributed still bypasses the existing
engine gate. That hole belongs to that predicate and is left alone here.

The test attributes each counter move to the query the server logged. A
parameterized identifier is logged as {fuzz_param_N:Identifier}, because the
trace line is formatted before substitution, so the object name is absent and a
move paired with such a query cannot be attributed by name. In a table position
that placeholder is a leak whatever it stands for, since both placeholder
branches above reject before any oracle runs, so the test counts it as one.
ARRAY JOIN and IS DISTINCT FROM end in those keywords while taking a column
operand, which reaches no such branch, so they are excluded and a correct build
cannot fail. The IN operand is matched in its parenthesized spelling, because
ASTFunction always parenthesizes a bare identifier right-hand side.

Validation: 03322 run under the oracle fails 8 of 40 runs before this change
and 0 of 40 after. On a binary without the change all seven screened cases
of the new test redden at once while all three anti-vacuity controls stay
green, and each screened path is armed individually by an ablation build
that reddens exactly its own case. The placeholder branch is armed the same
way: a build that stops rejecting a parameterized IN operand reddens the IN
case, which the same test without that attribution rule never reports. The
fuzzer's parameterization rate is hard-coded, so that arm fires in 1 of 40
unforced runs and is therefore also shown deterministically by forcing the
rate, with the correct build staying green on all seven screened cases under
the same forcing. The sibling branch, an ASTTableIdentifier whose name parts
were cleared, cannot be armed at all: made permissive, the empty StorageID
is still built and throws out of the fuzzer, so no oracle runs and the
counter never moves. Coverage was measured per test over repetitions,
because a single batch total is noisy under random mutation: on a 30-test
view-heavy batch the total ASTFuzzerOracleChecks is 119 without the screen
and 74 with it, and every rejection is attributable to a substantive
predicate, none to the fail-closed paths.
@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 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Five rounds of pre-publication review before this PR was opened: an independent model
(engine: codex) plus my own cold review of the resulting code each round, adjudicated against the
recorded validation. The branch is one commit, so every AGREEd fix below is in it.

# Sev Finding Verdict Evidence / action
1 ❌ A temporary view and a fuzzer-generated {name:Identifier} bypass the new screen, because the identifier is resolved by hand into the current database instead of the way a read resolves it AGREE, fixed A temporary view uses the View storage and lives in the session namespace, which only Context::resolveStorageIDImpl consults (Context.cpp:8263-8291), and a parameterized identifier has an empty name until substitution (QueryFuzzer.cpp:3965-3971). Resolved through Context::tryResolveStorageID, failing closed on an unresolvable name.
2 ❌ A view read through ENGINE = Alias bypasses the screen, because view detection tests the wrapper's engine name AGREE, fixed StorageAlias::getName() is the fixed string "Alias" (StorageAlias.h:28), yet its metadata and its read both forward to the target, so the target view's body is evaluated on every read. Now fails closed on readsFromOtherTables(), whose declaration names exactly this set (IStorage.h:121-125). I re-censused every overrider and confirmed StorageView and StorageMaterializedView do not override it, so the View branch and the MaterializedView exclusion are untouched.
3 ❌ A table named as the right operand of IN is never screened AGREE, fixed ClickHouse's own source states the equivalence (MarkTableIdentifiersVisitor.cpp:52-56), and the ASTIdentifier to ASTTableIdentifier rewrite happens during analysis, after check() runs, so the walk passed over it. The synthesised identifier now re-enters the same screen; joinGet and dictGet argument 0 are covered by the same branch. checkFunctionIsInOrGlobalInOperator is deliberately not called: it dereferences the argument list and throws on arity other than 2 (misc.h:44-58), both ordinary on a fuzzer-mutated AST.
4 ❌ The new test would fail the flaky-check lane's runtime limits AGREE, fixed clickhouse-test:208,3749-3765 fails a test in flaky-check mode when one run exceeds 180s without the long tag, and :3923,7057-7061 applies a 600s per-test timeout that the tag does not waive; the flaky check gives a no-parallel test 25 runs (ci/jobs/functional_tests.py:703-714). Anchored on the sibling 04658, which uses the same counter technique. Tagged long and reworked to one client invocation per iteration: 85-87 client invocations and a 16.2s local median, projecting to 216-407s on an asan flaky-check runner depending on the anchor, against the 600s per-test timeout.
5 ⚠️ The regression test is weaker than the screening contract: the only anti-vacuity case is a deterministic view, and the recursion and the system-database branches have no arming case AGREE, fixed I raised the first half independently. The test now has 7 screened cases and 3 anti-vacuity controls, and each screened path is armed by an ablation build that reddens exactly its own line.
6 💡 Every resolved table's ALIAS columns are screened even when the query does not read them DISAGREE Over-rejection can only skip an oracle check, never produce a false mismatch, and it matches this file's stated doctrine that over-matching "merely skips one more query, which is safe". Re-examined in round 5 against a larger measurement: on a deliberately view-heavy 30-test batch the screen takes ASTFuzzerOracleChecks from 119 to 74, and every rejection is attributed to a substantive predicate (non-deterministic function 78, system.* 22, reads-from-other-tables 21, nested definition 13) with zero from the fail-closed paths, so the drop is the false-mismatch source being removed rather than coverage lost. Narrowing the screen to only the ALIAS columns a query names would be unsound: SELECT * excludes ALIAS columns only while asterisk_include_alias_columns = 0, and column binding has not happened when check() runs.
7 💡 Other read-time carriers stay unscreened: a MaterializedView's target, a DEFAULT/MATERIALIZED expression for a column absent from parts written before an ALTER ADD COLUMN, a row policy filter, and system.* reached as an IN operand Noted, not blocking Merge and Buffer are covered by the fix to finding 2. For each of the rest I looked for a live carrier in the 14518-file stateless suite and found none: the one DEFAULT rand() candidate is OPTIMIZE ... FINALed before its only read, the one rand() row policy is used only under EXPLAIN over an already-gated query, and the only IN <system table> spelling is system.one, a constant single-row table, inside a query the table-function gate already rejects. The fuzzer cannot manufacture the last shape either: its only IN generation path requires a subquery operand, which the existing predicates walk directly. Re-enumerated independently in round 5 from the read paths rather than from the earlier list, which also confirmed that LiveView/WindowView no longer exist in the tree. Not raised.
8 ⚠️ A regression in either fail-closed path for a fuzzer-parameterized identifier would be reported as a pass, because the test attributes a counter move by matching the object name in the logged query AGREE, fixed QueryFuzzer::makeParameterizedIdentifier clears every name_parts entry and keeps the real name only in the separately shipped parameter map (QueryFuzzer.cpp:8790-8823), and the logged query is formatted before substitution (executeQuery.cpp:3481-3495), so the only Fuzzed query: line in the stream carried {fuzz_param_N:Identifier} and the sample was discarded as an unrelated mutation. The leak condition now also fires on a placeholder in a FROM/JOIN/IN operand, which a correct build can never let reach an oracle. Arming came out asymmetric and is reported as such rather than as two armed paths - see finding 9.
9 ⚠️ Ten random mutations per assertion rarely reach the 1/200 table-identifier and 1/800 expression-identifier parameterization rates, so show that both placeholder fail-closed paths redden under forced-rate ablations, or add deterministic coverage DISAGREE: satisfied for one path, impossible for the other createTable() path: the asked-for evidence exists. Forcing the 1/800 site to 1/1 makes the permissive build red on exactly its own line 5 of 5, while the same binary under the previous leak condition never reports that line (5 of 5) and the correct build leaves all 7 screened lines green under the same saturation; unforced rate is 1 red in 40 runs. ASTTableIdentifier cleared-name path: deterministic coverage is impossible by construction, not merely absent. QueryFuzzer::fuzzTableName calls identifier->getTableId() (QueryFuzzer.cpp:3231) on the table expression it visits; for a cleared-name identifier that builds StorageID{{}, "", Nil} (ASTIdentifier.cpp:431-435), whose constructor calls assertNotEmpty() and throws UNKNOWN_TABLE (StorageID.cpp:83-84) inside the fuzzer's own mutation pass, before the query executes and so before any ASTFuzzerOracleChecks increment. The table_id.empty() guard at :3232 is one line too late. No counter-delta assertion of any shape can therefore redden that path, and none is claimed to: the permissive ablation for it (build id differing from the correct build) produces byte-identical output under table-name forcing at 1/1. There is also no user-writable input that reaches the branch, since {t:Identifier} with its parameter supplied resolves to a real name.
10 💡 Round 5 completeness check of the new leak condition, for the record Noted, no defect The condition anchors on FROM/JOIN followed by a placeholder, so I enumerated every formatter emission ending in those words that takes a non-table operand, to rule out a false positive on a correct build. INNER/LEFT/RIGHT/FULL OUTER/CROSS/PASTE JOIN (ASTTablesInSelectQuery.cpp:241-259) are all table positions; ARRAY JOIN/LEFT ARRAY JOIN (:307) and IS DISTINCT FROM (ASTFunction.cpp:693) take operands and are both blinded before matching; ORDER BY ... WITH FILL FROM <expr> (ASTOrderByElement.cpp:81-83) is the only one left and cannot false-positive, because hasWithFillAnywhere skips the oracle for such a query before any counter move exists. Every other FROM emission belongs to a statement extractSimpleSelect rejects.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

One note for whoever merges this: it touches QueryOracleChecker.cpp, which #117200 would remove
and #117187 rewrites. This PR is scoped to the oracle as it stands on master and becomes moot if
#117200 lands. It does not overlap #117799's hunks.

Session id: cron:clickhouse-review-slot-9:20260906-222500

@clickhouse-gh clickhouse-gh Bot closed this Sep 6, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [caeabfb]

Summary: ✅


AI Review

Summary

This PR substantially improves the AST fuzzer oracle gate by screening hidden read-time definitions such as view bodies, column defaults, row policies, MaterializedView, DEFINER views, and IN <table> spellings. The remaining gap is that the new helper still treats readsFromOtherTables() as the boundary of "hidden read-time definitions", which is not true for at least TimeSeries, so the oracle can still run on a relation whose actual read path was never screened.

Findings

⚠️ Majors

  • [src/Interpreters/QueryOracleChecker.cpp:967] readsFromOtherTables() is not a complete proxy for storages whose reads evaluate hidden definitions. StorageTimeSeries stores SAMPLES / TAGS / METRICS targets in its metadata and builds a query over those targets on each read, but it does not override readsFromOtherTables(). As a result, SELECT ... FROM ts can still reach the oracle without screening the target tables' view/default/row-policy carriers, so the same false-mismatch class survives through ENGINE = TimeSeries. Suggested fix: fail closed for TimeSeries (and similar engines) here, or add a stronger storage capability that means "a read may evaluate hidden definitions outside this table's visible AST/metadata".
Final Verdict

⚠️ Not ready yet: the new gate closes the cases discussed in the existing review threads, but it still leaves at least one concrete storage family (TimeSeries) outside the contract it is now trying to enforce.

LLVM Coverage Report

Measured on commit caeabfb.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.20% +0.10%

Changed lines: Changed C/C++ lines covered: 26/55 (47.27%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local with ast_fuzzer_runs=1, ast_fuzzer_oracle=1 over the reported view (CREATE OR REPLACE VIEW tmp AS SELECT initialQueryStartTime() as it, now() AS t FROM system.one WHERE NOT ignore(sleep(0.5))) gives Code: 906 ... TLP WHERE oracle mismatch! in 9 of 10 runs. End to end, 03322_initial_query_start_time_check run under the oracle fails 8 of 40 runs on master. The IN-operand path added later is fuzzer-triggered rather than on-demand, so it is quantified instead (~1 in 450 fuzzed queries) with the exact reproducer captured.
b Root cause explained? Yes. QueryOracleChecker::check screens the query as written: it walks the query's own AST for non-deterministic functions, and resolves referenced tables only to test the engine name and the database. A query naming a view carries just an ASTTableIdentifier, so the view's body is never inspected. A view body is re-evaluated on every read, so the reference arm and the rewritten arm observe two states of one relation. now() already reports isDeterministic() == false, so the same expression written inline is rejected today.
c Fix matches root cause? Yes. The screen is added at the gate that classifies oracle eligibility, which is where the misclassification happens. No widened bound, no no-random-* tag, no dataset reduction, no guard at the mismatch site. The 03322 fixture is deliberately not modified: 316 stateless files create a plain view, so the class is a property of the harness.
d Test intent preserved / new tests added? Yes. No existing test is changed. New 05099_ast_fuzzer_oracle_view_definition.sh covers ten cases: a view, a view over a view, a view over system.*, a temporary view, ENGINE = Alias over a view, an ALIAS column, a table named as an IN operand, and three anti-vacuity controls (a deterministic view, a deterministic ALIAS column and a deterministic IN operand, each of which must still reach an oracle). It asserts on the ASTFuzzerOracleChecks profile event rather than on "the query succeeded", because a random mutation can make a query oracle-ineligible for unrelated reasons, so an absent mismatch alone cannot distinguish "screened" from "never checked". A counter move is attributed to the query the server logged; because a parameterized identifier is logged as {fuzz_param_N:Identifier} (the trace line is formatted before substitution), a move paired with such a placeholder in a table position also counts as a leak, so a regression in the placeholder path cannot be discarded as an unrelated mutation.
e Both directions demonstrated? Yes. (1) 03322 under the oracle: 8 of 40 runs fail on pristine master, 0 of 40 with the change; the base mismatches span five different optimizer settings, so the drift is in the fixture, not one optimizer. (2) On pristine master all seven "must be screened" lines of the new test redden at once while all three controls stay green, and that held in 5 consecutive runs (35 of 35 screened-line detections), so it cannot pass vacuously. (3) Each screened path is armed individually: seven one-mechanism ablation builds, each run against the whole test file, and each reddens exactly its own line and no other; an over-broad variant that rejects every named definition reddens all three controls, and one that rejects every IN operand reddens the IN control alone. (4) The placeholder path is armed too: a build that stops rejecting a parameterized IN/joinGet/dictGet operand reddens the IN screened line, which the same test without that attribution rule never reports. Because the parameterization rate is hard-coded (fuzz_rand() % 800 == 0) that arm fires in 1 of 40 unforced runs, so it is also shown deterministically by forcing the rate to 1/1: armed build 5 of 5 red, correct build 7 of 7 screened lines green under the same saturation. The sibling path (an ASTTableIdentifier with cleared name parts) is reported as NOT armable: made permissive, the empty StorageID still throws out of QueryFuzzer::fuzzTableName, so the counter never moves and no attribution rule can observe it. Build IDs asserted against the live server on every run (base 7221a938, final b3ecb53b).
f Fix is general across code paths? Yes. The predicate is called once, in check(), the single entry point, so all nine oracles are covered rather than the one that happened to report. That location is the point: this class has appeared through two different oracles on two unrelated PRs, so it is a gate defect. Carriers covered by reusing the existing predicates: a view body with a non-deterministic function, with system.*, with a Distributed table, with a table function or SAMPLE, view over view to the depth cap, a temporary view, ALIAS column expressions, and any storage that returns rows it does not hold (Alias, Merge, Buffer).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Names are resolved the way a read resolves them (Context::tryResolveStorageID), so a temporary view in the session namespace is screened and a {name:Identifier} placeholder, whose name parts are empty until substitution, fails closed. Engine classification does not rely on the engine's own name where that name does not describe what a read evaluates: readsFromOtherTables() fails closed on Alias/Merge/Buffer. Gated on getName() == "View" rather than isView(), which is also true for MaterializedView (whose read goes to its target table, so its body is not a read-time carrier). Tests getSelectQuery().inner_query directly rather than hasSelectQuery(), which tests select_query, a field StorageView never sets, so using it would have made the screen silently vacuous. Depth cap bounds a view chain closed into a cycle by CREATE OR REPLACE; unresolvable names and unreadable metadata fail closed.
h Backward compatible? (maintainer-approved exception only) Yes. Behaviour changes only on the fuzzer-only oracle path, behind ast_fuzzer_oracle = 1 and ast_fuzzer_runs > 0, both non-default. No setting added or changed, so no SettingsChangesHistory.cpp entry; no format change; no error-code change.
i Invariants and contracts preserved? Yes. A read-only predicate over ASTs and catalog metadata: no mutation of the query AST, the storage, or the context, and every path returns a bool, including the depth-cap and catch (...) paths. No lock beyond what the sibling gate two lines above already takes. Coverage measured rather than assumed, per test over repetitions because a single batch total is noisy under random mutation: on a 30-test view-heavy batch the total ASTFuzzerOracleChecks is 119 without the screen and 74 with it, and a diagnostic build attributes every rejection to a substantive predicate (non-deterministic function 78, system.* 22, reads-from-other-tables 21, nested definition 13) with zero from the fail-closed paths, so the widening is not a blanket.

Session id: cron:clickhouse-impl-slot-7:20260906-185200

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @qoega @PedroTadim, could you review this? check() screens only the query text, so a now() hidden in a view body or an ALIAS column expression is never seen and the oracle's two reads of that name observe two different values, reported as a mismatch. I add one predicate in check() that resolves each name the way a read resolves it and screens the definition behind it with the three predicates that already screen the query.

Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing caeabfbfc with master e568d262d (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.

Compile time of recompiled translation units

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

Job report

…AS defaults

Two read-time definition carriers the previous commit's screen let through. Both
were disclosed there as left alone; both are reachable, so close them.

A MaterializedView read is not evaluated from the view's stored SELECT.
StorageMaterializedView::readImpl resolves the target name and forwards the read
to it, so the engine name and the column defaults that decide this verdict belong
to a table the screen never inspects. StorageMaterializedView does not override
readsFromOtherTables(), so the branch above does not catch it, and the previous
commit's note that only a Distributed target bypasses the engine gate understates
the hole: a carrier screened on an ordinary table is reachable through the target,
using nothing but MergeTree.

    SET mutations_sync = 2;
    CREATE TABLE src (k UInt32, v UInt32) ENGINE = MergeTree ORDER BY k;
    CREATE TABLE tgt (k UInt32, v UInt32) ENGINE = MergeTree ORDER BY k;
    CREATE MATERIALIZED VIEW mv TO tgt AS SELECT k, v FROM src;
    INSERT INTO src SELECT number, number FROM numbers(5);
    ALTER TABLE tgt DROP COLUMN v;
    ALTER TABLE tgt ADD COLUMN v UInt32 DEFAULT rand();
    SELECT groupArray(v) FROM mv;   -- [474819641,38312494,1664185434,...]
    SELECT groupArray(v) FROM mv;   -- [3709367502,3115761651,2759094222,...]

Recursing into the target instead would not bind the read, because the target is
resolved again when the read runs: for a non-append refreshable view through
RefreshTask::getAndLockTargetTable, whose retry loop exists precisely because
that name can resolve to a different table. So the name fails closed.

A read also evaluates a column's default expression for every column the part it
reads does not store. defaultRequiredExpressions pulls
ColumnsDescription::getDefault into the read pipeline for any missing column, so
two reads of one unchanged part disagree exactly as the already-screened ALIAS
case does.

    CREATE TABLE t (k UInt32) ENGINE = MergeTree ORDER BY k;
    INSERT INTO t SELECT number FROM numbers(5);
    ALTER TABLE t ADD COLUMN x UInt32 DEFAULT rand();
    SELECT groupArray(x) FROM t;    -- [2314848760,775700247,1367725962,...]
    SELECT groupArray(x) FROM t;    -- [3083446352,2545416879,855013712,...]

Which columns a part stores is not in the metadata this screen reads, so screen
every column carrying a default expression, of any kind. EPHEMERAL is included
even though such a column cannot be selected: supplying a missing column also
pulls in the defaults of the columns its own expression needs, which reaches an
ephemeral expression through a readable column that defaults to it.

    ALTER TABLE t ADD COLUMN e UInt32 EPHEMERAL rand();
    ALTER TABLE t ADD COLUMN y UInt32 DEFAULT e;
    SELECT groupArray(y) FROM t;    -- [4247061986,3501469440,501034194,...]
    SELECT groupArray(y) FROM t;    -- [420030954,3211237349,2928432379,...]

Coverage cost of the wider column test: 44 of 14527 stateless test files name a
non-deterministic DEFAULT, MATERIALIZED or EPHEMERAL expression, against the 500
that already create an object this screen rejects. A screen can only skip an
oracle check, never fail one, so the cost is coverage and never a red test.

Validation: five arms added to 05099, and three one-mechanism ablation builds
each redden exactly the lines their own screen guards. Dropping the
MaterializedView branch reddens only the materialized-view line; narrowing the
column test back to ALIAS reddens the DEFAULT, MATERIALIZED and EPHEMERAL lines;
restoring an EPHEMERAL exclusion reddens only the EPHEMERAL line, so that arm is
the sole detector of it. All four anti-vacuity controls stay green under every
ablation. The restored build passes 25 of 25 runs, and 03322 under the oracle
stays at 0 of 15.

Also trims the predicate doc comment, whose second half restated this message
rather than a local invariant.
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
…ER view

The third read-time definition carrier disclosed as left alone. A row policy adds a
filter to every read of the table it is attached to, for the current user, and the
filter is stored on the policy, so it is in neither the query nor the table's
metadata. The read path looks it up per read: getEffectiveRowPolicyFilter in
Planner/PlannerJoinTree.cpp with the analyzer, the InterpreterSelectQuery
constructor without it. Such a filter is allowed to be non-deterministic, so two
reads of a query naming only the table select different rows, which is the same
false mismatch this screen exists to prevent.

    CREATE TABLE t (k UInt32) ENGINE = MergeTree ORDER BY k;
    INSERT INTO t SELECT number FROM numbers(50);
    CREATE ROW POLICY p ON t USING (rand() % 2) = 0 TO ALL;
    SELECT count() FROM t;   -- 21
    SELECT count() FROM t;   -- 27
    SELECT count() FROM t;   -- 30

Screen the filter expression with the predicates already applied to a view body and
a column default, rather than rejecting every table that carries a policy. The
expression is available exactly where a column default is, so the fail-closed
treatment a MaterializedView needs does not apply, and the narrower verdict costs
far less coverage: 119 stateless test files create a row policy, 3 of them with a
non-deterministic filter. The lookup is Context::getRowPolicyFilter, the one the
read performs, so a policy attached to the database rather than to the table is
covered by the same call.

Unlike every other predicate here, this verdict is relative to a user, so a view
that evaluates its body as someone else escapes it. A DEFINER view does exactly
that, and the definer's policy is then reachable through a body naming one plain
column, while the reader has no policy on the base table at all:

    CREATE TABLE s (k UInt32) ENGINE = MergeTree ORDER BY k;
    INSERT INTO s SELECT number FROM numbers(50);
    CREATE USER u IDENTIFIED WITH no_password;
    GRANT SELECT ON db.s TO u;
    CREATE ROW POLICY p ON s USING (rand() % 2) = 0 TO u;
    CREATE VIEW v DEFINER = u SQL SECURITY DEFINER AS SELECT k FROM s;
    SELECT count() FROM s;   -- 50, 50, 50: no policy applies to the reader
    SELECT count() FROM v;   -- 27, 31, 25: the definer's policy is evaluated

Recursing with getSQLSecurityOverriddenContext would answer that precisely, but it
builds a whole query context per node, resolves the definer through the access
control and throws once that user is gone, none of which belongs on this screen's
hot path, so a DEFINER view fails closed instead. SQL SECURITY NONE needs nothing:
it runs with no user, where no policy applies, and screening the reader's policy is
then merely conservative. The cost is 15 stateless files, and INVOKER is the
default for a normal view.

Validation: two screened arms and one anti-vacuity control added to 05099, and two
one-mechanism ablation builds redden exactly one arm each. Dropping the policy
lookup reddens only the row-policy line; dropping the DEFINER branch reddens only
the DEFINER line, which is also what proves that arm is not vacuous, since a
DEFINER view the screen ignores does reach an oracle. The deterministic-filter
control reads "oracle ran" under both ablations, separating "screen a
non-deterministic policy" from "reject every table that has one". The restored
build returns its Build-ID, passes 10 of 10 runs of 05099, and keeps 03322 under
the oracle at 0 of 15.
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-testing Test content only (no production code). labels Sep 7, 2026
Comment thread src/Interpreters/QueryOracleChecker.cpp Resolved
A review round asked for the documented dictGet('name', ...) spelling to enter the
screen as well: the branch re-entered it only for an ASTIdentifier operand, while
AddDefaultDatabaseVisitor accepts an identifier or a String literal in that same
position. Handling the literal there would add unreachable code, so remove the two
legs instead and keep the reachable one.

Every name functionIsJoinGet and functionIsDictGet match is itself
non-deterministic: all 43 functions whose name starts with dictGet or joinGet, plus
dictHas, dictIsIn and the three naiveBayesClassifier spellings, report
deterministic = 0 in system.functions. hasNonDeterministicFunctionsImpl rejects an
AST holding any of them, through FunctionFactory::tryGet(name)->isDeterministic(),
and each oracle applies that predicate to the whole select before rewriting
anything. So a query naming one of these functions is skipped whichever spelling it
uses, and a stored definition holding one is rejected by the first predicate of the
same loop rather than by this branch.

Measured on this build over 15 fuzzed runs each, with fixtures that carry no
non-deterministic definition at all, counting ASTFuzzerOracleChecks:

    SELECT joinGet(cj, 'v', k)              FROM src WHERE k > 5   -- 0 oracles ran
    SELECT joinGet('cj', 'v', k)            FROM src WHERE k > 5   -- 0
    SELECT dictGet(cd, 'v', toUInt64(k))    FROM src WHERE k > 5   -- 0
    SELECT dictGet('cd', 'v', toUInt64(k))  FROM src WHERE k > 5   -- 0
    SELECT k                                FROM src WHERE k > 5   -- 14 of 20

The last line is the control: an oracle-eligible query in the same session does run.
Repeating the four over a Join table with an ALIAS rand() column and a dictionary
carrying a non-deterministic row policy changes nothing, and every count is
identical before and after this commit.

IN t stays. Its operand is a name no other predicate resolves, a String there is a
value rather than a name (SELECT 7 IN 'src' is Code 53 TYPE_MISMATCH), and deleting
the leg reddens 05099's IN arm while the other 17 arms stay green.
/// An engine that returns rows it does not store evaluates a definition that
/// is neither in this AST nor in its own metadata, so its engine name does
/// not say what a read of it evaluates.
if (storage->readsFromOtherTables())

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.

readsFromOtherTables() is not a sufficient proxy for "this name's read evaluates hidden definitions outside the query AST." StorageTimeSeries is a concrete bypass: its metadata stores SAMPLES / TAGS / METRICS targets (src/Storages/StorageTimeSeries.h:20-22, src/Storages/StorageTimeSeries.h:49-53), and each read builds a query over those target tables (src/Storages/TimeSeries/makeASTSelectFromTimeSeries.cpp:692-760), but StorageTimeSeries does not override readsFromOtherTables().

That means SELECT ... FROM ts can still reach the oracle without screening the target tables' view/default/row-policy carriers, which is the same false-mismatch class this helper is meant to eliminate. I think this branch needs either an explicit fail-closed case for TimeSeries (and any similar engine) or a stronger storage capability than readsFromOtherTables() that specifically means "a read may evaluate hidden definitions not visible in this table's own AST/metadata."

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

Ok, it makes the fuzzer less wrong.

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit 9d75482 Sep 13, 2026
174 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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.

3 participants