Repository navigation
Revert "Revert "Refuse a Set table on the right side of IN when a row policy applies to it"" - #122141
Conversation
… row policy applies to it""
|
Workflow [PR], commit [eb6d3e5] Summary: ✅
AI ReviewSummaryThis PR re-applies the Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit eb6d3e5.
Changed lines: Changed C/C++ lines covered: 218/235 (92.77%) · Uncovered code |
The eight IgnoreSet variants of IN (in.cpp registers inIgnoreSet, globalInIgnoreSet, notInIgnoreSet, globalNotInIgnoreSet, nullInIgnoreSet, globalNullInIgnoreSet, notNullInIgnoreSet, globalNotNullInIgnoreSet) return 0 for every row without ever looking at their right operand. They exist so that types can be resolved without building a set, and FunctionIn is variadic precisely so the left operand can be passed alone: isVariadic() == ignore_set, getNumberOfArguments() == ignore_set ? 0 : 2, and getReturnTypeImpl accepts 1 or 2 arguments and returns UInt8 either way (src/Functions/in.cpp:51-72). The old analyzer already builds the node that way, and its comment at src/Interpreters/ActionsVisitor.cpp:1322-1341 explains why a stand-in column is not an acceptable substitute. Commit c0596ea stopped preparing the right operand for these functions, which is correct, but kept adding a set column to the ActionsDAG. It gated the tuple lookup, the subquery/storage lookup and the guarding `if (!set) throw` on !ignore_set, so `set` stays default-constructed and ColumnSet::create(1, nullptr) enters the plan. That unconditional throw was what enforced the invariant "a planner-built ColumnSet always holds a non-null FutureSetPtr", so removing it turned an enforced property into an assumed one, and every consumer that dereferences ColumnSet::getData() without a null check became reachable with null. Six of the getData() call sites in the tree are in that shape (ActionsDAG.cpp:4744, VirtualColumnUtils.cpp:83 and :140, ReadFromRemote.cpp:324, KVStorageUtils.cpp:189 and :381); the rest null-check the pointer before using it. Two were observed crashing within fifteen minutes of each other on 2026-09-24, both first-ever in ninety days: - serializeConstant at src/Interpreters/ActionsDAG.cpp:4744, reached from the aggregation hash-table cache-key path (calculateHashTableCacheKeys.cpp:161 -> optimizeTreeSecondPass), master STID 2060-5018; - buildSetsForDagImpl at src/Storages/VirtualColumnUtils.cpp:84, reached from SourceStepWithFilterBase::applyFilters for virtual-column and PREWHERE filter analysis, STID 4168-5979. Both are plain segmentation faults on a debug or release build, and UndefinedBehaviorSanitizer reports them as a member call on a null pointer of type DB::FutureSet. Note that this is a null shared_ptr, not the not-ready-set state, which is future_set->get() == nullptr with future_set itself non-null. Fix the producer rather than the consumers. visitFunction no longer calls makeSetForInFunction for an IgnoreSet call and builds the DAG node from the left operand alone, so no set column is created and there is nothing for a consumer to dereference. Because makeSetForInFunction is no longer reached for these functions, its ignore_set gates are removed and the unconditional `if (!set) throw` is restored, which makes the invariant enforced again instead of merely documented. Guarding the consumers was rejected: it is a symptom guard at the dereference rather than a fix at the source, it does not scale, because each consumer needs its own decision about what a null set means, and serializeConstant has no good local answer because it must emit a FutureSet::Hash, so a sentinel would silently collide distinct plans in the hash-table statistics cache. Attaching a non-null empty placeholder set was also rejected: notInIgnoreSet executes to 0, but an empty set makes a notIn predicate true, so index analysis at KeyCondition.cpp:1044 and RPNBuilder.cpp:432 would then disagree with execution. Since the DAG node now has one child while the query tree function was resolved over two arguments, the node is built from a FunctionFactory resolver over the children that are actually present, which is the same branch group_by_use_nulls already uses and which keeps the node's argument types in agreement with its children. The access-control behaviour added by c0596ea is unchanged: neither PreparedSets lookup is reinstated, so the right-hand side is still never prepared and never authorized, and tests/integration/test_set_engine_row_policy_serialized_plan passes, including the assertion that inIgnoreSet over a Set table succeeds for a user for whom the plain IN spelling is denied by a row policy. Co-Authored-By: Claude Opus 5 <[email protected]> (cherry picked from commit 19d4854 of #122130)
…r to a shard tryBuildAdditionalFilterAST (src/Processors/QueryPlan/ReadFromRemote.cpp) rebuilds a pushed-down filter as an AST out of the plan's expression DAG, and it assumes the two-child shape for every IN-family function name. The previous commit leaves an IgnoreSet call with its left operand alone, which breaks that assumption in two independent ways. The four global variants are covered by isNameOfGlobalInFunction (src/Analyzer/Utils.cpp), so the GLOBAL IN block reaches node->children.at(1) on a one-child node. std::out_of_range derives from std::logic_error, so src/Common/Exception.cpp aborts the whole server process on a debug or sanitizer build, and on any build where abort_on_logical_error is set (observed: exit 134, stack through tryBuildAdditionalFilterAST); a release build without that flag reports it as query error Code: 1001 instead. Either way a query whose filter is pushed to a shard fails. Before the previous commit this site was safe only incidentally, because the second child existed, its FutureSetPtr was null, typeid_cast of a null pointer gave null, and the set_from_subquery guard skipped the block. The four local variants reach makeASTFunction with arguments built from node->children, so the predicate is written back as one-argument SQL such as HAVING inIgnoreSet(x). The receiving shard resolves that text and src/Analyzer/Resolve/resolveFunction.cpp throws NUMBER_OF_ARGUMENTS_DOESNT_MATCH for any isNameOfInFunction name, so the distributed query fails. Declare such a node non-convertible to AST instead, which is the mechanism this function already uses for lambdas and for captures three lines above: node_to_ast[node] = nullptr. Its existing handling then applies unchanged. The parent's has_all_args goes false; an enclosing and() whose polarity is known positive drops just that child, which is the invariant the function was hardened for in #113445; and if the whole predicate is the IgnoreSet call the function returns nullptr and addFilters adds no filter. This is sound because the AST is only a pushdown optimization: omitting a conjunct can only widen what the shard returns, the initiator still applies the whole filter, and an IgnoreSet call evaluates to 0 for every row anyway, so no pruning is lost even in principle. The bail sits in the single argument walk that all three addFilters call sites funnel through, so it covers the plain, the external-tables GLOBAL and the parallel-replicas paths at once. It fires only when isNameOfInFunction accepts the name and the name ends with IgnoreSet. isNameOfInFunction accepts sixteen names, of which exactly eight end that way, so the walk is byte-identical in behaviour for every DAG that contains no IgnoreSet call. The regression test gains the remote arms, a plan-shape assertion that is true only when the call has a single operand, a wrapper-type matrix whose output is byte-identical to pristine master, an assertion that a filter mixing a convertible conjunct with an IgnoreSet call still pushes the convertible one to the shard, and a paired serialize_query_plan round trip over wrapped operands. Co-Authored-By: Claude Opus 5 <[email protected]> (cherry picked from commit 64f2f5b of #122130)
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes51 object files changed (+95.12 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units775 translation units recompiled, 5750 s compile time in total, 775 of them have a recent master baseline. |
…as the initiator's user The `ON CLUSTER` mutation precheck rejected every `IN` operand missing on the initiator with `UNKNOWN_TABLE`. That is needed only when the workers run the query under the DDL worker's own context. With `distributed_ddl_use_initial_user_and_roles` enabled and an entry format which carries the initiator's user (`distributed_ddl_entry_format_version` 8 and above), the worker runs the query as the submitting user and roles and applies the same `Set` row-policy check to its own objects, so the initiator now leaves an unresolved operand to the worker in that case. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds access and row-policy checks for Set tables used on the right side of IN, adds mutation checks for Replicated and ON CLUSTER DDL, and handles IgnoreSet variants in the planner. None of this touches the per-row execution path of the clickbench or tpch_adapted_1_official SELECTs. The only flagged query, clickbench Q34 (+5.4%), stays not_sure because the two tests disagree, and its total CPU time is unchanged. The baseline for this query was also refit after a recent shift on master, so treat the wall-time delta as unrelated to this change. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
The DDL worker of a `Replicated` database runs the mutation with full access. Before enqueueing, the initiator only ran `checkNoRowPolicyForSetOperands`, which sees the `IN` operands written in the query but not those inside a view. So a user whose row policy hides rows of a `Set` table could still delete or update by them with `k IN (SELECT number FROM v)`, where `v` is an `INVOKER` view over `number IN set_table`. Before `ALTER ... DELETE`, `ALTER ... UPDATE`, `DELETE` or `UPDATE` is enqueued, analyze it as the submitting user, as `MutationsInterpreter::validate` already does for a table in a local database. This also means that such a mutation now needs `SELECT` on the tables its subqueries read, as it does in a local database. The determinism check is left to the worker, because the lightweight `UPDATE` and `DELETE` paths never run it. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the initiator In the default mode, the other hosts run an `ON CLUSTER` query without the initiating user, so the initiator checks each `IN` table for a row policy itself. When the table does not exist on the initiator, the query failed with "Table ... does not exist", for any engine and even if the other hosts have the table. Say why the initiator needs the table, and name the two ways out: run the query on a host that has it, or enable `distributed_ddl_use_initial_user_and_roles` with `distributed_ddl_entry_format_version` of at least 8. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… user The check added in 9865902 analyzed a mutation in the session of the submitting user before the mutation was enqueued. The DDL worker then ran it with full access, and the two could see different objects. A temporary table with the name of the `Set` table hid the `Set` table from the check, but not from the worker. A scalar subquery in an `UPDATE` assignment read a view whose body the analysis did not plan. The check also ran before the replica applied the earlier entries of the queue. So it refused an `UPDATE` of a column that an earlier `ADD COLUMN` from another replica had added. Remove that check. Instead, the initiator runs its own copy of an `ALTER ... DELETE`, `ALTER ... UPDATE`, `DELETE` or `UPDATE` entry as the submitting user with the current roles, the same way an `ON CLUSTER` worker runs with `distributed_ddl_use_initial_user_and_roles`. This run comes after the replica has caught up, sees no session temporary tables, and applies the checks of a local database. The other replicas run only the entries that succeeded on the initiator, so they keep the full access of the worker. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…user `MutationsInterpreter::validate` runs the scalar subqueries of the predicates as the submitting user, in `prepareQueryAffectedQueryTree`. The assigned values reach only the query plan, which analyzes a scalar subquery without planning the view that it reads. So a heavy `ALTER TABLE ... UPDATE v = (SELECT max(number) FROM view)` passed validation even when the view reads a `Set` table with a row policy, and the background mutation then read the view with full access. This happened for a local table, and for a `Replicated` one, where the initiator now validates as the submitting user. Analyze the assigned values in the same way as the predicates. Their scalar subqueries now run once more during validation, as those of the predicates already do. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A worker runs an `ON CLUSTER` query as the initiating user only if the server setting is enabled on the worker too, so the advice in the `UNKNOWN_TABLE` message has to name every host. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
e799360 analyzed each assigned value as a whole. Full analysis folds the constants of the value, so `UPDATE v = now(exists(SELECT 1023)) WHERE NULL` failed validation with a type error, although it touches no rows and was accepted before (`03925_exists_with_mutations_execute_on_initator`). The values also skipped the normalization of set operations, so a `UNION` in a subquery failed with "UNION mode UNION_DEFAULT must be normalized" (`04560_union_subqueries_in_mutations`). Analyze only the parts of a value that read a subquery: a scalar subquery, or an `IN` or `exists` call on a subquery. Normalize their set operations first, as for the predicates. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…heck 3829d82 lifted a whole `IN` call out of the assigned value into the `SELECT` that `validate` analyzes. The left side of the call can use the parameter of a lambda or an alias defined next to it, and neither exists in that `SELECT`. So a valid heavy `ALTER TABLE ... UPDATE` failed with `UNKNOWN_IDENTIFIER`, for example `v = arrayExists(x -> x IN (SELECT 3), [k])` or `v = ((k + 1) AS kk) * (kk IN (SELECT 3))`. Lift only the subqueries. The set of an `IN` or `exists` call becomes `exists(subquery)`, because it may return more than one row; a scalar subquery stays as is. Both still run the subqueries nested in them as the submitting user. Also correct the comment: a failing subquery fails the validation even if no row matches, as in the predicate. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ated` mutation aed04cb passed the current roles of the session as external roles to `setUser`. That turned the default roles of the user back on after `SET ROLE`, and dropped the grant limit and the expiry of the credential. So the initiator could refuse a mutation that the same session runs on a local table, or accept one that the credential may not run. Keep the submitting context in the task and replay its identity the way `AsynchronousInsertQueue` does: `setUser` with the external roles, the grant limit and the expiry, then the current roles of the session without the grant check. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…alues a79522b put the subqueries of all commands into one `SELECT` and left out the rest of each assigned value. But a subquery can use an alias that is defined outside it: in the same value, in another assignment, or in the `WHERE` of the command. Two commands can also define the same alias. So valid heavy `ALTER TABLE ... UPDATE` statements failed with `UNKNOWN_IDENTIFIER` or `MULTIPLE_EXPRESSIONS_FOR_ALIAS`, for example `v = (5 AS c) + (SELECT c)` or `v = (SELECT c) WHERE k = (2 AS c)`. Analyze one `SELECT` per command, with the predicate of the command as its `WHERE`. Lift the aliased expressions outside of lambdas together with the subqueries. A command whose assigned values have no subquery is skipped. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The comment said "the whole identity", but the client info, such as the user name in `system.query_log`, is not replayed. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
This reverts 1e105f9, a79522b, 3829d82 and e799360. They made `MutationsInterpreter::validate` run the subqueries of the assigned values as the submitting user. To do that, they re-analyzed parts of each value outside of the scope that the mutation gives them. Every version refused some valid heavy `ALTER TABLE ... UPDATE`. The causes were the names of lambdas and aliases, aliases repeated across assignments, commands or the `WHERE`, and constants that fail to fold although no row matches. The last version also ran the sets of `IN` calls when the mutation was submitted. So the gap that they addressed stays open, as it is at the PR head: a heavy `ALTER TABLE ... UPDATE v = (SELECT ... FROM view)` can read a `Set` table with a row policy through the view, on a local and on a `Replicated` database. A lightweight `UPDATE` does not have this gap. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
No logic changes. Only comments and the text of one exception change. `DDLTask.cpp`: the comment in `makeQueryContext` no longer lists the arguments of `setUser`. It now says why the current roles are set without the grant check: they include the external roles, which are not granted locally. `DDLTask.h`: the comment on `submitting_user_context` fits on one line. `QueryFlags.h`: the long first sentence of the comment on `run_as_submitting_user` is now three short sentences. It keeps every fact. `MutationsInterpreter.cpp`: the `UNKNOWN_TABLE` message in `checkNoRowPolicyForSetOperands` first says that the other hosts do not run the query as the initiating user. Then it says that the initiator must check the table. This removes an unclear "it". The substrings that the integration test asserts stay the same. `test_set_engine_row_policy_serialized_plan/test.py`: the comment of the view case says what the DDL worker must do. The comment of the temporary table case no longer has a comma splice. The comment of the `ON CLUSTER` case says that the initiator refuses a `MergeTree` table too, because it cannot see the engine of a table that it does not have. Related: #122141 Co-Authored-By: Claude Opus 5.5 <[email protected]>
| && function->arguments->children.size() == 2) | ||
| { | ||
| const auto & right_operand = function->arguments->children[1]; | ||
| if (const auto * table_identifier = right_operand->as<ASTTableIdentifier>()) |
There was a problem hiding this comment.
This helper still only sees the surface IN syntax where the right-hand side is a table identifier. That leaves a real bypass in the mutation paths that now rely on it instead of a submitting-user execution.
Two concrete cases:
... ON CLUSTER ... WHERE k IN (SELECT number FROM invoker_view_over_set)in the default mode.additional_access_checkis the only submitting-user guard before the DDL worker runs with full access, but the view body's... IN set_tableis not in this AST, so the query is enqueued and the worker reads theSettable unfiltered.- Heavy
ALTER TABLE ... UPDATE col = (SELECT ... FROM invoker_view_over_set)on local orReplicatedtables. This helper sees only the outer view name, andMutationsInterpreter::validateis still built withSettings(false), soprepareMutationStageskeepsexecute_scalar_subqueries = falseand never executes the assigned-value scalar subquery as the submitting user.
So the PR's new mutation guarantee is still bypassable by hiding the Set behind a view/subquery. Can we add a real submitting-user validation for those forms, or at least regressions for both before merging?
| if (auto supports = table->supportsLightweightUpdate(); !supports) | ||
| throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Lightweight updates are not supported. {}", supports.error().text); | ||
|
|
||
| checkNoRowPolicyForSetOperands(query_ptr, table_id.database_name, getContext()); |
There was a problem hiding this comment.
This foreground lightweight UPDATE path now uses the same fail-closed helper as the background/worker paths, but checkNoRowPolicyForSetOperands resolves the RHS through tryResolveTableIdentifierFromDatabaseCatalog, which ignores session temporary tables.
That means a session like CREATE TEMPORARY TABLE set_rp ...; UPDATE local_mt SET v = v + 1 WHERE k IN set_rp can now be checked against an unrelated persistent default.set_rp and fail with ACCESS_DENIED, even though the actual query would read the temporary table in the current session. The catalog-only lookup makes sense once the query is leaving the session (Replicated, ON CLUSTER, background ALTER ... UPDATE/DELETE), but here it changes the semantics of an ordinary local lightweight update.
|
@alexey-milovidov I've pushed a few changes to this PR and approved it from my side. Please take another look. If you don't like my changes, feel free to revert them. Merging is yours. What I changed:
Side effect: on Replicated, such a mutation now needs SELECT on the tables its subqueries read, same as local. Still open, same as before: ON CLUSTER in the default mode, and a heavy ALTER UPDATE whose value reads a view. Since some existing queries now fail, I also edited the changelog category to be |
Reverts #122140, i.e. reapplies #120312, together with the fix from #122130.
#120312 was reverted because the
*IgnoreSetfunctions left aColumnSetwith a nullFutureSetin theActionsDAG, which was dereferenced in the aggregation hash table cache key serialization (serializeConstant, STID 2060-5018 / 2060-4607) and in virtual column /PREWHEREfilter analysis. The fix does not build the set operand forIgnoreSetcalls at all, so they take the left operand alone (the shape the old analyzer already used), andtryBuildAdditionalFilterASTdoes not write such a call back asINsyntax when pushing a filter to a shard.On a
Replicateddatabase, the DDL worker runs each entry with full access. Now the initiator runs its own copy of anALTER ... DELETE,ALTER ... UPDATE,DELETEorUPDATEentry with the access rights of the submitting session. These are the user, the current and external roles, and the grant limit and expiry of the credential. The run starts after this replica has processed all earlier entries of the queue. It does not see the temporary tables of the session, so a temporary table with the same name cannot hide aSettable from it. It applies the same checks as a local database. The other replicas run only the entries that succeeded on the initiator.Known limitations:
ON CLUSTERin the default mode: the hosts do not run the mutation as the initiating user. The initiator checks only the tables that the query names on the right side ofIN. So it misses aSettable with a row policy when the query reads that table through a view, or when a temporary table with the same name hides it. To close this gap, enable the server settingdistributed_ddl_use_initial_user_and_roleson every host, and setdistributed_ddl_entry_format_versionto 8. Then every host runs the query as the initiating user and applies the row policies of that user.ALTER TABLE ... UPDATE, on any database: an assigned value such asv = (SELECT ... FROM view)can still read aSettable with a row policy through the view. The validation of the mutation does not run the scalar subqueries of the assigned values, and the background mutation runs with full access. A lightweightUPDATEdoes not have this gap. The behavior is the same as before this PR.Replicateddatabase: only the initiator runs the entry as the submitting user. The other replicas run it with full access, against their own database objects and row policies. These normally match those on the initiator.Closes: #122042
Related: #120312
Related: #122140
Related: #122130
CI reports: (the five existing Stress test links, unchanged)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A row policy on a
Settable was not applied on the right side ofIN. The query read the whole prebuilt set, including the rows that the policy hides. Such a query now fails withACCESS_DENIED, even when the policy is database-wide.IN set_tablenow requiresSELECTon all columns of the table. Before, the analyzer required onlySHOW COLUMNSon at least one column, and the old analyzer required nothing. On aReplicateddatabase, the initiator now runsALTER ... DELETE,ALTER ... UPDATE,DELETEandUPDATEas the submitting user. So these mutations get the same checks as on other databases. The checks also find aSettable that theWHEREcondition reads through a view. Such a mutation now needsSELECTon the tables that its subqueries read, and it counts twice against the query quota of the user. AnON CLUSTERALTER ... DELETE,ALTER ... UPDATE,DELETEorUPDATEnow fails if the right side of itsINis a table that does not exist on the initiator. Run such a query on a host that has the table. Or enable the server settingdistributed_ddl_use_initial_user_and_roleson every host, and setdistributed_ddl_entry_format_versionto at least 8.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/122141]
Version info
26.10.1.1105-master(included in26.10and later)