Skip to content

Authorize the table engine's target on the initiator of an ON CLUSTER CREATE - #113073

Open
groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:groeneai/on-cluster-create-engine-access
Open

groeneai wants to merge 21 commits into
ClickHouse:masterfrom
groeneai:groeneai/on-cluster-create-engine-access

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #111561

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed an access-control bypass in CREATE TABLE ... ON CLUSTER: the access checks a table engine performs on its target were not enforced, so a user could create a Remote/RemoteSecure table over a local table it may not SELECT, INSERT or DESCRIBE, a Merge over sources it may not SHOW COLUMNS, or a clustered QueryRunner table without READ/WRITE ON REMOTE. The identical statement without ON CLUSTER was rejected. These engines now require the same privileges on both paths, except where the answer depends on which host runs the statement: a shard or source database present only on a target host is still authorized under that host's own context. The Merge check covers every source the initiator's catalog matches, seen by the issuing user or not, because a host infers from it regardless.

Description

What breaks. CREATE TABLE t ON CLUSTER c (x UInt64) ENGINE = Remote('127.0.0.1', db, protected, 'default') succeeds for a user holding only CREATE TABLE, TABLE ENGINE ON Remote, REMOTE and CLUSTER but no read on db.protected. Without ON CLUSTER it is denied.

Root cause. The initiator authorizes only what getRequiredAccess emits. Every check an engine performs on its target sits behind StorageFactory::get, which here runs only on each host's DDL worker whose context has no user, making it a no-op (#111561).

The change. The initiator now runs the engine's own validation before the enqueue, under the issuing user's context, through the same function the storage path calls.

Not fixed, not claimed. CREATE ... AS SELECT checks; the URL engine's delegate TABLE ENGINE check; an inner engine in create.targets, so a materialized view's is not preflighted either; an engine inherited through AS other_table below distributed_ddl_entry_format_version 3, where each host resolves the source itself. Those are bypassed on both paths. Plain Distributed with an omitted column list is not: master infers its structure under the user's context, so the local CREATE is denied without SHOW COLUMNS while this path accepts it. That one follows separately, on the preflight this PR introduces.

Parity is incomplete where the answer is host-specific. A Remote address local only to a target host skips the preflight, though the table stays unreadable. A Merge whose match set is partly invisible to the user is now refused, where a local CREATE infers from the visible part. A Merge source database absent from the initiator is tolerated (rejecting it would break authorized statements), so its columns can be inferred without SHOW COLUMNS.

Validation

Carriers covered: local-shard SELECT+INSERT on a plain Remote target; SHOW_COLUMNS when the structure is omitted; the source READ and inference checks for a table-function target (these fire even with explicit columns); per-source-table SHOW_COLUMNS while a Merge infers an omitted structure; QueryRunner with a cluster setting.

Every ON CLUSTER case in the new integration test is paired with the same statement without it, so the test asserts the two paths agree rather than that ON CLUSTER merely became stricter. Each denial is matched against the privilege named by the error, not the whole error text, since the query echo and stack trace also mention the target.

suite result
test_on_cluster_create_engine_access (new, 22 cases), unmodified tree 10 FAIL / 6 pass of the 16 cases that existed then, every failure the statement being accepted, or denied on the target where a statement-level grant was expected
same, with the fix 22/22 pass
Remote stateless family (04308, 04318, 04341, 04342, 04401, 04402, 04403, 04489, 04511, 04601, 04626) + 04337, 04418, 04541 pass
Merge stateless family (82 tests) 73 pass, 9 fail on missing fixtures of the local server (no test.hits, no ZooKeeper, absent clusters) with no access-control error in any of them
04318, 04337, 04418, 04541 at --test-runs 50 200/200 pass

The extraction commit is a behaviour-preserving move; the whole Remote engine family passing byte-for-byte is the guard on it.


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

groeneai and others added 4 commits August 2, 2026 19:55
Behaviour-preserving move. The `Remote`/`RemoteSecure` engines validate their
target while the storage object is constructed: they parse the engine arguments,
detect a local shard, and then perform a local-shard SELECT + INSERT check on a
plain target, or analyze a table-function target under the user's context (which
performs the source READ and SHOW COLUMNS checks). All of that lived inside
`registerStorageRemote`'s create callback, reachable only from
`StorageFactory::get`.

A following commit needs to run exactly those checks from a second place: the
initiator of an `ON CLUSTER CREATE`, which never constructs the storage. Moving
the block into `parseAndValidateRemoteEngineTarget` gives both call sites one
definition instead of a paraphrase that can drift out of date -- the drift that
caused the bypass the next commit fixes.

Two parameters replace what the callback read from `StorageFactory::Arguments`:
`columns_given` (the caller has the structure, so no inference is needed) and
`dependent_table_id`, which is forwarded to `parseRemoteFunctionArguments` and
registers the id as a dependent of a named collection. The callback keeps passing
its own table id; the preflight will pass nullptr, so a statement that is
rejected leaves no dependency for a table that never exists.

Verified with the whole `Remote` engine test family, which covers the create,
short-ATTACH, RESTORE, named-collection and settings paths: 11/11 pass
(04308, 04318, 04341, 04342, 04401, 04402, 04403, 04489, 04511, 04601, 04626).

Co-Authored-By: Claude Fable 5 <[email protected]>
… CREATE

`CREATE TABLE ... ON CLUSTER c ... ENGINE = Remote(...)` authorized only what
`InterpreterCreateQuery::getRequiredAccess` emits -- CREATE_TABLE, TABLE_ENGINE and
target ids from `create.targets`. Every access check the engine performs while its
storage object is built lives behind `StorageFactory::get`, which on this path runs
only on each host's DDL worker. That worker's context carries no user unless the
server setting `distributed_ddl_use_initial_user_and_roles` is on (default off), so
`full_access = !user_id` turns all of those checks into no-ops.

Consequence: a user holding CREATE TABLE on its own database plus TABLE ENGINE ON
Remote, REMOTE and CLUSTER could create, via ON CLUSTER, a `Remote` table pointed at
a local table it may neither SELECT nor INSERT nor DESCRIBE. The same statement
without ON CLUSTER was correctly rejected with ACCESS_DENIED.

The fix calls the engine's own validation from the initiator, before the query is
enqueued, under the issuing user's context. It is the same function the storage path
calls, not a second paraphrase of the engine's requirements -- the paraphrase drifting
out of date is what opened the gap in the first place. In particular the source check
for a table-function target stays filter-aware (`checkAccessWithFilter`), which a
declarative `READ ON <SOURCE>` requirement could not express, because
`ContextAccess::checkAccessImplHelper` never reads an `AccessRightsElement`'s filter.

Carriers closed, all local-shard only:
  - `Remote`/`RemoteSecure` SELECT + INSERT on a plain target,
  - SHOW_COLUMNS on the target when the structure is omitted,
  - the source READ and the target's own inference checks for a table-function
    target, which fire even when the columns are given explicitly,
  - `QueryRunner` with a `cluster` setting: READ + WRITE ON REMOTE.

Three details worth naming. Whether the structure was omitted is taken from the
contents of `create.columns_list`, not its presence: normalization materializes an
empty node before the enqueue, so a nullity test is always false there and would skip
the SHOW_COLUMNS branch while appearing to work. The legacy
`distributed_ddl_entry_format_version < 3` funnel is preflighted too, since that is a
per-query setting and the branch returns before normalization -- otherwise the whole
fix is bypassed by one SET; an engine inherited through `AS other_table` is genuinely
unknown there and is refused with NOT_IMPLEMENTED. And the initiator passes
`dependent_table_id = nullptr`, so a rejected statement registers no named-collection
dependency for a table that never exists, which would otherwise block
DROP NAMED COLLECTION forever.

This tightens ON CLUSTER to match non-ON CLUSTER behaviour; it can only turn a
previously-permitted statement into ACCESS_DENIED, never the reverse. No setting
default changes.

Two related gaps are deliberately NOT addressed, and neither is claimed fixed:
`CREATE ... AS SELECT` source/destination checks on ON CLUSTER (the pending design
decision in ClickHouse#111561), and plain `Distributed` with an omitted column list, which
bypasses SHOW_COLUMNS on the local path too because `doCreateTable` passes the global
context as the storage context.

New integration test `test_on_cluster_create_engine_access` (11 cases) pairs every
ON CLUSTER case with the same statement without ON CLUSTER, so it asserts the two
paths agree rather than that ON CLUSTER merely became stricter. Against the
unmodified tree 8 of its cases fail (the statement is accepted where ACCESS_DENIED is
required); with the fix all 11 pass, and 240/240 over 10 repeats together with the
pre-existing `test_query_runner` suite. Stateless guards: 20/20, and 200/200 over 50
randomized runs of 04318, 04337, 04418 and 04541.

Related: ClickHouse#111561

Co-Authored-By: Claude Fable 5 <[email protected]>
Review round 1 on the ON CLUSTER engine-target preflight. Three defects.

Authorization now precedes target resolution. On the legacy
distributed_ddl_entry_format_version < 3 funnel, execute() returns before its own
checkAccess and executeDDLQueryOnCluster checks later still, so the preflight was the
first thing an unprivileged user reached: one per-query setting let a user with no
CREATE TABLE, no TABLE ENGINE and no CLUSTER grant drive constant-expression
evaluation over its own engine arguments, named-collection resolution (whose
NAMED_COLLECTION check became the first authorization event, and which
getRequiredAccess never emits), address-glob expansion bounded only by
table_function_remote_max_addresses, and an outbound DESC TABLE. The check now runs
inside executeQueryOnCluster before the preflight, so both funnels are covered by one
line and a future third call site cannot regress. It is additive: checkAccess only
reads, and executeDDLQueryOnCluster still re-checks after its database substitution.

The Merge engine is a third carrier. registerStorageMerge passes the local context
into the constructor, which infers an omitted structure by reading each source table
under a per-table SHOW_COLUMNS check, and declares supports_schema_inference. Behind
StorageFactory::get, so it is a no-op on the DDL worker. This is not the Distributed
case deferred by the plan: Distributed receives the global context and is therefore
bypassed on the local path too, so its two paths agree, whereas Merge receives the
local context and its two paths disagree, which is exactly the invariant this PR
claims. The argument parsing is extracted into one function used by both the creator
callback and the new preflight branch; the preflight parses a clone, because constant
folding rewrites arguments in place and the caller's query may still be formatted.
It calls the static getColumnsDescriptionFromSourceTables overload, which unlike the
member one does not throw CANNOT_EXTRACT_TABLE_STRUCTURE on a regexp matching no
table, so the initiator can never reject a statement the workers would accept.

The preflight no longer forwards is_restore_from_backup. A preflight authorizes a
user-issued statement and has no backup metadata to fall back on, so tolerating an
unanalyzable target is meaningless there and stricter is correct. This cannot regress
restore, which runs through DatabaseWithOwnTablesBase::createTableRestoredFromBackup
with setInternal(true) and so never reaches the preflight. It also makes the tolerate
branch structurally unreachable from the preflight, which is what the comment there
previously only asserted; that comment could not be verified, since
setIsRestoreFromBackup is also reachable from executeQuery on a DDL-worker query.

Remote and RemoteSecure are now selected by one named condition used for both the
branch and the secure flag it implies, so the secure engine cannot be dropped from
the branch without also changing Remote's behaviour.

Test changes. Two new cases, each verified to fail on the previous commit and pass
here: one asserting authorization precedes resolution on the legacy funnel, and a
paired denied/allowed Merge case with a non-ON CLUSTER control. Denials are now
matched against the privilege named by the error rather than the whole error text,
which also contains the query echo and a stack trace and so could not distinguish
which privilege was missing. The Merge fixture grants SHOW TABLES on the target
deliberately: the inference traversal silently skips a table the user cannot see, so
without it the case would pass for the wrong reason. Two positive assertions that
only checked the statement succeeded now read through the created table.

Comments in the extracted file are trimmed to the local invariants; the rationale
they carried is in the commit message of the extraction instead. Verified
comment-only by stripping comments from both revisions and diffing.
The Merge branch of the initiator preflight resolves the source database
through DatabaseCatalog::getDatabase, which throws UNKNOWN_DATABASE
unconditionally. The initiator of an ON CLUSTER query need not host that
database and need not even be a member of the cluster it targets, so a
statement that used to succeed on every host that does have the database
started failing outright. Tolerate that one error code, in the interpreter
only, so storage construction stays strict; every host still checks its
own sources while building the storage. A companion case proves a denial
on the same branch still reaches the user.

Add the granted direction of the RemoteSecure case. With explicit columns
nothing on the create path opens a connection, so no TLS listener is
needed, which the earlier note wrongly assumed.

Qualify the parity claim for Merge in the changelog and the description.
Its inference traversal filters on the acting user's SHOW_TABLES
visibility before checking SHOW_COLUMNS, and a host acts with full
access, so a source the issuing user cannot see is still inferred there
unchecked. Closing that needs the host to run as the user, which is the
open question in ClickHouse#111561.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 9 findings across 3 rounds;
2 fix rounds, all raised blockers and majors resolved before publication).

# Sev Finding Verdict Evidence / action
1 ❌ The preflight ran before any access check on the legacy distributed_ddl_entry_format_version < 3 funnel, so one per-query setting exposed constant folding, named-collection resolution and an outbound DESC TABLE to an unauthorized user AGREE, fixed @ 3938a16 checkAccess(getRequiredAccess()) moved ahead of the preflight inside executeQueryOnCluster; new case fails on the pre-fix binary
2 ❌ Merge is an uncovered carrier: its creator passes the local context, its constructor infers omitted columns under a per-source SHOW COLUMNS check AGREE, fixed @ 3938a16 Merge branch added to the preflight plus 3 cases. Distinct from plain Distributed, whose creator gets the global context so both paths already agree
3 ❌ A comment asserted a RESTORE combination was unreachable that I could not confirm unreachable AGREE, fixed @ 3938a16 the preflight now passes is_restore_from_backup = false, making it unreachable by construction rather than by claim
4 ⚠️ The description claimed the change "can only turn a previously-permitted statement into ACCESS_DENIED, never the reverse" AGREE, fixed @ 3938a16 false: on the legacy funnel ... AS other_table now raises NOT_IMPLEMENTED. Claim removed, the compat break disclosed in the changelog entry
5 ⚠️ RemoteSecure had no oracle: deleting it from the branch condition left every case green AGREE, fixed @ 3938a16, 94a7bf8 one condition now drives both the branch and the secure flag, and both directions are asserted. Deleting the disjunct reddens the case
6 ⚠️ The URL engine's delegate TABLE ENGINE check is a third carrier of the same mechanism AGREE, disclosed out of scope here (it needs the URL configuration resolution re-run on the initiator, not one call into an existing helper); named in "Not fixed, not claimed" and tracked for a follow-up
7 ⚠️ The changelog claimed Merge reaches full parity, but its traversal filters sources on isGranted(SHOW TABLES) before checking SHOW COLUMNS, so the checked set depends on the issuing user's visibility AGREE, fixed @ 94a7bf8 not closable here: mirroring the throw over-rejects, dropping the filter breaks partial-grant multi-table Merge, and exact parity needs the host to run as the user. The claim is narrowed instead, in the changelog, the description and the test module
8 ⚠️ The new Merge preflight was a functional regression: DatabaseCatalog::getDatabase throws unconditionally, and the initiator of an ON CLUSTER query need not host the source database (it need not even be a cluster member) AGREE, fixed @ 94a7bf8 only UNKNOWN_DATABASE is tolerated, only in the interpreter's branch, so storage construction stays strict. Two cases: one proves the previously-working statement works again, one proves a denial still propagates
9 ❌ Legacy ON CLUSTER creates with an omitted engine could still bypass the target check "when the configured default engine is target-sensitive", e.g. a default QueryRunner with SETTINGS cluster = ... DISAGREE the scenario needs a target-sensitive default engine, which cannot be configured. default_table_engine is a closed enum (SettingsEnums.h:213-225), not a string; its ten values are all local storage engines, QueryRunner is not among them and an unlisted name is rejected at SET time. setDefaultTableEngine can only emit one of those names. The one genuinely unresolved engine on that funnel, an inherited AS other_table, already fails closed with NOT_IMPLEMENTED, and AS table_function(...) is resolved on the initiator under the user's context (ITableFunction.cpp:36-46)

Noted, not blocking: the tolerated UNKNOWN_DATABASE is wider than its one cause by
construction, though only the genuine absent-database throw sites are reachable from this
path and the tolerated code cannot mask ACCESS_DENIED (different codes, asserted by a
test); the tolerance is needed for Merge alone because the Remote branch gates all of
its target work on a local shard existing and QueryRunner resolves only a cluster name;
and is_local is resolved per host from DNS, so the preflight enforces the initiator's
locality view, which is exactly the view a local CREATE on the initiator would have used.

Severity: mapped as blocker / major / nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-50:20260803-085500

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One statement, no randomization, no timing dependence: on a two-node cluster, CREATE TABLE db.t ON CLUSTER c (x UInt64) ENGINE = Remote('127.0.0.1:9000', db, local_target, 'default') as a user with no rights on db.local_target SUCCEEDS on the unmodified tree. 10 of the new test's 18 cases reproduce on demand via pytest test_on_cluster_create_engine_access/test.py.
b Root cause explained? Yes. The initiator authorizes only getRequiredAccess (CREATE_TABLE, TABLE_ENGINE, create.targets ids). Every check an engine performs on its target sits behind StorageFactory::get, which on this path runs only on each host's DDL worker. entry.initiator_user is set only when distributed_ddl_use_initial_user_and_roles is on (default false), and DDLTaskBase::makeQueryContext has one reachable setUser, inside that guard, so Context::getAccess computes full_access = !user_id and the checks become no-ops.
c Fix matches root cause? Yes. The missing authorization is performed where the user is known (the initiator), by calling the engine's own validation. No widened bound, no no-random tag, no guard at the symptom site. The upstream defect (workers run with no user) is the design fork in #111561; this change is correct either way.
d Test intent preserved / new tests added? Yes. No existing test weakened. New integration test test_on_cluster_create_engine_access (18 cases). The extraction commit is guarded by the entire pre-existing Remote engine stateless family passing unchanged (20/20), which is the behaviour-preservation proof.
e Both directions demonstrated? Yes, same test and same command on Build-ID-verified binaries: base cd280abf 8 FAIL, extraction-only 0a6b73d3 8 FAIL (the move alone fixes nothing, as intended), extraction+preflight 0d48d609 10/10 pass, and after the review round the pre-fix binary 20f46d30 reddens exactly the two newly added cases while the round-1 binary 784ccab2 passes 16/16. Review round 2 repeated the pattern: with round-2 source reverted (binary 784ccab2, byte-identical to the round-1 final, which is itself the proof the revert was exact) the new cross-host Merge case fails with Code: 81 ... UNKNOWN_DATABASE, and the final binary 5ef8bfa6 passes 18/18. A failing case either accepted the statement outright, or denied it on the engine's target where a statement-level grant was the correct answer; the control cases prove the non-ON CLUSTER form is rejected on the same tree. Each denial is matched against the privilege the error names, not the whole error text, which also contains the query echo and a stack trace.
f Fix is general across code paths? Yes. All three executeQueryOnCluster call sites are classified rather than one patched: short ATTACH ineligible (definition comes from stored metadata), default path eligible, legacy distributed_ddl_entry_format_version < 3 funnel eligible for an explicit engine (that setting is per-query, so skipping it would let one SET bypass the whole fix) and NOT_IMPLEMENTED for an inherited one. Sweeping checkAccess inside registerStorage* callbacks found two further engines with the same gap: QueryRunner with a cluster setting, and Merge while it infers an omitted structure (its creator passes the LOCAL context, so unlike plain Distributed its two paths genuinely disagree). Both are fixed by the same shape and covered by their own cases. Authorization now also precedes target resolution, so the legacy funnel cannot be used to reach expression evaluation, named-collection resolution or an outbound DESC TABLE before any grant is checked. A third carrier, the URL engine's delegate TABLE ENGINE check, is verified, deliberately deferred and named in the PR body. CREATE OR REPLACE / REPLACE TABLE use the same helper with no special casing.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, over the axes this code has: plain target vs table-function target; explicit columns vs omitted structure; matching vs non-matching filtered source grant; Remote vs RemoteSecure (one condition drives both the branch and the secure flag, so neither engine can be dropped independently); named-collection vs positional arguments; malformed arguments; distributed_ddl_entry_format_version 2 vs 5; CREATE vs full-definition ATTACH vs short ATTACH; QueryRunner with and without a cluster setting. Type wrappers do not apply: this is an access-control path over table identifiers, not a value path.
h Backward compatible? (maintainer-approved exception only) It is a deliberate user-visible tightening, stated plainly in the PR body: an ON CLUSTER CREATE of a Remote/RemoteSecure engine over a local target now requires SELECT+INSERT (plus SHOW_COLUMNS when the structure is omitted, and the source READ for a table-function target), and a clustered QueryRunner requires READ+WRITE ON REMOTE. A Merge with an omitted structure now requires SHOW_COLUMNS on its source tables, though only on the sources the issuing user can see: the inference traversal filters on SHOW_TABLES before checking, and a host acts with full access, so parity for Merge is partial and the residual is named in the PR body and tracked separately. For the other engines this makes ON CLUSTER agree with the non-ON CLUSTER path. One exception to the tightening, disclosed rather than glossed: on the legacy distributed_ddl_entry_format_version < 3 funnel, CREATE ... ON CLUSTER ... AS other_table now raises NOT_IMPLEMENTED, so a statement that previously worked for a fully privileged user does not. The inherited engine is unresolved on that funnel and cannot be authorized, and silently enqueueing it would reinstate the bypass; the changelog entry states this. A second, opposite break was found in review and CLOSED rather than disclosed: the Merge preflight resolves the source database through DatabaseCatalog::getDatabase, which throws UNKNOWN_DATABASE, and the initiator of an ON CLUSTER query need not host that database (it need not even be a cluster member), so ENGINE = Merge('shard_db', ...) from such an initiator would have started failing. The preflight now tolerates that one error code, with a test proving ACCESS_DENIED still propagates on the same branch. No setting defaults change, so no SettingsChangesHistory.cpp entry applies; no experimental gate (this is a fix, not a feature). Filed as Bug Fix, not Critical Bug Fix.
i Invariants and contracts preserved? Yes. The initiator call is read-only: dependent_table_id = nullptr suppresses the only write parseRemoteFunctionArguments performs (registering the table as a dependent of a named collection), so a rejected statement cannot leave a dependency for a table that never exists and block DROP NAMED COLLECTION; asserted in both directions by a dedicated case. internal queries early-return, mirroring getRequiredAccess. Server-startup and short-ATTACH loads still skip the checks (isLoadingFromExistingMetadata || attach_short_syntax), so a validly created table stays attachable, guarded by 04601 and test_remote_storage_engine_attach. The new Merge branch parses a CLONE of the engine arguments (constant folding rewrites them in place) and calls the STATIC getColumnsDescriptionFromSourceTables overload, which unlike the member one does not throw on a regexp matching no table, so the initiator can never reject a statement the constructing hosts would accept. The RESTORE tolerance on the storage-construction path is preserved verbatim; the preflight passes is_restore_from_backup = false, making that branch structurally unreachable from the preflight instead of merely asserted so, and it cannot regress restore, which is internal and never reaches the preflight (all four RESTORE-exercising tests pass: 04341, 04401, 04489, 04601). The one invariant narrowed in review is that Merge branch's UNKNOWN_DATABASE tolerance, which weakens "the preflight rejects nothing the hosts would accept" in the safe direction only; it sits in the interpreter, not in validateMergeEngineTarget, so storage construction stays strict, and it cannot swallow a denial (codes 81 vs 497, asserted by a dedicated case rather than by inspection). Exceptions otherwise propagate unchanged; no new locks and no new concurrency surface.

Session id: cron:clickhouse-impl-slot-43:20260802-235600

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @evillique, could you review this? The initiator of a CREATE TABLE ... ON CLUSTER authorized only getRequiredAccess, while every access check an engine performs on its own target sits behind StorageFactory::get, which runs only on each host's DDL worker under a context with no user, so those checks were no-ops. The initiator now runs the engine's own validation before enqueueing, under the issuing user's context.

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [34d4609]

Summary: ✅


AI Review

Summary

This PR adds initiator-side engine-target preflights for CREATE TABLE ... ON CLUSTER and backs them with a large integration suite. It clearly improves the Remote/Merge/QueryRunner path, but the fix is still not closed over the current engine set and it intentionally leaves several supported access-control bypasses plus one IF NOT EXISTS contract regression in place, so I do not think it is ready to merge.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:4092] [dismissed by author -- https://github.com/Authorize the table engine's target on the initiator of an ON CLUSTER CREATE #113073#discussion_r3882568088] The legacy distributed_ddl_entry_format_version < 3 AS other_table funnel still re-resolves the inherited engine only to check TABLE ENGINE, then queues the original query without any target preflight. A single per-query setting therefore restores the same metadata bypass on inherited Remote / Merge / QueryRunner sources that this PR is meant to close. I still consider this real because the current code path never reaches preflightEngineTarget for inherited engines on that funnel.
  • [src/Interpreters/InterpreterCreateQuery.cpp:3996] [dismissed by author -- https://github.com/Authorize the table engine's target on the initiator of an ON CLUSTER CREATE #113073#discussion_r3720713863] The Merge preflight still fails open whenever the initiator cannot enumerate the real source set, for example when the source database or matching tables exist only on the executing host. In that case validateMergeEngineTarget cannot prove anything locally, but the worker still infers columns under its no-user context and persists protected schema metadata. I still consider this real because the current code still tolerates UNKNOWN_DATABASE and still treats an empty local match set as success.
  • [src/Interpreters/InterpreterCreateQuery.cpp:3967] [dismissed by author -- https://github.com/Authorize the table engine's target on the initiator of an ON CLUSTER CREATE #113073#discussion_r3884007571] Distributed is still missing from the initiator preflight even though omitted-schema creation still resolves the target under args.getLocalContext() at src/Storages/StorageDistributed.cpp:2631. CREATE TABLE ... ON CLUSTER ... ENGINE = Distributed(...) can therefore still materialize protected columns where the same local CREATE is denied. I still consider this real because the newly added preflight is already the mechanism needed to close it and the carrier stays on the exact surface this PR claims to fix.
  • [src/Interpreters/InterpreterCreateQuery.cpp:3967] [dismissed by author -- https://github.com/Authorize the table engine's target on the initiator of an ON CLUSTER CREATE #113073#discussion_r4005604511] The unified URL engine is also still outside the preflight even though it performs a delegate TABLE ENGINE check only during storage construction at src/Storages/StorageURL.cpp:3163. CREATE TABLE ... ON CLUSTER ENGINE = URL('file://...') can therefore still bypass TABLE ENGINE ON File / S3 / HDFS / AzureBlobStorage. I still consider this real because the worker still runs that delegate check under an empty user on the path this PR is tightening for Remote and QueryRunner.
  • [src/Interpreters/InterpreterCreateQuery.cpp:3967] The new whitelist is already incomplete even beyond the known Distributed / URL gaps. StorageAlias still requires SHOW_COLUMNS on every fresh target at src/Storages/StorageAlias.cpp:649, and StorageBuffer still requires SHOW_COLUMNS when it infers an omitted destination schema at src/Storages/StorageBuffer.cpp:1623; neither engine is covered here. That leaves new ON CLUSTER metadata-bypass carriers on the same worker-without-user mechanism immediately after this PR lands.

⚠️ Majors

  • [src/Interpreters/InterpreterCreateQuery.cpp:4038] [dismissed by author -- https://github.com/Authorize the table engine's target on the initiator of an ON CLUSTER CREATE #113073#discussion_r3720129192] CREATE TABLE IF NOT EXISTS ... ON CLUSTER is no longer idempotent: the initiator now runs preflightEngineTarget before any host can decide the statement is a no-op, so repeated deploys can fail with ACCESS_DENIED even when the table already exists everywhere and no storage would be created. I still consider this real because the current code unconditionally preflights every resolved engine and never makes a cluster-wide existence decision first.
Final Verdict

❌ Changes required. The current branch closes several important carriers, but it still leaves multiple supported ON CLUSTER access-control bypasses open and changes the IF NOT EXISTS contract.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 5, 2026
…erStorageRemote

Two style/lint failures introduced by this PR's own extraction of the `Remote`
engine's target validation into `validateRemoteEngineTarget`.

Both `ErrorCodes::ACCESS_DENIED` uses left `StorageDistributed.cpp` with the
extracted block (the explanatory comment and the `tolerate_absent_target`
rethrow guard now live in `validateRemoteEngineTarget.cpp`, which declares the
code itself), but the `extern const int ACCESS_DENIED;` declaration stayed
behind. `ci/jobs/scripts/check_style/check_cpp.sh` block 04 rejects a
declaration with no use in the same file:

    ErrorCodes::ACCESS_DENIED is defined but not used in file
    src/Storages/StorageDistributed.cpp

Reproduced locally with the real checker and confirmed to disappear only with
the declaration removed; re-adding it reproduces the message verbatim.

The `columns` initialization added by the extraction selected the inferred
columns through a ternary. `StorageFactory::Arguments::columns` is a
`const ColumnsDescription &`, so the conditional operator's common type is a
prvalue and the `std::move` could never bind to a non-const reference:

    error: passing result of std::move() as a const reference argument;
    no move will actually happen [performance-move-const-arg]

Copy-initialize from `args.columns` and move the inferred columns in only on
the branch that uses them, which is what the pre-extraction code did. Verified
with clang-tidy-21 restricted to `performance-move-const-arg`: no diagnostic
after the change, and the original spelling reproduces the error at the same
column.

The 147 dropped jobs on the failing run are dependees of `Build (arm_tidy)` and
the dropped `Code Review` is a dependee of `Style check`; no other failure was
reported at that commit.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 94a7bf8

Every failure below has an owner: a fixing PR (ours 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.

All three failures are caused by this PR's own diff and are fixed in ff85ffe.

Check / test Reason Owner / fixing PR
Style check / cpp PR-caused: both ErrorCodes::ACCESS_DENIED uses moved out of StorageDistributed.cpp with the extracted validation, but the extern declaration stayed behind PR-caused → fixed in this PR @ ff85ffe
Build (arm_tidy) / Build ClickHouse PR-caused: performance-move-const-arg: the new columns ternary makes std::move bind to a const ColumnsDescription &, so no move happens PR-caused → fixed in this PR @ ff85ffe
Finish Workflow / Post Hooks Cascade of the above: 147 of the 148 dropped jobs record Dropped due to previous failure [Build (arm_tidy)], and the three Bugfix validation jobs that need a build artifact are among them, so new_tests_check.py saw no validating job PR-caused → fixed in this PR @ ff85ffe

No other failure was reported at that commit: over the 175 check-runs, 3 failure / 3 success /
169 skipped, and the whole arm_tidy build log contains exactly one error: line. The two
remaining Bugfix validation jobs were SKIPPED for "no functional tests updates", which is
correct here: this PR's regression test is an integration test.

How each fix was verified.

  • Style: reproduced with the real ci/jobs/scripts/check_style/check_cpp.sh, which is clean
    after the change and reports the identical ErrorCodes::ACCESS_DENIED is defined but not used
    line when the declaration is put back.
  • clang-tidy: clang-tidy-21 restricted to performance-move-const-arg reports nothing after
    the change, and reproduces error: passing result of std::move() as a const reference argument at the same column on the original spelling. Arguments::columns is a
    const ColumnsDescription &, so the conditional operator yielded a prvalue copy and the move
    was dead; copy-initializing and moving only on the inference branch restores the
    pre-extraction behaviour.
  • Both branches of the changed initialization are exercised by the suite (columns omitted, and
    columns supplied). Full integration suite green on the rebuilt binary, 18 of 18.

Three findings from my own second-model re-review of this push, none of them fixed here, all
in the pre-existing diff rather than in the lint fix, and all recorded so they are not lost:

  1. getRequiredAccess does not include CLUSTER, so the initiator preflight runs before the
    CLUSTER grant is checked in executeDDLQueryOnCluster. This is fail-closed, not a bypass
    (a user without CLUSTER still creates nothing), but the pre-authorization work the preflight
    does is gated only on CREATE TABLE + TABLE ENGINE. Worth hoisting the CLUSTER check
    ahead of the preflight in a follow-up round.
  2. With IF NOT EXISTS over a table that already exists on every host, the local form is a no-op
    while the ON CLUSTER form now raises ACCESS_DENIED: doCreateTable returns at the
    isTableExist check before StorageFactory::get, whereas the initiator preflight is
    unconditional. Measured on both binaries: pristine master returns no error for either form,
    this branch returns no error locally and Code: 497 for ON CLUSTER. So it is introduced
    here, and it runs opposite to the description's "same privileges on both paths" claim. Either
    the no-op should be preserved or the claim qualified.
  3. test_malformed_engine_arguments_reported_by_initiator passes on a pristine pre-fix binary,
    so it pins nothing: the unchanged storage callback produces the same
    NUMBER_OF_ARGUMENTS_DOESNT_MATCH from a DDL worker, and the test's oracle cannot tell that
    from an initiator rejection. The eight cases that were measured to fail on the base tree are
    unaffected; this one is redundant and should either get a discriminating oracle or be removed.

Session id: cron:clickhouse-maint-slot-13:20260805-102600

/// whether the user supplied a structure; only its contents do.
const bool structure_given = create.columns_list && create.columns_list->columns
&& !create.columns_list->columns->children.empty();
preflightEngineTarget(create, structure_given);

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 unconditional preflight changes CREATE TABLE IF NOT EXISTS ... ON CLUSTER from an idempotent no-op into ACCESS_DENIED whenever the table already exists everywhere. The local path still returns from doCreateTable at database->isTableExist() before it reaches any engine-specific check, and each host on the distributed path still has that same short-circuit, but the initiator now denies the statement before any host can take it.

That means repeated deploys start failing even though no storage would be created. We need to preserve the IF NOT EXISTS short-circuit here, or move the engine-target authorization onto a path that runs only when creation will actually happen.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Answered together with the CLUSTER finding in #113073 (comment), since one commit covers both.

Short version: the over-rejection is real, but I implemented the short-circuit you propose and measured that it opens a bypass. The initiator's catalog is not the cluster's, so a user with no rights on the target can create the name on node1 alone with a harmless engine, then have node2 build the Remote table over the forbidden target under the DDL worker's full_access context. So the fix is withdrawn rather than shipped, the divergence is disclosed, and a correct remedy needs a cluster-wide no-op decision or hosts running as the issuing user (#111561). Measurements are in the linked reply.

`executeDDLQueryOnCluster` checks `AccessType::CLUSTER`, but it does so after
`executeQueryOnCluster` has already run `preflightEngineTarget`. Resolving an
engine's target expands named collections and address globs and can send the
`DESC TABLE` that `getStructureOfRemoteTable` uses, so a user holding
`CREATE TABLE` and `TABLE ENGINE` but not `CLUSTER` reached all of that before
the statement was finally rejected. Before this PR no engine work ran on that
path at all, so the check now runs first here and the previous authorization
boundary is restored. `getRequiredAccess` does not emit `CLUSTER`, so the added
check is not redundant with the one on the line below it.

The regression case withholds the target grant as well as `CLUSTER`, so the two
orderings are distinguishable by which privilege the denial names: on the
pre-fix binary it is `SELECT ON acl_db.local_target`, which is what shows the
engine work ran first. It then grants `CLUSTER` alone and asserts the target
check still denies, so the reordering does not drop either check.

if (engine_is_resolved)
{
/// Resolving the engine's target evaluates user expressions and may contact remote shards,

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.

UNKNOWN_DATABASE is not a harmless "nothing local to authorize" case here. It only means that the initiator does not host the source database. After this catch we still enqueue the DDL, and registerStorageMerge constructs the table on each target host with args.getLocalContext(). On a DDL worker that context has no user by default, so the constructor's SHOW COLUMNS checks are the same full-access no-ops this PR is compensating for.

That reopens the bypass whenever the source DB exists only on a target host: from node1, CREATE TABLE ... ON CLUSTER node2_only_cluster ENGINE = Merge('remote_db', '^src$') still succeeds without SHOW COLUMNS ON remote_db.src on node2. If the initiator cannot validate the source DB, this path needs to fail closed (or the worker must run as the issuing user).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and this one has an observable consequence, so it is the stronger of the two findings. Measured on a two-node cluster against this branch.

I granted SHOW TABLES on the source deliberately, because that removes the residual the description already discloses (the traversal skipping sources the user cannot see) and leaves only what you are describing:

arm outcome
ON CLUSTER node2_only_cluster ENGINE = Merge('<rdb>', '^src$'), <rdb> on node2 only, no SHOW COLUMNS accepted, created on node2
same definition, no ON CLUSTER, run on node2 denied SHOW COLUMNS ON <rdb>.src
same definition, no ON CLUSTER, run on node1 where the database is absent UNKNOWN_DATABASE
DESCRIBE TABLE <rdb>.src as that user on node2 denied SHOW COLUMNS ON <rdb>.src
system.columns for the table the accepted statement created secret_col, other_col

The last two rows are the point: the user cannot obtain those column names directly, and the ON CLUSTER route hands them over. The third row shows the route is unique, so this is not reachable without it. You are right that my in-source comment reads as though there is nothing to authorize, when what it actually means is that the initiator cannot see the source.

I am not failing closed. The same shape with SHOW COLUMNS granted on node2 is a fully authorized statement that works today, and it is pinned by test_merge_engine_source_database_absent_on_initiator. The tolerance exists because of the preceding commit on this branch, which fixed exactly the over-rejection a fail-closed rule would reinstate, so that would be a straight revert of a fix rather than a tightening. The alternative you name, the worker running as the issuing user, is the #111561 design question and out of scope here.

I have disclosed it instead, and separately from the SHOW TABLES shape, since the existing wording did not cover it: the changelog now excludes cases where the answer depends on which host runs the statement, and the description states that a Merge source database absent from the initiator is tolerated so its columns can be inferred where the user lacks SHOW COLUMNS, naming it as the one residual with a visible effect.

I have not added a test for it. An assertion pinning today's accepting behaviour would enshrine the gap as expected, which is worse than the gap.

This is the second review round on this PR, so I am leaving further discussion of the design fork to a human.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4ee53c6

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
Integration tests (arm_binary, distributed plan, 1/4) / test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write pre-existing: a JetStream subscription closed by the broker is not recovered; 43 rows across 38 distinct pull requests in 30 days, 2 on master #112828 (mine, open)
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) / 04228_check_optimize_alter_temporary_scoping_100966 flaky: the runner's own diagnosis on this job reran it 8 times and all 8 passed (the failure is not reproducible); 4 rows across 4 distinct pull requests in 30 days, 0 on master a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Docker server image infra: the image build step failed while resolving and transferring its build context, before any ClickHouse code ran a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks infra: build_profile_hook.py telemetry INSERT rejected with LogCluster query failed with code 500 #113409 (external, open)

All 174 check-runs completed and Finish Workflow succeeded.

The twelve test_on_cluster_create_engine_access entries on this commit are not failures. Both
Bugfix validation (integration tests, amd64) and (aarch64) report success, and those entries
are the before-binary reproducing the access-control gap this pull request closes: the summary line
is Failures: 6/19, and each one asserts the statement was accepted where the fix denies it. That
is exactly what the check exists to demonstrate.

Session id: cron:our-pr-ci-monitor:20260805-230000

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to the CI finish ledger above - 4ee53c6

I gave the Docker server image row a new fix task when an owner already existed, and my stated
reason was wrong about where it fails.

Check / test Reason Owner / fixing PR
Docker server image infra, pre-existing: the amd64 leg fails inside apt-get update while fetching Ubuntu package indexes, before any ClickHouse code runs. Over 30 days this check fails 168 times across 19 distinct pull requests, 12 of those on master a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)

What I got wrong. I wrote that the step "failed while resolving and transferring its build
context". It does not: the context transfer (#6 CACHED, #7 transferring context: 11.78kB)
completes, and the failure is in the later RUN layer, whose last output is
Ign:6 http://us-east-1.ec2.archive.ubuntu.com/ubuntu jammy InRelease followed by two
jammy-updates / jammy-backports fetches. I also implied this was a fresh finding when the
signature is already tracked; the owner is an existing task, not a new one.

The other three rows are unchanged and still owned by #112828, a pre-existing flaky-test fix task,
and #113409.

Session id: cron:our-pr-ci-monitor:20260805-230000

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Second correction to the CI finish ledger above - 4ee53c6

I gave the 04228_check_optimize_alter_temporary_scoping_100966 row a new fix task. That was wrong:
the row splits into two sub-signatures, and one of them already has a merged fix.

Check / test Reason Owner / fixing PR
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) / 04228_check_optimize_alter_temporary_scoping_100966 flaky: the runner's own diagnosis reran it 8 times under the same randomized settings and all 8 passed (the failure is not reproducible) #111789 (external, merged) for the memory-pressure sub-signature; the single non-reproducible msan row carries no separate defect

What I got wrong. I reported the 30-day breadth as one family of 4 rows and concluded no fixing
PR existed. Split by sub-signature it is:

  • 3 rows on Stateless tests (amd_asan_ubsan, distributed plan, parallel), all
    Code: 241 ... (total) memory limit exceeded ... current RSS: 41.84 GiB, maximum: 41.84 GiB on a
    1.00 MiB allocation, i.e. the runner at its global RSS ceiling with this test as the victim. That
    is the amd_asan_ubsan, distributed plan job-OOM family fixed by Run distributed-plan sanitizer stateless on runner with more mem instead of cutting concurrency #111789 (merged
    2026-07-25T09:53:57Z). All three rows are dated 2026-07-15 and 2026-07-16, so they predate the fix
    by nine days and cannot have run with it present.
  • 1 row on amd_msan, WasmEdge, parallel, 2/2 - this commit's row - which is the non-reproducible
    one above.

So there is nothing here for a fix task to own: the memory-pressure half is fixed, and the msan half
is a single rerun-green occurrence with no signature of its own. Zero master rows in 30 days either
way.

The other rows are unchanged and still owned by #112828, the existing Docker server image fix task,
and #113409.

Session id: cron:our-pr-ci-monitor:20260805-230000

The branch was 3007 commits behind. One content conflict, in
registerStorageMerge: this branch had extracted the argument parsing into
parseMergeEngineArguments so the new initiator-side preflight can reuse it,
while master (bfd95a6) added a deny of the internal temporary-tables
database between the two argument parses.

Master's placement is itself an authorize-before-evaluate boundary, so it is
preserved rather than reordered: the parse helper is split into a
database-argument half and a table-regexp half, and registerStorageMerge runs
the deny between them, evaluating the second argument's expression only after
the source database has been accepted. validateMergeEngineTarget keeps calling
the combined helper, so the preflight is unchanged.

The deny is deliberately not mirrored into preflightEngineTarget: the preflight
runs only when the structure is omitted, and in that case it infers the schema
through getColumnsDescriptionFromSourceTables, whose getDatabaseIterator
already throws DATABASE_ACCESS_DENIED for that database on every host.
The preliminary getRequiredAccess check added for the legacy funnel resolved an
element naming no database against the initiator's current database, because
ContextAccess substitutes params.current_database for an empty one. Distributed
DDL instead translates it to each host's configured default_database, so an
unqualified CREATE authorized on the hosts was rejected on the initiator's
database, which the user need hold nothing on.

Measured on a two-host cluster whose replicas declare default_database, with the
user granted CREATE TABLE only there: before this commit the unqualified create
failed with "necessary to have the grant CREATE TABLE ON default.t_f3", while
the same statement on the merge's other parent was accepted.

Such an element is now dropped from the preliminary check and left to the
translated one in executeDDLQueryOnCluster, the only place that can resolve it.
Qualified elements are unaffected, so the check that motivated it still runs:
with the same setup, a qualified create into a database the user cannot write is
still denied, and one into a granted database is still accepted.

Found by the second-model re-review of the master merge.
Keeps the local invariant (which check can resolve an empty database) and moves
the rest to the previous commit's message. No code change.
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 34d4609247df93ec2d5ece0c58f6eb0dc707c50b was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6992ce1

CI is fully finished on this head and there are no failures: 154 success / 20 skipped / 0 failure of 174 check-runs, Finish Workflow green. No CH Inc sync row on this head, so there is not even an exempt line.

Check / test Reason Owner / fixing PR
(none) - -

Gate detail: (a) 0 check-runs queued or in_progress across all 174 (fully paginated); (b) Finish Workflow = success at 2026-08-08T17:21:00Z; (c) 77 minutes since the last completion, past the 20-minute CIDB ingestion buffer; (d) trivially satisfied.

One note on reading CIDB for this head: Bugfix validation (integration tests, amd64/aarch64) contains six FAIL rows each for test_on_cluster_create_engine_access. Those are the expected arm of that check, which asserts the new regression tests DO fail without the fix. Both enclosing check-runs concluded success.

Session id: cron:our-pr-ci-monitor:20260808-183000

…/on-cluster-create-engine-access

# Conflicts:
#	src/Interpreters/InterpreterCreateQuery.cpp
groeneai and others added 2 commits August 14, 2026 14:46
…flight

parseRemoteFunctionArguments folds constant arguments into literals and writes
them back into the AST it was given, because the storage-construction path
persists exactly what it parsed. The initiator preflight runs before
executeDDLQueryOnCluster clones and enqueues the query, so validating the
query's own argument list froze host-dependent expressions to the initiator's
values on every worker.

Measured on a two-node cluster with
ENGINE = Remote('127.0.0.1:9000', hostName(), 'local_target', 'default'):
pristine master stores 'node1' on node1 and 'node2' on node2, while the
preflight made both hosts store 'node1'. The same definition without
ON CLUSTER was unaffected on either tree.

The Merge branch of the preflight already clones its arguments for this
reason; this gives the Remote branch the same treatment. QueryRunner needs
none: its validation only reads the SETTINGS changes and rewrites nothing.

Co-Authored-By: Claude Fable 5 <[email protected]>
The Style check's ruff gate rejects it as F541. The literal carries no
substitution: hostName() is SQL the initiator must leave unevaluated, which is
exactly what the test asserts, so the prefix was never doing anything.

CPython folds a placeholder-less f-string to a plain constant, so the compiled
module is unchanged: with heap addresses masked, the instruction stream and the
constant pool of the whole module are identical before and after.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1b089d3

CI is fully finished on this head: 178 praktika leaves, 0 dropped, 155 success / 21 skipped / 1 failure.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, distributed plan, 1/4) / test_storage_nats/test_nats_jet_stream.py::test_nats_restore_failed_connection_without_losses_on_write flaky, graded shortfall (97752 of 100000 messages) a fix task is moved to pending (investigating at full effort, fixing PR link to follow on this PR)
Bugfix validation (integration tests, amd64 and aarch64) expected-to-fail-on-master arm of the bugfix contract not a failure: both checks concluded success

On the NATS failure: it is unrelated to this PR's diff (this PR touches ON CLUSTER CREATE authorization; the failing test is the NATS producer path). 25 unrelated PRs plus 4 master shas carry it in the last 30 days. I did not link #112828 as its owner: that PR fixes the consumer resubscribe path, its symbols are present in the tree praktika built for this run, and the shape here is the graded 2.2% shortfall rather than the clean stop-and-starve shape #112828 addresses, so it is a post-fix residual and a separate defect.

Session id: cron:our-pr-ci-monitor:20260814-210000

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
…/on-cluster-create-engine-access

# Conflicts:
#	src/Interpreters/InterpreterCreateQuery.cpp
The paragraph removed here restated why the initiator has to run this
validation: on an ON CLUSTER query only each host's DDL worker constructs
the storage, and its context carries no user, so a check performed there
alone is a no-op. That is the reason for the change, not an invariant a
caller of this function needs at the declaration, and it is already in the
pull request description. What a caller does need - that this is the single
definition of the engine's requirements, called from both paths - stays.
`preflightEngineTarget` refused every `CREATE TABLE ... ON CLUSTER ... AS
other_table` with `distributed_ddl_entry_format_version < 3`, on the grounds
that `setEngine` has not run there so the inherited engine cannot be
authorized. That is a new validation over a supported, if non-default,
setting, and it breaks `05030_totime_on_cluster_as_settings_in_zk_version`,
which pins that version 2 accepts the statement: only version 1 has to be
rejected, and for an unrelated reason (that format drops the query settings,
so a worker cannot see `use_legacy_to_time`).

Resolving the source table on the initiator instead would not be sound on
that funnel. The entry ships the query text as written, so every host
resolves the name in its own catalog and the initiator's answer need not be
the engine a host materializes. The inherited engine therefore stays
unauthorized there, exactly as before this pull request, and the pull
request description discloses it. The explicit-engine preflight on the same
funnel is unchanged (`test_legacy_funnel_explicit_engine_is_checked`).

`test_legacy_funnel_inherited_engine_is_rejected` asserted the rejection
that is removed here. It is replaced by
`test_inherited_engine_is_checked_at_the_default_version`, which asserts the
stronger property: at the default version the inherited engine's target is
authorized like an explicit one. That case fails against a pristine master
binary with "the statement was accepted" and passes with the fix.
The header said plain `Distributed` is bypassed on the non-`ON CLUSTER`
path too, so that the two paths already agree there. That stopped being
true on master: `registerStorageDistributed` now infers an omitted
structure under the local context, so a local `CREATE` is denied without
`SHOW COLUMNS` on the target while the same statement with `ON CLUSTER`
is accepted and the columns are inferred on a worker that has no user.

Measured on this branch, user holding `CREATE TABLE`,
`TABLE ENGINE ON Distributed` and `CLUSTER` but nothing on the target:

  CREATE TABLE d.local ENGINE = Distributed(c, d, protected)
    -> Code: 497, SHOW COLUMNS ON d.protected
  CREATE TABLE d.clustered ON CLUSTER c ENGINE = Distributed(c, d, protected)
    -> accepted, both columns of d.protected inferred and describable

The carrier is not addressed here, and the pull request description says
so. Only the stale claim is corrected.

/// `setEngine` has not run here, and each host resolves `AS other_table` in its own catalog, so an
/// inherited engine has no single value the initiator could authorize.
if (!create.storage || !create.storage->engine)

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.

Returning here leaves legacy CREATE TABLE ... ON CLUSTER ... AS other_table on the exact bypass path this PR is trying to close. On distributed_ddl_entry_format_version = 2, execute() reaches executeQueryOnCluster before setEngine, so getRequiredAccess() has no TABLE ENGINE or engine-target element and preflightEngineTarget exits here. The queued query is then materialized on each worker under the default no-user DDL context, so inheriting a Remote / Merge / QueryRunner source still skips the engine-specific checks entirely.

Because distributed_ddl_entry_format_version is a per-query setting, one SET ... = 2 is enough to reopen the bypass on a supported path. If the initiator cannot soundly authorize inherited engines on this funnel, this combination still needs to fail closed here (or be accepted only when the worker preserves the initiating user).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed by measurement, and the funnel skips more than the engine checks this PR adds. For a user
holding nothing on prot (source prot.rsrc is ENGINE = Remote(..., prot, secret)):

statement result
CREATE TABLE udb.d ON CLUSTER c AS prot.rsrc Code: 497 ... SHOW COLUMNS ON prot.rsrc
the same without ON CLUSTER the same denial
the same with distributed_ddl_entry_format_version = 2 (or 1) accepted, Remote(..., 'prot', 'secret') stored
version 2 with the engine written out instead of inherited denied on the target, so the preflight does run there

So the privilege the legacy funnel drops is SHOW COLUMNS on the source table, checked at
InterpreterCreateQuery.cpp:897 when the initiator resolves AS. That check is master's and
predates this PR, which is why the gap is not specific to the engine-target checks here. Reading
rows through the created table is still denied, so what the user obtains is the definition and the
column list.

I am not closing it in this PR. A blanket refusal on that funnel was here until earlier today and was
removed because master's own 05030_totime_on_cluster_as_settings_in_zk_version asserts that a
version-2 CREATE ... ON CLUSTER ... AS src succeeds. A privilege-based refusal instead is a
different change, on a funnel that was narrowed in review a few days ago, and the alternative you
name is #111561's open question. The sibling Merge finding in the same review is fixed and pushed.

Comment thread src/Storages/StorageMerge.cpp Outdated
/// Runs the same per-source-table SHOW_COLUMNS checks as construction; the columns are
/// discarded. Unlike the member overload this does not reject a regexp matching no table,
/// so a statement the constructing host would accept is never rejected here.
StorageMerge::getColumnsDescriptionFromSourceTables(

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.

Using the static StorageMerge::getColumnsDescriptionFromSourceTables overload here turns "the initiator found no matching source table" into success. On ON CLUSTER, that is not equivalent to "nothing to authorize": if the source database exists on the initiator but only a target host has a table matching the regexp, this preflight returns cleanly, while the worker-side StorageMerge constructor still infers columns under its no-user DDL context and skips the SHOW COLUMNS check.

So the fail-open is broader than the UNKNOWN_DATABASE case discussed above. Any host-specific Merge match set can still leak the source schema through system.columns on the created table. If we cannot prove that the initiator and every executing host see the same source set, treating an empty local result as successful validation is still unsafe.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and it does not need the hosts to see different tables at all.
getColumnsDescriptionFromSourceTablesImpl filters on isGranted(SHOW_TABLES) before checking
SHOW_COLUMNS, so a source the issuing user cannot see is skipped on the initiator too, leaving
nothing to check. Measured on one node, user holding nothing on prot:

statement before
CREATE TABLE udb.m ON CLUSTER c ENGINE = Merge(prot, '^secret$') accepted, prot.secret's id UInt32, payload String stored in a table the user can read
the same without ON CLUSTER CANNOT_EXTRACT_TABLE_STRUCTURE
DESCRIBE prot.secret by that user Code: 497

Fixed in a314e5c7c812eab: the preflight requires SHOW COLUMNS for every table the initiator's
catalog matches, seen or not, through its own traversal so that merge() and the read path keep
their visibility semantics. The denial names the narrowest object the statement could already have
named, so a regexp does not become an enumeration oracle: SHOW COLUMNS ON prot.* here, *.* when
the database came from a REGEXP the user may not see, and ON prot.secret once it may see the
table, which is what the same statement without ON CLUSTER reports. Reverting only the source
change reddens the new case alone.

The half your wording describes remains: the initiator's catalog cannot name a table only a host
has, so that needs the host to run as the user (#111561). The absent-database tolerance also stays,
since rejecting it refuses statements that are legal when the initiator does not host the source.

`validateMergeEngineTarget` borrowed the schema-inference traversal, which skips a source
table the acting user may not `SHOW_TABLES` and only then checks `SHOW_COLUMNS`. On the
initiator that left the preflight vacuous for exactly the user it exists to stop: holding
nothing on the source database, the statement was accepted, and every host then inferred
the source's columns under its no-user DDL context, so
`CREATE TABLE t ON CLUSTER c ENGINE = Merge(prot, '^secret$')` stored the structure of a
table the user may not even `DESCRIBE`. The same statement without `ON CLUSTER` is refused,
because there the constructor infers under the user and finds nothing it may read.

`StorageMerge::checkSourceTablesAccess` runs that traversal without the visibility filter,
so every table the initiator's catalog matches has to be authorized. Because a denial names
the object it asks the grant for, and the regexps would turn that into an enumeration oracle,
it asks for the narrowest object the context could already have named: the table when the
context may see it, otherwise the database when the statement spelled it out or the context
may see it, otherwise nothing. The inference overload is untouched, so `merge()` and the read
path keep their own visibility semantics.

Measured on a single-node cluster. Before: accepted, with the hidden columns stored. After:
`ACCESS_DENIED ... SHOW COLUMNS ON prot.*` for a user holding nothing, `... ON *.*` when the
database came from a `REGEXP` it may not see, and `... ON prot.secret` once it may see the
table, which is byte for byte what the same statement without `ON CLUSTER` reports. Any of
those grants unblocks it, and an explicit column list still requires nothing. Reverting only
the source change reddens the new integration case alone, with `the statement was accepted`,
while the five pre-existing `Merge` cases keep passing.

Found while adjudicating a review of the same preflight's fail-open on an empty local match.
{
validateQueryRunnerTarget(*create.storage, getContext(), mode);
}
else if (engine_name == "Merge")

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.

Distributed with an omitted column list is still on the same bypass path. registerStorageDistributed resolves the schema under args.getLocalContext() for a fresh definition, so a plain CREATE TABLE ... ENGINE = Distributed(...) does the SHOW COLUMNS check there, but ON CLUSTER still reaches that code only on each DDL worker under its no-user context. Because this new preflight handles Remote/RemoteSecure, Merge, and QueryRunner but not Distributed, CREATE TABLE ... ON CLUSTER ... ENGINE = Distributed(cluster, db, protected) can still materialize protected's columns where the local form is denied.

Please add the same initiator-side omitted-structure preflight for Distributed, or fail closed on that shape until the worker preserves the issuing user.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on the fact. The preflight branches on Remote/RemoteSecure, QueryRunner and Merge only, and the asymmetry is real. Measured on ca88c417a70bb36 (the head since then changes only the Merge arm and a comment, so it still holds): single node, cluster test_shard_localhost, a user holding CREATE TABLE on its own database plus TABLE ENGINE ON Distributed and CLUSTER, and nothing at all on the target.

statement observed
CREATE TABLE dprobe.local_dist ENGINE = Distributed('test_shard_localhost', dprobe, protected) Code: 497 ... necessary to have the grant SHOW COLUMNS ON dprobe.protected
the same with ON CLUSTER test_shard_localhost accepted; system.columns and DESCRIBE then expose secret_col UInt64, other_col String

Not folding it into this PR. The preflight it would reuse is introduced here, so its fix is sequenced right after this one rather than inside it. This PR already spans four engine names across 13 files, and growing it further before review is the wrong trade. The gap is tracked with the repro above, so it is not lost.

Not failing closed on that shape either. It is the form the deployment guide tells users to write. docs/guides/oss/deployment-and-scaling/examples/2-shards-1-replica.mdx:

CREATE TABLE IF NOT EXISTS uk.uk_price_paid_distributed
ON CLUSTER cluster_2S_1R
ENGINE = Distributed('cluster_2S_1R', 'uk', 'uk_price_paid_local', rand());

No column list. The same statement is in the 2-shards-2-replicas example and in all nine translations, 18 occurrences in total. Refusing it would reject documented input, so the initiator-side preflight is the only remedy I would take.

If a reviewer would rather have it in this PR, say so and I will add it.

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.

Yes, I think this needs to land in this PR. Distributed with an omitted column list is still a straight local-vs-ON CLUSTER SHOW COLUMNS bypass on the same CREATE TABLE ... ON CLUSTER surface, and the initiator-side preflight added here is already the mechanism that can close it. Leaving that carrier open would make the contract of this change materially incomplete.

@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026
Resolves the one conflict, in `registerStorageRemote`. Our side deletes that block
(its logic moved into `parseAndValidateRemoteEngineTarget`, shared with the new
initiator-side preflight); master's side keeps it. Took our empty side by editing the
marked region only, rather than `git checkout --ours`, which would also have discarded
master's other, auto-merged changes to the same file: the two
`hasLimitAfter()`/`limitAfter()` guards in `getOptimizedQueryProcessingStage` and the
Mintlify admonition migration in the engine's documentation block. Both verified present
afterwards.

The part that mattered was outside the conflict markers. Master's change to the deleted
block came from ClickHouse#118221, which added a third disjunct to the guard:

    || args.getLocalContext()->isRecoveryFromStoredMetadata()

Without it, a `Replicated` database replaying metadata it stored in Keeper re-analyzes a
persisted `Remote` engine's table function target, and a target that legitimately matches
nothing now fails the replica's initialization. Recovery cannot be recognised from
`args.mode`, which it shares with an ordinary secondary-replica `CREATE` that must keep
validating, so the flag is carried on the context.

`validateRemoteEngineTarget.cpp` exists only on this branch, so git had no reason to
report anything there, and a resolution that only removed the conflicted block would have
reverted ClickHouse#118221 silently while compiling and passing this branch's own tests. Ported the
disjunct into the helper and amended the route enumeration above it, which had claimed
that only server startup and a short `ATTACH` skip the analysis. The second comment
ClickHouse#118221 amended needs no change here: this helper's `analyze_table_function_target`
comment does not enumerate those routes.

Verified on the merged tree with two servers sharing one Keeper and one `tcp_port` across
`127.0.0.1` and `127.0.1.1`, so the target is a local shard on both (`is_local = 1`
measured on each; without that every probe below passes vacuously).

This branch's own fix, under `GRANT CLUSTER ON *.*` so the query reaches the preflight
rather than stopping at the cluster gate: an `ON CLUSTER` `Remote` over a table the user
cannot read is refused with `SELECT ON occ.protected` when the structure is given and
`SHOW COLUMNS ON occ.protected` when it is omitted, matching the local form; with the
grants both succeed, and the omitted form infers `secret_col UInt64, other_col String`.

ClickHouse#118221's invariant, both halves: a fresh `CREATE` naming an absent `merge()` target is
still rejected with `BAD_ARGUMENTS`, while a second replica of the same Keeper path
instantiates the stored definition with its recorded columns, logging no initialization
error and no target re-analysis. The fresh-CREATE rejection is the control proving the
analysis is reachable on that server, so the asymmetry is the evidence.

Submodules were resynced to the merged pins after the ownership gate reported the
worktree's own plumbing; no `contrib` drift against master remains.

Co-Authored-By: Claude Opus 5 <[email protected]>
{
validateQueryRunnerTarget(*create.storage, getContext(), mode);
}
else if (engine_name == "Merge")

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.

preflightEngineTarget still enumerates only Remote/RemoteSecure, QueryRunner, and Merge, but the unified URL engine also defers a security-relevant check until storage construction: tryDispatchURLEngineByScheme requires TABLE ENGINE on the chosen delegate backend (File, S3, HDFS, AzureBlobStorage, ...) only on the host that builds the storage. On CREATE TABLE ... ON CLUSTER, that host is still a DDL worker running with no user, so ENGINE = URL('file:///...', ...) can still bypass the delegate-engine grant even though the same statement without ON CLUSTER is denied. This is the same initiator/worker split the new preflight is fixing for Remote and QueryRunner, so URL needs an initiator-side preflight too.

@groeneai

Copy link
Copy Markdown
Collaborator Author

URL delegate grant: confirmed by measurement, and it reframes the scope question

Measured on this PR's head 37cf9ab, single node, test_shard_localhost. User granted TABLE ENGINE ON URL and CLUSTER ON *.*, not granted TABLE ENGINE ON File:

statement observed
CREATE TABLE t (a String, b UInt64) ENGINE = URL('file:///.../probe.csv', 'CSV') Code: 497 ... necessary to have the grant TABLE ENGINE ON File
the same with ON CLUSTER test_shard_localhost accepted; the user then reads that file and appends to it with INSERT

Controls: granting TABLE ENGINE ON File makes the local form succeed, so the denial arm is not vacuous; a user without TABLE ENGINE ON URL is still denied under ON CLUSTER, so what is skipped is the delegate check specifically, not engine checks in general. system.query_log shows the worker replay of the queue entry running with an empty user, which is the mechanism.

The check being defeated is the one added in f23989503b8 ("a user granted only URL cannot create File/S3/Azure/HDFS backed tables"). It is not new to this PR: that commit is contained in 26.7 and 26.8, and StorageURL.cpp is not in this PR's diff.

The part I did not expect: closing it needs no code. With server setting distributed_ddl_use_initial_user_and_roles = 1 plus distributed_ddl_entry_format_version = 8, the same ON CLUSTER statement is denied by the worker with TABLE ENGINE ON File, and the queue entry carries initiator_user. Two traps for anyone trying it: the server setting has to be present at startup (after SYSTEM RELOAD CONFIG the enqueued entry still carried an empty initiator_user), and the entry format version defaults to 5 while initiator_user is only serialized from 8, so the server setting on its own is silently inert.

That leaves two shapes, and the choice is not mine to make:

  1. Keep extending the initiator preflight engine by engine. This PR covers Remote, RemoteSecure, QueryRunner and Merge; Distributed and URL would be next, and the enumeration is only ever as complete as the next engine that defers a check to storage construction.
  2. Have the DDL worker run as the initiator's user, which closes the whole family at once and already works behind those two settings.

@PedroTadim you cc'd this PR in August, and you classified the ATTACH sibling of this same delegate check as a critical bug fix in #115914, so I would rather have a ruling than guess. If (1), I will add Distributed and URL here. If (2), I would leave this PR as it stands and put the effort into the worker instead, which is really @ alexey-milovidov's call since the check in f23989503b8 is his. Both follow-ups are planned either way; the only thing I am waiting on is which.

This answers #113073 (comment) and #113073 (comment).

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I would prefer with 2, which is the general solution. How many lines would take to implement it?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Two lines, and the distributed_ddl_entry_format_version default does not have to move.

The mechanism already exists, behind distributed_ddl_use_initial_user_and_roles (#71334): executeDDLQueryOnCluster.cpp:219-223 fills initiator_user when the setting is on, and DDLTask.cpp:333-353 adopts that principal on the worker. What is missing is that toString() serializes the field only from INITIATOR_USER_VERSION = 8, while the entry version comes from distributed_ddl_entry_format_version (default 5), so the server setting on its own is silently inert. One line at the enqueue site closes that, mirroring the parent_table_uuid idiom a few lines above it in setSettingsIfRequired: version = std::max(version, INITIATOR_USER_VERSION) when the server setting is on. Rolling upgrades are safe, since DDL_ENTRY_FORMAT_MAX_VERSION is already 8 in 26.5, 26.6, 26.7 and 26.8, so every supported worker parses a version-8 entry. The second line is the default flip at ServerSettings.cpp:1201.

The cost is not in the line count. DDLTask.cpp:340 and :349 throw UNKNOWN_USER / UNKNOWN_ROLE when the initiator's user or one of its roles is absent on the executing node, so flipping that default turns every ON CLUSTER DDL issued by a user that is not present on all nodes into a hard failure. The setting's own description says it "requires that the user and roles exist on all nodes", so I read the default-off as deliberate: clusters with users in per-node users.xml, or with non-replicated SQL-driven access, would break on upgrade.

Two shapes avoid that, both still small:

  1. adopt the initiator's principal for the access check only, and fall back to today's behaviour when the principal is absent instead of throwing;
  2. leave the default off and make the setting the documented remedy for this class, so the bypass is closable by configuration rather than silently open.

I would build (1), but the default-off choice is @ pufit's from #71334 and the reason behind it decides which of these is right, so I do not want to overrule it on my own reading. Tell me which you prefer, or pull him in, and I will send it.

In the meantime I am leaving this PR as it stands, with no Distributed or URL branch added to the initiator preflight, since the general solution makes that enumeration unnecessary.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 37cf9ab

CI is fully finished on this head: 176 praktika leaves, 150 success / 22 skipped / 4 failure. Two of the four are the PR and Mergeable Check rollups, which only mirror the two stateless failures below.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, targeted) / 03710_analyzer_limit_by_aggregate_validation (5 retries, plus the runner's Too many test failures marker) trunk regression, reproduced on master itself a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Stateless tests (arm_binary, parallel) / 03710_analyzer_limit_by_aggregate_validation trunk regression, reproduced on master itself a fix task is created (investigating at full effort, fixing PR link to follow on this PR)

Bugfix validation (integration tests, amd64 and aarch64) is deliberately absent from the table: both jobs concluded success. The 14 red rows CIDB records under them are the expected-to-fail-on-master arm of the bugfix contract, that is, this PR's new test_on_cluster_create_engine_access cases failing against a master binary that lacks the fix. That is the check passing, not a failure to own.

On 03710_analyzer_limit_by_aggregate_validation: it is unrelated to this PR's diff. This PR touches ON CLUSTER CREATE authorization (InterpreterCreateQuery, StorageMerge, StorageDistributed, StorageQueryRunner, validateRemoteEngineTarget, plus one new integration test); the failing test exercises analyzer LIMIT BY validation, and none of the 13 files in the diff is on that path.

The signature is one day old and master carries it without this PR. Over 90 days CIDB holds 39 failing rows for this test, every one of them on 2026-09-14 from 13:37:41Z onward and zero before that, spread over 12 unrelated PRs plus 2 true-master shas (7f4f8755 and 0642d3da, both Stateless tests (amd_release, parallel, 2/2)). The harness has already isolated the culprit setting deterministically, so the fix task starts from a reproduction rather than from a hunt.

I did not link an existing PR as the owner: the open injectivity PRs in this area (#117197, #117238, #117894) all predate the onset by about two weeks and none of them targets this test, so linking one would be a coincidental same-area link rather than a fix.

Session id: cron:our-pr-ci-monitor:20260914-180106

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 03710_analyzer_limit_by_aggregate_validation: #120070 (not mine, open).

It stops OptimizeLimitByInjectiveFunctionsPass from unwrapping a LIMIT BY key past a GROUP BY key, which is the defect behind this failure: LIMIT BY is evaluated after aggregation, so the argument the key was unwrapped to is no longer in the block. I built that patch locally and confirmed it turns the failing query green under optimize_injective_functions_in_group_by = 0, so I am tracking it rather than opening a second PR for the same defect.

groeneai and others added 3 commits September 28, 2026 13:09
One conflict, in `registerStorageRemote`: this branch deletes the block whose logic
moved into `parseAndValidateRemoteEngineTarget`, master keeps it. Took this branch's side
by editing the marked region only, so master's auto-merged hunks in the same file stay.

Master changed that block once since the previous merge. ClickHouse#121335 clears the column TTLs
of a structure inferred from another table (`columns.clearColumnTTLs()`): `Remote` stores
no data, and a copied TTL makes the table unloadable once an `ALTER` persists it. The
block now exists only on master's side, so git reported nothing about that line. Ported
to where this branch adopts the inferred columns, the only place they become the
storage's structure; the preflight discards them and needs no change. Diffing master's
block at the old and new merge bases shows that call as its only change.

The `ErrorCodes` list conflicted too: kept master's new `ILLEGAL_COLUMN`, and
`ACCESS_DENIED`, which has no use left in the file, stays removed.

ClickHouse#117791's new `is_fresh_definition` constructor argument merged cleanly into this
branch's `registerStorageRemote` call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ClickHouse#117572 made `Merge` schema inference require `SHOW COLUMNS` on the target of an `Alias`
source table, in `getColumnsDescriptionFromSourceTablesImpl`, because an `Alias` reports
its target's columns. `checkSourceTablesAccess` walks the same source tables for the
`ON CLUSTER` preflight and did not follow, so on the merged tree a local
`CREATE TABLE ... ENGINE = Merge(db, '^alias$')` is denied while the `ON CLUSTER` form is
accepted and every host, running with no user, stores the target's columns in a table
the issuing user can describe. The preflight now makes the same check, with the same
message.

`Remote` needs no change: its preflight infers through `getStructureOfRemoteTable`,
where ClickHouse#117572 added the equivalent check. The new test covers both carriers, each
paired with the same statement run locally, then with the target granted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
{
validateQueryRunnerTarget(*create.storage, getContext(), mode);
}
else if (engine_name == "Merge")

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 whitelist is still fail-open on the current tree. Two concrete carriers that already exist outside this diff are:

  • StorageAlias, which requires SHOW_COLUMNS on every fresh target at src/Storages/StorageAlias.cpp:649.
  • StorageBuffer, which requires SHOW_COLUMNS when it infers an omitted destination schema at src/Storages/StorageBuffer.cpp:1623.

Neither engine is covered here, so CREATE TABLE ... ON CLUSTER ENGINE = Alias(...) (or Buffer(...) without an explicit column list) still reaches those checks only on the DDL worker's no-user context and bypasses them. The created table then exposes the protected schema through its own metadata even though the same local CREATE is denied.

So the new initiator-side preflight is not closed over the current engine set: extending the per-engine list later is still required unless the worker starts running the access checks as the initiating user.

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-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants