Skip to content

Revert "Revert "Refuse a Set table on the right side of IN when a row policy applies to it"" - #122141

Merged
alexey-milovidov merged 17 commits into
masterfrom
revert-122140-revert-120312-set-engine-row-policy
Sep 30, 2026
Merged

alexey-milovidov merged 17 commits into
masterfrom
revert-122140-revert-120312-set-engine-row-policy

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Reverts #122140, i.e. reapplies #120312, together with the fix from #122130.

#120312 was reverted because the *IgnoreSet functions left a ColumnSet with a null FutureSet in the ActionsDAG, which was dereferenced in the aggregation hash table cache key serialization (serializeConstant, STID 2060-5018 / 2060-4607) and in virtual column / PREWHERE filter analysis. The fix does not build the set operand for IgnoreSet calls at all, so they take the left operand alone (the shape the old analyzer already used), and tryBuildAdditionalFilterAST does not write such a call back as IN syntax when pushing a filter to a shard.

On a Replicated database, the DDL worker runs each entry with full access. Now the initiator runs its own copy of an ALTER ... DELETE, ALTER ... UPDATE, DELETE or UPDATE entry 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 a Set table 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 CLUSTER in 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 of IN. So it misses a Set table 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 setting distributed_ddl_use_initial_user_and_roles on every host, and set distributed_ddl_entry_format_version to 8. Then every host runs the query as the initiating user and applies the row policies of that user.
  • Heavy ALTER TABLE ... UPDATE, on any database: an assigned value such as v = (SELECT ... FROM view) can still read a Set table 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 lightweight UPDATE does not have this gap. The behavior is the same as before this PR.
  • Replicated database: 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):

  • Backward Incompatible Change

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

A row policy on a Set table was not applied on the right side of IN. The query read the whole prebuilt set, including the rows that the policy hides. Such a query now fails with ACCESS_DENIED, even when the policy is database-wide. IN set_table now requires SELECT on all columns of the table. Before, the analyzer required only SHOW COLUMNS on at least one column, and the old analyzer required nothing. On a Replicated database, the initiator now runs ALTER ... DELETE, ALTER ... UPDATE, DELETE and UPDATE as the submitting user. So these mutations get the same checks as on other databases. The checks also find a Set table that the WHERE condition reads through a view. Such a mutation now needs SELECT on the tables that its subqueries read, and it counts twice against the query quota of the user. An ON CLUSTER ALTER ... DELETE, ALTER ... UPDATE, DELETE or UPDATE now fails if the right side of its IN is a table that does not exist on the initiator. Run such a query on a host that has the table. Or enable the server setting distributed_ddl_use_initial_user_and_roles on every host, and set distributed_ddl_entry_format_version to at least 8.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1105-master (included in 26.10 and later)

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eb6d3e5]

Summary: ✅


AI Review

Summary

This PR re-applies the Set-engine row-policy guard and fixes the IgnoreSet planner fallout. The direct Set checks themselves look reasonable, but the new mutation coverage is still incomplete: one path still bypasses the submitting-user policy check through views/subqueries, and another path now over-rejects valid foreground lightweight updates.

Findings

❌ Blockers

  • [src/Interpreters/MutationsInterpreter.cpp:136] checkNoRowPolicyForSetOperands only inspects explicit IN <table> syntax. ... ON CLUSTER ... WHERE k IN (SELECT number FROM invoker_view_over_set) still bypasses the new guard in the default mode, because additional_access_check is the only submitting-user check before the DDL worker runs with full access and the view body's IN set_table is never in this AST. The same gap remains for heavy ALTER TABLE ... UPDATE col = (SELECT ... FROM invoker_view_over_set) on local and Replicated tables: the helper sees only the outer view name, and MutationsInterpreter::validate still runs with Settings(false), so prepareMutationStages keeps execute_scalar_subqueries = false and never executes the assigned-value scalar subquery as the submitting user. Suggested fix: add a real submitting-user validation that plans or executes these hidden subqueries, and add regressions for both concrete forms.

⚠️ Majors

  • [src/Interpreters/InterpreterUpdateQuery.cpp:187] The foreground lightweight UPDATE path now uses the same catalog-only helper as the background/worker paths. Because checkNoRowPolicyForSetOperands resolves names through tryResolveTableIdentifierFromDatabaseCatalog, it ignores session temporary tables. A query such as CREATE TEMPORARY TABLE set_rp ...; UPDATE local_mt SET v = v + 1 WHERE k IN set_rp can therefore be denied against an unrelated persistent default.set_rp, even though the actual query would read the temporary table in the current session. Suggested fix: keep the catalog-only lookup for paths that lose session state, but let the foreground lightweight path validate against normal query resolution.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit eb6d3e5.

Metric Baseline Current Δ
Lines 87.90% 87.90% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 218/235 (92.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 25, 2026
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)
Condense the argument_types_match note to a one-line invariant: an IgnoreSet node has one child against two expected types.

(cherry picked from commit 302ee40 of #122130)
@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing eb6d3e5e6 with master 3f1c583fe (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8155a2295; 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

51 object files changed (+95.12 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/MutationsInterpreter.cpp.o 852.64 KiB 897.41 KiB +44.77 KiB (+5.25%)

716 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

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

Job report

…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]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-critical-bugfix labels Sep 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 35 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1136 1197 +5.4% <0.0001 aggregation: Q34 is a large GROUP BY with no IN over a Set table, so the new row-policy checks and IgnoreSet handling never run per row. Total CPU is flat (16461 ms vs 16441 ms), so the +5.4% wall-time shift is not backed by extra work.

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
  • StressHouse run: 8f831472-de2f-4b0f-a4a7-c871984959be
  • MIRAI run: bd09bb6a-42db-472f-b350-c39226e1f3be
  • PR check IDs:
    • clickbench_2369960_1790681795
    • clickbench_2369966_1790681795
    • clickbench_2369972_1790681795
    • tpch_adapted_1_official_2369983_1790681795
    • tpch_adapted_1_official_2369993_1790681795
    • tpch_adapted_1_official_2370030_1790681795

harikrishnan94 and others added 8 commits September 28, 2026 22:24
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]>
harikrishnan94 and others added 4 commits September 29, 2026 12:55
…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]>

@harikrishnan94 harikrishnan94 left a comment

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.

LGTM

&& function->arguments->children.size() == 2)
{
const auto & right_operand = function->arguments->children[1];
if (const auto * table_identifier = right_operand->as<ASTTableIdentifier>())

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.

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_check is the only submitting-user guard before the DDL worker runs with full access, but the view body's ... IN set_table is not in this AST, so the query is enqueued and the worker reads the Set table unfiltered.
  • Heavy ALTER TABLE ... UPDATE col = (SELECT ... FROM invoker_view_over_set) on local or Replicated tables. This helper sees only the outer view name, and MutationsInterpreter::validate is still built with Settings(false), so prepareMutationStages keeps execute_scalar_subqueries = false and 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());

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.

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.

@harikrishnan94

harikrishnan94 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

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

  1. On a Replicated database, the DDL worker runs the mutation with full access. So a Set behind a view, or behind a temp table with the same name, got past the check. Now the initiator runs its own copy of the mutation as the user who sent it, so it gets the same checks as on a local database.
  2. The ON CLUSTER error for an IN table that's missing on the initiator now says why it refuses and what to do.

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 Backward Incompatible Change.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 30, 2026
Merged via the queue into master with commit 484e8f0 Sep 30, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the revert-122140-revert-120312-set-engine-row-policy branch September 30, 2026 20:32
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 30, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 30, 2026
@alexey-milovidov alexey-milovidov added minor Priority: minor and removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-synced-to-cloud The PR is synced to the cloud repo pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Sep 30, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. minor Priority: minor pr-improvement Pull request with some product improvements 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.

Server crashes with SIGSEGV on inIgnoreSet in a WHERE/PREWHERE filter

5 participants