Skip to content

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

Merged
harikrishnan94 merged 13 commits into
ClickHouse:masterfrom
harikrishnan94:set-engine-row-policy
Sep 24, 2026
Merged

harikrishnan94 merged 13 commits into
ClickHouse:masterfrom
harikrishnan94:set-engine-row-policy

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Related: #115304

CREATE ROW POLICY on a Set-engine table succeeds and shows up in system.row_policies, but nothing applies it. The only reader of a Set table is the right side of IN, and that path takes the prebuilt set straight from StorageSet::getSet, so with a k = 1 policy over {1, 2} the query number IN set_table still returns both rows. Every other engine on the right of IN goes through a subquery and gets filtered.

There is nothing to fall back to. StorageSet has no read path (SELECT * FROM set_table throws NOT_IMPLEMENTED), so the query now fails with ACCESS_DENIED when a non-trivial SELECT filter applies, the same way #115304 handled mergeTreeIndex. The check is StorageSet::checkNoRowPolicy, called from 3 places: collectSets in the planner, the legacy ActionsVisitor path that mutations still use, and makeSetsFromStorage when a replica materializes a set from a serialized plan. ExpressionAnalyzer::isPlainStorageSetInSubquery had 0 callers and is removed.

Rejecting the policy at DDL time is not an option: a database-wide policy (ON db.*) is legitimate and also covers Set tables created after it. The test covers plain IN, GLOBAL IN, a key condition, ALTER TABLE ... DELETE (the only way to reach the legacy path now that enable_analyzer = 0 is rejected), an always-true policy, and a database-wide policy.

Cloud: StorageSharedSet derives from StorageSet, and the check runs before the SharedSet dispatch at both call sites, so the private engine is covered with no private-side change.

Breaking for anyone with a database-wide policy over a database that contains a Set table: those IN queries ran unfiltered before and throw now.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

A row policy on a Set-engine table was accepted but never applied: the right side of IN read the prebuilt set directly and returned the rows the policy hides. Such a query now fails with ACCESS_DENIED, because the Set engine has no read path that could filter the rows. Queries that used a Set table covered by a database-wide row policy ran unfiltered before and now throw.


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

Version info

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

…ies to it

A row policy on a `Set`-engine table was accepted and listed in `system.row_policies`, but
the only consumer of such a table, the right-hand side of `IN`, reads the prebuilt set directly
and never sees the filter, so every hidden element stayed testable. The engine has no read path
that could apply the policy, so such a query now fails with `ACCESS_DENIED`, the same way
`mergeTreeIndex` fails closed for a policed source table. The check runs in the planner, in the
legacy expression analyzer that mutations still use, and when a replica materializes a set
from a serialized plan. `ExpressionAnalyzer::isPlainStorageSetInSubquery` had no callers and
is removed.

Closes: ClickHouse/clickhouse-private#70502
Related: ClickHouse#115304
The legacy `IN` path tested the `StorageSet` cast twice around the Cloud `SharedSet` block. One
block now runs the row-policy check and both dispatches. The comments and the error message drop
the invented wording and read as short sentences. No behaviour change.
@harikrishnan94 harikrishnan94 added comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Sep 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c0596ea]

Summary: ✅


AI Review

Summary

This PR closes most of the StorageSet row-policy gaps across the analyzer, legacy mutation, replicated mutation, and serialized-plan worker paths, and it now requires full-column SELECT before a prebuilt Set can be used. I still see one blocker in the new ON CLUSTER initiator-side precheck: it treats the initiator's local lookup of the RHS table as authoritative, but IN rhs_table is rebound on each worker. That changes valid remote-only cases into UNKNOWN_TABLE and can still miss a worker-side Set when the catalogs differ.

Missing context / blind spots
  • ⚠️ The public checkout still does not include the private StorageSharedSet implementation, so the Cloud-coverage claim in the PR body is still not verifiable end-to-end here. The public call sites suggest the same guard will run, but a Cloud-side regression test or linked CI result for x IN shared_set would close the gap.
Findings

❌ Blockers

  • [src/Interpreters/MutationsInterpreter.cpp:139] The clustered mutation fix now resolves IN rhs_table against the initiator's local catalog and treats that result as authoritative. That is not a valid proxy for what the worker will execute. ALTER / UPDATE / DELETE ... ON CLUSTER worker_only ... IN remote_mt now throws UNKNOWN_TABLE when remote_mt exists only on the worker, and the opposite mismatch is worse: if the initiator has a local non-Set homonym while the worker resolves the same name to a Set, the new guard is skipped and the worker still executes under its default context when distributed_ddl_use_initial_user_and_roles = 0. Suggested fix: do not decide ON CLUSTER safety from the initiator's local lookup alone; either run the source-table check on each worker under the submitting access snapshot, or fail closed only after proving that the worker-side object identity matches what was checked on the initiator.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make the ON CLUSTER Set precheck independent of the initiator's local RHS resolution, or reject only with a fail-closed rule that cannot misclassify worker-side source tables.

LLVM Coverage Report

Measured on commit c0596ea.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 163/181 (90.06%) · Uncovered code

Full report · Diff report

@ahmadov

ahmadov commented Sep 22, 2026

Copy link
Copy Markdown
Member

@antaljanosbenjamin are you currently reviewing this PR? If not, could you please assign to me?

@antaljanosbenjamin

Copy link
Copy Markdown
Member

Sorry, I was on holiday. I can take a look at it now

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

The code looks good, however is there any occasion when

@tavplubix

Copy link
Copy Markdown
Member

Refuse a Set table on the right side of IN when a row policy applies to it
CREATE ROW POLICY on a Set-engine table succeeds and shows up in system.row_policies, but nothing applies it. The only reader of a Set table is the right side of IN

Does it mean that a Set table with a row policy becomes completely unusable? Should we disallow creating it instead?

Also, please check if we have other table engines that cannot apply row policies

@alexey-milovidov

alexey-milovidov commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Does it mean that a Set table with a row policy becomes completely unusable?

That's ok.

Also, please check if we have other table engines that cannot apply row policies

I suspect Join and Dictionary, EmbeddedRocksDB, KeeperMap, SystemZooKeeper.

@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Sep 23, 2026
Cover serialized query plans when only the remote worker has a row policy. The control query proves the initiator can plan it before the worker rejects it with `ACCESS_DENIED`.
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 756458be-9f5a-4cdc-bf79-ac183595d4cc
  • MIRAI run: 3c13655a-1b6f-4fcf-9f91-6610cd7aabd8
  • PR check IDs:
    • clickbench_1593189_1790220892
    • clickbench_1593195_1790220892
    • clickbench_1593202_1790220892
    • tpch_adapted_1_official_1593212_1790220892
    • tpch_adapted_1_official_1593223_1790220892
    • tpch_adapted_1_official_1593260_1790220892

@tavplubix

Copy link
Copy Markdown
Member

Does it mean that a Set table with a row policy becomes completely unusable?

That's ok.

Yes, but it would be slightly better to throw on CREATE ROW POLICY for unsupported engines

Also, please check if we have other table engines that cannot apply row policies

We also have SharedSet

Run the initiator-side policy check before `ALTER` and `UPDATE` queries are enqueued for `ON CLUSTER` execution.

PR: ClickHouse#120312
Review: ClickHouse#120312 (comment)
Resolve mutation `Set` operands through the analyzer access path and defer clustered policy checks until the standard cluster and target privileges pass.

ClickHouse#120312
ClickHouse#120312 (comment)
Copilot AI lite review requested due to automatic review settings September 23, 2026 21:55

Copilot AI 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.

Note

Copilot was unable to run its full agentic suite in this review.

Copilot review overview

Review effort: Lite
Findings: 1 Medium severity · 2 Low severity

Open (3)
What changed in this PR

This PR closes a security/RBAC gap where row policies defined on Set-engine tables were silently ignored when the table was used on the right-hand side of IN. The fix refuses such queries (and related mutation paths) with ACCESS_DENIED whenever a non-trivial row policy applies, since StorageSet has no read path to enforce filtering.

Changes:

  • Add StorageSet::checkNoRowPolicy() and invoke it from planner set collection, legacy ActionsVisitor set building, and serialized-plan set materialization.
  • Introduce an additional_access_check hook for executeDDLQueryOnCluster() and run the Set row-policy check pre-enqueue for ON CLUSTER mutations (UPDATE/DELETE/ALTER ... DELETE/UPDATE).
  • Add stateless and integration tests for plain IN, GLOBAL IN, mutations, database-wide policies, and serialized query plan execution across nodes.
File Description
src/​Storages/​StorageSet.{h,cpp} Adds and implements the row-policy refusal check for Set tables.
src/​Planner/​CollectSets.cpp Enforces the refusal early in the analyzer/planner path.
src/​Interpreters/​ActionsVisitor.cpp Enforces the refusal in the legacy set-building path used by mutations.
src/​Processors/​QueryPlan/​SetsSerialization.cpp Enforces the refusal when materializing sets from serialized plans on replicas.
src/​Interpreters/​executeDDLQueryOnCluster.{h,cpp} Adds a hook to run additional authorization checks before enqueueing distributed DDL.
src/​Interpreters/​MutationsInterpreter.{h,cpp} Adds helper to detect IN set_table in mutation ASTs and enforce the refusal in submitting context.
src/​Interpreters/​Interpreter{Update,Delete,Alter}Query.cpp Invokes the mutation-side check locally and for ON CLUSTER.
src/​Interpreters/​ExpressionAnalyzer.{h,cpp} Removes unused isPlainStorageSetInSubquery() helper.
tests/​queries/​0_stateless/​05218_set_engine_row_policy.* Adds stateless regression coverage for IN/GLOBAL IN and policy scopes.
tests/​integration/​test_set_engine_row_policy_serialized_plan/​* Adds integration coverage for serialized plans, replicas, and ON CLUSTER mutation authorization ordering.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +42 to +47
def test_worker_checks_set_row_policy(started_cluster):
for node in (initiator, worker):
node.query("CREATE TABLE set_rp (k UInt64) ENGINE = Set")
node.query("INSERT INTO set_rp VALUES (1), (2)")
node.query("CREATE TABLE data_rp (k UInt64) ENGINE = MergeTree ORDER BY k")
node.query("INSERT INTO data_rp VALUES (1), (2)")
if (!storage_set)
throw Exception(ErrorCodes::INCORRECT_DATA, "Table {} is not a StorageSet", set.storage_name);

/// The initiator ran this check against its own policies; the replica's may differ.
if (row_policy_filter && !row_policy_filter->isAlwaysTrue())
throw Exception(ErrorCodes::ACCESS_DENIED,
"Cannot use table {} on the right side of IN because a row policy applies to it. "
"The Set engine has no read path that could filter the rows",
{
auto resolved = IdentifierResolver::tryResolveTableIdentifierFromDatabaseCatalog(
Identifier(table_identifier->name_parts), context);
if (!resolved.resolved_identifier && throw_if_unresolved)

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 makes the clustered mutation paths treat the initiator's local catalog as authoritative for the RHS table name, but IN rhs_table is resolved independently on each worker. That creates both a false positive and a false negative.

For example, ALTER TABLE dst ON CLUSTER worker_only DELETE WHERE k IN remote_mt now throws UNKNOWN_TABLE if remote_mt exists only on the worker, even when it is an ordinary MergeTree table and no Set fast path is involved. The opposite mismatch is worse: if the initiator has a local non-Set homonym while the worker resolves the same name to a Set, this helper skips the guard entirely and the worker still executes under its default context when distributed_ddl_use_initial_user_and_roles = 0.

So the new precheck is only sound if the initiator can prove it is looking at the same source object the worker will use. Suggested fix: do not make the initiator-local lookup authoritative for ON CLUSTER mutations. Either run the source-table check on each worker under the submitting access snapshot, or fail closed only after proving the worker-side object identity instead of throwing/skipping based on the initiator's catalog alone.

@harikrishnan94
harikrishnan94 added this pull request to the merge queue Sep 24, 2026
Merged via the queue into ClickHouse:master with commit 875485a Sep 24, 2026
521 of 522 checks passed
@harikrishnan94
harikrishnan94 deleted the set-engine-row-policy branch September 24, 2026 13:04
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 24, 2026
@alexey-milovidov alexey-milovidov added invalid 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-critical-bugfix pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Sep 25, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This was reverted in #122140 because it causes a segmentation fault on master, found by the AST fuzzer in the stress tests (STID 2060-5018 / 2060-4607): 14 failures across 9 stress test configurations since 2026-09-24, both on master and in PRs.

Commit c0596ea (Skip IgnoreSet operand preparation) stopped registering a set for the *IgnoreSet functions, but PlannerActionsVisitor still materializes the set operand. The ColumnSet in the ActionsDAG then holds a null FutureSet, which serializeConstant dereferences when computing the aggregation hash table cache key (ActionsDAG.cpp:4744, called from calculateHashTableCacheKeys). The same null pointer is dereferenced in virtual column / PREWHERE filter analysis (#122042).

Example queries:

SELECT notNullInIgnoreSet([], []) GROUP BY 1, '%system.processes%'
SELECT count() FROM numbers(10) GROUP BY inIgnoreSet(number, (1, 2, 3))

Reports:

The change is reapplied together with the fix from #122130 in #122141. The cherry-picks of this PR to the release branches (#121983, #121984, #121985, #121986) carry the same crash and must not be merged as is.

@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 25, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 25, 2026
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md.

Changelog-revert: 119274 118919 Revert "Carry the mutation version onto a rewritten lightweight `DELETE`"
Changelog-revert: 119306 119274 Revert "Revert "Carry the mutation version onto a rewritten lightweight `DELETE`""
Changelog-revert: 119334 117356 Revert "Unify the spill trigger for hash joins"
Changelog-revert: 119335 119334 Revert "Revert "Unify the spill trigger for hash joins""
Changelog-revert: 121135 118279 Revert "Test the ESCAPE route into the ngram LIKE-pattern tokenizer"
Changelog-revert: 121136 121135 Revert "Revert "Test the ESCAPE route into the ngram LIKE-pattern tokenizer""
Changelog-revert: 121258 118216 Revert "Do not invert an ordered comparison that can see a `NaN` in the CNF form"
Changelog-revert: 121298 117578 Revert "Bound the docker buildx retry ladder by wall clock, not by the timeout divisor"
Changelog-revert: 121443 114465 Revert "Fix an error reading an Iceberg table whose `current-snapshot-id` is JSON null"
Changelog-revert: 121477 121096 Revert "Trim `test_max_bytes_ratio_before_external_distinct` to fit the client timeout"
Changelog-revert: 121901 121869 Revert "docs(managed-postgres): updated Private Service Connect"
Changelog-revert: 122110 118223 Revert "Correct nightly coverage selection and share PR test manifests"
Changelog-revert: 122140 120312 Revert "Refuse a `Set` table on the right side of `IN` when a row policy applies to it"
Changelog-deleted-entry: 114465 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed an error when reading an Iceberg table whose `current-snapshot-id` is JSON null, which some writers emit for a table with no current snapshot. [#114465](#114465) ([Shaohua Wang](https://github.com/tiandiwonder)).
Changelog-deleted-entry: 118216 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * Fixed `convert_query_to_cnf = 1` silently dropping rows with a `NaN` in a floating point column: the conversion rewrote `NOT (x < c)` into `x >= c`, which is not an equivalent condition for `NaN`. [#118216](#118216) ([Alexey Milovidov](https://github.com/alexey-milovidov)).
Changelog-deleted-entry: 118223 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Correct nightly coverage selection and share PR test manifests. [#118223](#118223) ([Nikita Fomichev](https://github.com/fm4v)).
Changelog-deleted-entry: 120312 [Bug Fix (user-visible misbehavior in an official stable release)] [raw] * A row policy on a `Set`-engine table was accepted but never applied: the right side of `IN` read the prebuilt set directly and returned the rows the policy hides. Such a query now fails with `ACCESS_DENIED`, because the `Set` engine has no read path that could filter the rows. Queries that used a `Set` table covered by a database-wide row policy ran unfiltered before and now throw. [#120312](#120312) ([Harikrishnan Prabakaran](https://github.com/harikrishnan94)).
Changelog-deleted-entry: 121096 [NOT FOR CHANGELOG / INSIGNIFICANT] [raw] * Sized `test_max_bytes_ratio_before_external_distinct` to fit the integration harness's 600 second per-query timeout. [#121096](#121096) ([Groene AI](https://github.com/groeneai)).
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 29, 2026
…ress

Picks up ClickHouse#122140, the revert of ClickHouse#120312. That change left a null set in
the plan for the *IgnoreSet functions, and the stress test crashed on it
in serializeConstant. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 invalid 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.

9 participants