Repository navigation
AST fuzzer oracle: screen the definitions a read evaluates, not only the query text - #118484
Conversation
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.
Internal second-model review: adjudication log (click to expand)Five rounds of pre-publication review before this PR was opened: an independent model
Severity: ❌ blocker / One note for whoever merges this: it touches Session id: cron:clickhouse-review-slot-9:20260906-222500 |
|
Workflow [PR], commit [caeabfb] Summary: ✅
AI ReviewSummaryThis PR substantially improves the Findings
Final Verdict
LLVM Coverage ReportMeasured on commit caeabfb.
Changed lines: Changed C/C++ lines covered: 26/55 (47.27%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260906-185200 |
|
cc @qoega @PedroTadim, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 11 s compile time in total, 7 of them have a recent master baseline. |
…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.
…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.
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()) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Ok, it makes the fuzzer less wrong.
Related: #91358
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
AST fuzzer (amd_release, oracle)reported a TLPWHEREmismatch over03322_initial_query_start_time_check's viewtmp(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 evaluatesnow()on every read, and a query naming a view carries just anASTTableIdentifier, so the arms read two states of one relation rather than a wrong result. Only the hidden spelling slipped through:now()already reportsisDeterministic() == 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 anEPHEMERALone), and the row policy filter the read applies for the current user. What it cannot read fails closed: aMaterializedView, whose read is forwarded to a target resolved at read time, and aDEFINERview, 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) andIN t.Validation:
03322under 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 (withrand(): 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 screenedobject is not reading it under an eligible query.
MATERIALIZED VIEW, or anAlias/Merge/Buffer/DistributedtableSQL SECURITYisDEFINER340 of the 393 come from the
MaterializedViewrule; recovering them by screening a plain view'starget was reviewed here and left out.
joinGet/dictGetargument 0 also names a relation, and is not screened: every function those twopredicates match is non-deterministic (43
dictGet*/joinGet*,dictHas,dictIsIn,naiveBayesClassifier*), so the query is already skipped whichever spelling names it: over cleanfixtures, 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:
exchanges its contents between the two arms. Answering that needs a
RefreshSetlookup, adifferent question from what this metadata holds.
Executableruns private input queries plus a script per read,
TimeSeriesbuilds a query overits targets, and
Dictionary,File,S3,URL,Kafkaand 5 more read outside the server.None override
readsFromOtherTables. That is 13 families over about 220 files, so naming two orthree 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]