Skip to content

Reject CREATE ROW POLICY and ALTER ROW POLICY whose filter cannot be applied to an existing table - #126643

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:row-policy-filter-checked-at-create
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:row-policy-filter-checked-at-create

Conversation

@groeneai

@groeneai groeneai commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

CREATE ROW POLICY and ALTER ROW POLICY now analyze the USING condition against the existing tables the policy is for (every existing table of the database for ON db.*) and fail if it cannot be applied to one of them, for example because it uses a column the table does not have, instead of storing a policy that makes every read of that table fail.

Description

Related: #126169 (requested in #126169 (comment))
Related: #121944 (the ALTER TABLE side)

CREATE/ALTER ROW POLICY checked the filter only syntactically; it is first resolved against a table when the table is read. So CREATE ROW POLICY p ON db.t USING nosuchcol = 1 TO ALL was accepted, and every later read of db.t by its users failed with UNKNOWN_IDENTIFIER. An ON db.* policy broke every table lacking the column (as a leaked 02703 policy did in the Upgrade check of #126078).

The policy DDL now resolves each new filter with the read-time helper (buildFilterQueryTree) against every existing table it is for, in the creator's session (agreed in #126169 (comment)), and, as a read would, rejects aggregate and window functions and a result type unusable as a filter. The analyzer's error is kept, naming the policy and the table.

Not checked: filters that read another table or a dictionary (a subquery, a table on the right of IN, dictGet, joinGet, ..., also via an ALIAS column), resolved against the reader's current database; tables created later; parameterized views; tables of databases with an external engine (MySQL, PostgreSQL, ...); tables whose columns the creator cannot see (nothing is disclosed); ON CLUSTER hosts that do not run the statement as the initiator's user. Persisted policies are not checked and keep loading after restart, restore, upgrade.

Behaviour change: a policy created before ALTER TABLE ADD COLUMN of the column it uses now fails; add the column first.

Validation: new tests 05407 and 05408 (a data lake schema changed outside the table object), the row policy integration tests and all stateless tests that create a row policy; two that create an unresolvable filter on purpose are adjusted.

🤖 Generated with Claude Code


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

groeneai and others added 4 commits October 19, 2026 01:53
CREATE/ALTER ROW POLICY checked the USING filter only syntactically. The
filter is first resolved against a table when the table is read, so a
policy using a column the table does not have was stored, and every read
of the table by the policy's users failed with UNKNOWN_IDENTIFIER (for
ON db.*, every table of the database lacking the column).

The policy DDL now analyzes each new filter with buildFilterQueryTree, the
helper reads use, against every existing table it is for, in the
creator's session, and rejects aggregate, window and GROUPING functions
and a result type that cannot be used as a filter, as a read would.

- Filters that read another table or a dictionary (subquery, IN with a
  name that is not a column of the table, IN with a table function,
  dictGet/joinGet and the other functions that resolve a dictionary or
  table while being analyzed) are not checked: those names resolve
  against the reader's current database. They are classified after SQL
  UDF calls are expanded, so a UDF parameter is judged by its argument.
- Only tables whose columns the creator may see (SHOW COLUMNS or SELECT
  at table level, through the whole Alias chain) are checked, decided by
  name before a table is waited for or opened, so success, failure and
  the analyzer's hints disclose nothing else.
- Only in a user session: an ON CLUSTER host checks as the creator only
  when it runs the statement as the initiator's user.
- A not yet created lazy or table-function proxy is checked against a
  StorageDummy of its declared columns when the filter names only stored
  columns (the dummy differs from the real storage only for other names);
  otherwise against the real table, as its first read would.
- Names the statement leaves untouched (IF NOT EXISTS of an existing
  policy, ALTER IF EXISTS of a missing one) are not checked.
- Persisted, restored and replicated policies are not checked and keep
  loading.

04368 now creates its projection-only policy before the table; 05228 uses
USING 0, which still empties the projection when the policy is wrongly
applied to the projection calculation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A data lake table object keeps the columns it saw at its last read, and a
read refreshes them from the latest snapshot before resolving anything
(IdentifierResolver, DESCRIBE). The policy DDL analyzed the filter against
the cached columns, so a column added to the table through another table
object was unknown to the check while every read resolved it, and a valid
policy was rejected with UNKNOWN_IDENTIFIER.

The check now takes the share lock, refreshes external dynamic metadata
and then takes the metadata snapshot, in the DESCRIBE order. The lock is
taken with tryLockForShare, so a table dropped or restarting meanwhile is
skipped under ON db.* (as system.columns does) instead of failing the
statement.

05407 gains the window function and GROUPING cases and a negative case for
the declared-columns check of a not yet loaded lazy table; 05408 covers the
data lake case. The docs paragraph now says that the server running the
statement checks it and that tables of external databases are not checked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y check

An `Alias` whose table was dropped has no columns, but its
updateExternalDynamicMetadataIfExists resolves the target table and throws
UNKNOWN_TABLE. Since the previous commit refreshed metadata before the
empty-columns skip, an `ON db.*` policy over a database holding such an
alias, or a policy on the alias itself, failed where master accepts it.
The check now returns for a storage whose cached metadata has no columns
before refreshing.

05407 gains the dangling `Alias` case and an `ON db.*` case that fails only
on the last table in name order, so a walk that stops after the first
table is caught.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The check decides which names to analyze from one existence lookup, but
CREATE built a policy for every name and ALTER IF EXISTS looked the names
up again, so a concurrent DROP or CREATE of the same policy could store a
filter that was never checked. CREATE now builds only the checked names
and ALTER IF EXISTS updates only them; single-session behaviour is
unchanged for every statement shape.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds: 5 agreed and fixed, 5 declined with evidence, 2 noted)
  • ❌ Data lake schema read stale at the DDL (own, round 1): the check refreshes external dynamic metadata before analyzing, as a read and DESCRIBE do. AGREE, fixed.
  • ❌ An Alias whose table was dropped made ON db.* fail with UNKNOWN_TABLE after that refresh (own + gate, round 2): a storage without columns is skipped before the refresh. AGREE, fixed, test case added.
  • ⚠️ IF [NOT] EXISTS decided which names to check from one lookup and wrote from another, so a concurrent CREATE/DROP of the same policy could store an unchecked filter (gate, round 3): the names written are now exactly the names checked. AGREE, fixed.
  • ⚠️ Window / GROUPING guards, the declared-columns path of lazy tables and the walk over every table of ON db.* had no failing case in the test: AGREE, cases added.
  • 💡 Docs: tables of external-engine databases are not checked; the check runs on the server that runs the statement. AGREE, docs narrowed.
  • ⚠️ A table-qualified IN operand or array-mode assignCentroid skips the check: DISAGREE, that is the behaviour before this PR, never a wrong rejection.
  • ⚠️ Replicated access storage peers are not checked: DISAGREE, peers deserialize the entity like restore and upgrade, which must keep loading.
  • 💡 A qualified column name loads a lazy table: DISAGREE, that is the cost of its first read, never a wrong verdict.
  • ⚠️ A not yet loaded lazy data lake table is checked against its stored columns: DISAGREE, a read analyzes against the same columns (StorageProxy does not forward the metadata refresh), so the verdict matches the read.
  • ⚠️ A table under SYSTEM RESTART REPLICA is skipped: DISAGREE, for most of the restart the table is detached and skipped as a missing table (a policy before its table stays legal), so failing on the restart flag cannot close the window and would reject a valid ON db.* statement because of an unrelated table.
  • 💡 A data lake table whose object storage is unreachable fails the statement with the error a read of it raises, naming the table. Noted, not changed.
  • 💡 CREATE ROW POLICY IF NOT EXISTS of a name that only users.xml (or a later access storage) holds is now a no-op, where it used to attempt the insert (a readonly error, or a second policy of that name). Noted, not changed: that is what IF NOT EXISTS means.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: CREATE ROW POLICY p ON db.t USING nosuchcol = 1 TO ALL is accepted on master every time, and every later read of db.t fails UNKNOWN_IDENTIFIER; the new test 05407 fails on master every run.
b Root cause explained? Policy DDL checked the filter only syntactically (arrayJoin, column matchers); the filter is first resolved against a table at read time, in each reader's query, so an unresolvable filter was stored and broke every read of the covered tables.
c Fix matches root cause? Yes: the DDL resolves each new filter with the read-time helper buildFilterQueryTree against the existing tables it is for, in the creator's session. The read path is unchanged, nothing is caught and retried.
d Test intent preserved / new tests added? New 05407 (14 cases) and 05408 (a data lake table whose schema changed outside the table object); 21 mutations of the check each make one of them fail (incl. an ON db.* walk that stops after the first table). 04368 and 05228 created an unresolvable filter on purpose: the first now creates its policy before the table, the second uses USING 0, and still fails when the bug it guards is restored.
e Both directions demonstrated? 05407 and 05408: FAIL on master, OK with the fix; 50/50 randomized runs and 50 concurrent copies of each green.
f Fix is general across code paths? CREATE, OR REPLACE, ALTER, IF [NOT] EXISTS, several names/targets, ON db.*, ON CLUSTER (each host, as the initiator's user), lazy and table-function proxies, Alias, data lakes (metadata refreshed first, as a read does). Persisted, restored and replicated policies keep loading unchecked (verified by upgrading a server holding such a policy).
g Fix generalizes across inputs (params/datatypes/wrappers)? Ordinary, MATERIALIZED, ALIAS, sub- and virtual columns; Nullable, LowCardinality, Nothing, String, Array, Decimal, Tuple results (the result-type check matches what a read accepts, measured on master); SQL UDFs, lambdas, IN operands; MergeTree, views, Merge, Distributed, Dictionary, external databases.
h Backward compatible? (maintainer-approved exception only) New validation on new DDL only, no setting. One script order now fails: a policy created before ALTER TABLE ADD COLUMN of the column it uses (the table was unreadable for its users in between). Category Improvement.
i Invariants and contracts preserved? The check runs before the policy is written, so a rejected ALTER keeps the old policy, and the names checked are exactly the names written, so a concurrent CREATE or DROP of the same policy cannot bypass it; tables are locked one at a time for analysis only, one dropped or restarting meanwhile is skipped, and a storage without columns (an Alias whose table is gone) is skipped before anything is refreshed; visibility is decided by name before any table is opened, so nothing is disclosed about a table the creator cannot see.

Session id: cron:clickhouse-impl-slot-4:20261019-050000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit @vitlibar, could you review this and add the can be tested label so CI runs? CREATE/ALTER ROW POLICY now resolve the USING filter with the read-time buildFilterQueryTree against each existing table the policy covers (all tables for ON db.*), in the creator's session, so a filter that would make every read fail with UNKNOWN_IDENTIFIER is rejected at DDL time; persisted policies still load unchecked.

@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [62e37a9]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
Some queries hung FAIL cidb
02346_non_negative_derivative NOT_FAILED cidb
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb

AI Review

Summary

CREATE ROW POLICY and ALTER ROW POLICY now validate new filters against visible existing tables before storing them. The earlier dictionary-backed ALIAS finding is fixed and verified with the current head's CI binary. No unresolved findings remain.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Oct 19, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 21, 2026
…jects

A filter that names an ALIAS column runs the alias expression, so an ALIAS
that calls `dictGet` with a name stored unqualified (for example a computed
`dictGet(concat('d', ''), ...)`) resolves the dictionary against the reader's
current database, exactly like a `dictGet` written in the filter itself. The
check skipped only the latter, so `CREATE ROW POLICY p ON db.t USING tenant = 'a'`
run from another database was rejected with `Dictionary (d) not found` while
reads in `db` work.

`readsOtherObjects` now follows referenced ALIAS columns, through ALIAS chains,
through a subcolumn of an ALIAS (`tup.val`), and also when the column is
qualified with the table or with the database and the table. Any other
qualifier does not name the column, so `wrong.tenant` is still analyzed and
rejected. The documentation also lists parameterized views as not checked:
their catalog entry has no columns. Stored ALIAS expressions already have SQL UDF calls
expanded (`InterpreterCreateQuery` expands column defaults, `InterpreterAlterQuery`
the whole ALTER), so they need no expansion here.

The test also covers a SQL UDF whose body calls `dictGet`, which is skipped only
because the filter is expanded before it is classified.

Reported by the AI review on ClickHouse#126643.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 62e37a91f with master b4013bf36 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c10265338; 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

4 object files changed (+76.73 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Access/InterpreterCreateRowPolicyQuery.cpp.o 88.70 KiB 164.12 KiB +75.42 KiB (+85.03%)

719 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 62e37a9

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / Some queries hung flaky, not from this PR: the only hung query is the parallel-replicas secondary query of 04117_detach_database_kill_query (initial query select_04117_test_b9d0y5f9n1u2, 246 s), which keeps sleeping after the test kills its initial query; the same hang hit master twice today #127149 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127149 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261021-113005

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants