Repository navigation
Replace ExpressionAnalyzer with Analyzer for standalone expression compilation - #96886
alexey-milovidov wants to merge 308 commits into
Conversation
|
Workflow [PR], commit [59c296f] Summary: ❌
AI ReviewSummaryThe PR replaces standalone Findings❌ Blockers
Missing context / blind spots
Tests
Final VerdictStatus: ❌ Block Close the cluster constraint-authorization bypass and preserve lambda bindings during row-policy alias expansion, with the focused regression coverage above. Keep both existing blocker threads open until those changes are verified. |
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
|
The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158 |
…pport `TTL ... WHERE col IN (SELECT ...)` regressed in this PR because `buildExpressionAndSets` was migrated to `analyzeExpressionToActionsDAG`, which eagerly builds subquery sets via `buildSetInplace` during analysis. That caused `Key expressions cannot contain subqueries` or unwanted subquery execution at DDL time. Revert `buildExpressionAndSets` in `TTLDescription.cpp` to the legacy `TreeRewriter` + `ExpressionAnalyzer` path so subqueries become `FutureSetFromSubquery` and are evaluated lazily when TTL is actually applied. Also drop the newly added `checkExpressionDoesntContainSubqueries` guard on the TTL `WHERE` AST — subqueries are legitimate there and are exercised by tests `02908_table_ttl_dependency`, `02932_set_ttl_where`, `03236_create_query_ttl_where`, `04029_ttl_delete_filter_vertical_merge_subquery`, and `04039_ttl_where_in_subquery_vertical_merge`. The guard on the main TTL expression (`TTLDescription::getTTLFromAST`) is preserved — subqueries remain forbidden in the expression that produces the TTL value itself. CI report: #96886 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two small follow-ups after merging master:
- `GlobalPlannerContext` gained a new `parallel_replicas_table_union_`
parameter in master. Update both `std::make_shared<GlobalPlannerContext>`
calls in `AnalyzeExpression.cpp` to pass `nullptr` for it so the file
compiles again.
- Revert `01160_tables_with_no_dependencies.sh` to use
`nonexistent_column` instead of `COLUMNS('')` for the sharding key.
With the Analyzer-based expression analysis, an empty `COLUMNS('')`
matcher no longer produces `UNKNOWN_IDENTIFIER` during CREATE analysis
(it falls through to cluster lookup instead), so the `grep -F
UNKNOWN_IDENTIFIER` assertion stopped firing. `nonexistent_column`
reliably exercises the same no-loading-dependencies invariant the test
was added to protect.
CI report: #96886
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
After commit `dece1664c54` reverted `buildExpressionAndSets` (TTL) to the
legacy `TreeRewriter` + `ExpressionAnalyzer` path to preserve `FutureSet`
semantics, `ALTER TABLE ... TTL indexHint(*)` once again raises
`UNKNOWN_IDENTIFIER` (47) instead of `BAD_ARGUMENTS` (36). Restore the
expected error code in `03571_trying_to_get_name_of_not_a_column_asterisk`.
For `02111_global_context_temporary_tables`, the 4th query
`remote('127.1', view(SELECT number AS id FROM numbers(2)), 1 IN id)`
succeeds in the old-analyzer build because the new
`buildShardingKeyExpression` resolves `id` correctly as the view's column.
Use `1 IN nonexistent` so the query fails with `UNKNOWN_IDENTIFIER` in
both old and new analyzer modes.
CI report: #96886
| auto storage = DatabaseCatalog::instance().tryGetTable(table_id, context); | ||
| return storage && castStorage<StorageSet>(storage, DeferredTable::Load); |
There was a problem hiding this comment.
[Blocker] Check source-table visibility before testing its engine
This catalog lookup and castStorage run without any access check, and their result changes whether DDL succeeds. On the exact PR-head binary, a user granted only CREATE TABLE on oracle_owned.* can run:
CREATE TABLE oracle_owned.t
(x UInt64, CONSTRAINT c CHECK x IN oracle_secret.target)
ENGINE = MergeTree ORDER BY x;This succeeds when the inaccessible target exists and uses Set, but returns BAD_ARGUMENTS when it uses MergeTree or does not exist. A direct SELECT from the same protected Set table returns ACCESS_DENIED. ALTER TABLE ... ADD CONSTRAINT exposes the same distinction. The ASSUME equivalents all succeed, confirming that the existing metadata-analysis path does not introduce this distinction.
Thus the new validator reveals a protected table's existence and engine to users without privileges on it. Enforce source metadata visibility before inspecting the storage type, consistently with Analyzer table resolution, and add restricted-user coverage for the CREATE and ALTER entrypoints.
There was a problem hiding this comment.
🕵 Fixed in 68ba794. isSetTable now calls checkAccess(SHOW_TABLES, database, table) on the resolved table ID before it looks the table up. The check does not depend on whether the table exists, so a user without access gets ACCESS_DENIED whether the target is a Set table, a MergeTree table, or absent, from both CREATE TABLE and ALTER TABLE ... ADD CONSTRAINT. Once access is granted, the Set table is accepted and the MergeTree table is still rejected with BAD_ARGUMENTS. Covered by 05621_check_constraint_set_table_access.
There was a problem hiding this comment.
[Blocker] The visibility issue remains through ALTER TABLE ... ON CLUSTER on the current head.
src/Interpreters/InterpreterAlterQuery.cpp:723 returns through executeDDLQueryOnCluster before the new checkAddedConstraintPermissions call at line 754. Its additional_access_check callback (lines 698–722) does not validate constraints.
With the default distributed_ddl_use_initial_user_and_roles = false, the DDL worker executes without the submitting user; Context::getAccess grants that context full access. Consequently AlterCommands::validate reaches isSetTable with permission to inspect the protected table. A user with CLUSTER globally and only ALTER ADD CONSTRAINT on owned.t can submit:
ALTER TABLE owned.t ON CLUSTER cluster
ADD CONSTRAINT c CHECK x IN secret.target;The source trace still gives success for an inaccessible Set target and BAD_ARGUMENTS for another engine or an absent target, and the worker's status is returned to the user. This does not require SHOW TABLES on secret.target. I have not executed the reproduction in this CI job.
Run the constraint authorization from the ON CLUSTER callback before enqueueing when workers do not preserve the initiating user, and extend 05621 to that entrypoint. The new Replicated-database check covers that queue, but not this earlier return.
# Conflicts: # src/Storages/IndicesDescription.cpp
…ting to replicas When a plain `MergeTree` initiator routes the read to the replicas of `cluster_for_parallel_replicas` (`parallel_replicas_count = 0`), the custom key was resolved by `buildFilterQueryTree` only for the access check, and the tree was discarded without `checkCustomKeyQueryTreeReadsOnlyRow`. The replicas then received the filter generated from the AST, so a qualified `ALIAS` reference like `q.a` could bring a `Set` table into the partitioning expression. Apply the check there and in the view pushdown path over a `Distributed` table too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`05572_parallel_replicas_custom_key_resolved_binding` failed under randomized `serialize_query_plan` (`NOT_IMPLEMENTED`) and with the randomized `cluster_for_parallel_replicas` / `parallel_replicas_for_non_replicated_merge_tree`, which turned the follower query into a read over a cluster. Pin these settings, as the other custom key tests do. `05573_parallel_replicas_custom_key_udf_lambda_capture` depended on the order of `groupArray`; sort the arrays and pin the same settings. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96886&sha=latest&name_0=PR #96886 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes `readability-duplicate-include` in `Build (arm_tidy, 1/4)`: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96886&sha=b12d5e230e4f3234ae5e0bb294d3fc7ba3647b94&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 PR: #96886 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n a `CHECK` constraint `isSetTable` looked up the table on the right-hand side of `IN` and checked whether it is a `Set` table without any access check, and the result decided whether `CREATE TABLE` or `ALTER TABLE ... ADD CONSTRAINT` succeeded. A user with no privileges on the table could learn whether it exists and whether it is a `Set` table. Check `SHOW_TABLES` on the resolved table ID first; the check does not depend on whether the table exists, so the outcome is `ACCESS_DENIED` for a `Set` table, any other table, and an absent one alike. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ting the custom key `isColumnIdentifier` and `expandAliasColumns` used `isTableExist` without an access check to decide whether `x.y` on the right-hand side of `IN` is a table, so whether `parallel_replicas_custom_key` was accepted revealed the existence of a protected table. Treat a table that the user may not see (`SHOW_TABLES`) as absent. Such a key is then left to the analyzer, whose binding is checked by `checkCustomKeyQueryTreeReadsOnlyRow` and which handles the identifier exactly as in an ordinary `WHERE x IN db.t` filter. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Status update, head is now
|
…analyzer-with-analyzer Conflict resolution: - `QueryAnalyzer` constructor: keep master's `view_source_in_subqueries_` and append the PR's typo hint parameters after it. - `WhatIfEstimator.cpp`: take master's rework, which no longer rebuilds the index from AST at estimate time. - `optimizeDirectReadFromTextIndex.cpp`: keep the PR's AST-valued capture map, using master's `UnorderedMapWithMemoryTracking`. - `04908_constraint_subquery_loading_dependency`: deleted, as master reverted the feature it tests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…int_set_table_access` With `table_engines_require_grant` enabled, `CREATE TABLE ... ENGINE = MergeTree` by the test user failed with `ACCESS_DENIED` for the missing engine grant, which also masked the access check the test is about. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96886&sha=d125d47808040b5d36dce65c37a5ba44b88135f9&name_0=PR&name_1=Fast%20test #96886 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Status update, head is now
|
|
Dear @KochetovNicolai, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
…analyzer-with-analyzer Master moved the planner steps out of `Planner.cpp` into `PlannerSteps.cpp` and declared `collectFiltersForAnalysis` in `PlannerSteps.h`. The conflict in `Planner.cpp` is resolved by taking master's version; this branch's change to `addAdditionalFilterStepIfNeeded` (keep the result header with `makeFilterKeepHeader`) is ported to `PlannerSteps.cpp`, and the duplicate `collectFiltersForAnalysis` declaration in `Planner.h` is dropped in favour of including `PlannerSteps.h` in `AnalyzeExpression.cpp`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rallel replicas custom key Master added the `view_source_in_subqueries` parameter before `check_access_rights`, so `/*check_access_rights=*/ true` was silently bound to `view_source_in_subqueries` and the column-level access check of the custom key filter was skipped. This was caught by clang-tidy (`bugprone-argument-comment`) and by the failing test `05076_additional_table_filters_column_access`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96886&sha=620c4a5b4b18f3a30927d7a8a4c1e6b8fbe69304&name_0=PR PR: #96886 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…materialized view The old `ExpressionAnalyzer` path planned the `IN` subquery of a standalone expression (e.g. a row policy applied while a `Merge` table reads its child) with `interpretSubqueryWithAnalyzer`, which substitutes the view source. The `analyzeExpression` path planned it against the catalog table instead, so under a materialized view over a `Null` table the set was empty. Replace the view source in the set subqueries, plan them with `view_source_in_subqueries`, and let the analyzer read the view source in scalar subqueries as well. Fixes the failing test `05321_in_subquery_of_standalone_expression_under_materialized_view`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96886&sha=620c4a5b4b18f3a30927d7a8a4c1e6b8fbe69304&name_0=PR PR: #96886 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Status update, head is now
|
…analyzer-with-analyzer Conflicts: - `ReadFromMergeTree.cpp`: master replaced the per-query analysis of the sorting-key prefix with `getSortingKeyPrefixExpression`, which cuts the already compiled key expression. Took master's version; the legacy `ExpressionAnalyzer` call this PR converted is gone. Updated the comment in `requestReadingInOrder` accordingly. - `Iceberg/Utils.cpp`: master evaluates every sort key on its own inputs in `sortBlockByKeyDescription`. Took master's version and ported it to `analyzeExpressionToActions`. - `ProjectionsDescription.cpp`: master removed `getSingleExpressionForProjections`. Took master's version. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…`Replicated` database A host of a `Replicated` database applies `ALTER TABLE ... ADD CONSTRAINT` without the submitting user, so `ConstraintsDescription::validateNoSubqueries` in `AlterCommands::validate` did not see the user's access rights there: `CHECK x IN db.table` was accepted when `db.table` is a `Set` table and rejected with `BAD_ARGUMENTS` otherwise, even when the user may not see the table. Run the check as the submitting user before the statement is enqueued, like `checkAddedIndexPermissions`. Fixes `05621_check_constraint_set_table_access` in the `DatabaseReplicated` job: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96886&sha=f787ad174dd999a9bd882093fa00f3e86990b6e1&name_0=PR #96886 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…n is drawn With plan-based parallel replicas `EXPLAIN` draws the plan as a tree, so the line with `Granules` starts with `│`, which `trim` does not remove. Use `extract` instead. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96886&sha=f787ad174dd999a9bd882093fa00f3e86990b6e1&name_0=PR #96886 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Status update, head is now
|
After merging `master`, `FunctionNode::isOrdinaryFunction`, `isWindowFunction` and `isAggregateFunction` no longer exist. Use `isOrdinaryCall`, `isWindowCall` and `isAggregationCall` instead. The window check runs first, so the meaning is unchanged. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ECK` constraint rules The test was added in `master` with `CHECK x < (SELECT count() + 1000 FROM t_probe)`. This PR intentionally rejects a scalar subquery in a `CHECK` constraint with `BAD_ARGUMENTS`, so the test failed in Fast test at `CREATE TABLE`. Use the allowed form, a direct subquery on the right-hand side of `IN`. Its set is built at insert time and is not analyzed when the table is loaded, so `SYSTEM RESTART REPLICA` succeeds while the referenced table is missing, the table stays in place, and it is the `INSERT` that reports `UNKNOWN_TABLE`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96886&sha=c3c261bdfccce8a4561901ac4be8e7a1a0bf7340&name_0=PR&name_1=Fast%20test #96886 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Status update, head is now
One observation outside this PR's scope, seen on this branch only (not re-checked on |
| || !occursOutsideLambdaArguments(expanded_expr, column_name, {}); | ||
| }); | ||
|
|
||
| if (reads_only_storage_columns) |
There was a problem hiding this comment.
[Blocker] Preserve lambda bindings during row-policy alias expansion
replaceAliasColumnsInQuery immediately above uses ColumnAliasesVisitor, whose lambda mask contains only the exact parameter name (z). If a table has an ALIAS column literally named z.v, it therefore replaces the bound lambda field z.v with that column's expression. This check then accepts the rewritten policy because its dependencies are physical columns.
For example:
CREATE TABLE t
(
tenant String,
arr Array(Tuple(v String)),
`z.v` String ALIAS tenant
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (tenant, arr) VALUES ('a', [tuple('b')]);
CREATE TABLE m (tenant String, arr Array(Tuple(v String)))
ENGINE = Merge(currentDatabase(), '^t$');
CREATE ROW POLICY p ON t
USING arrayExists(z -> z.v = 'a', arr) TO ALL;
SELECT tenant FROM t;
SELECT tenant FROM m;Tracing the current code, the direct policy resolves z.v through the lambda argument and excludes this row. The Merge policy becomes arrayExists(z -> tenant = 'a', arr) and admits it, disclosing a row the policy forbids. QueryAnalyzer::tryResolveIdentifier gives lambda arguments precedence, so the alias-expansion pass must preserve that same binding. The helper defect predates this PR, but the changed policy-compilation path still reaches it; this is a source trace, without runtime confirmation in this CI job.
Make ColumnAliasesVisitor also protect fields rooted at bound lambda arguments, and cover the dotted-ALIAS collision with a direct-versus-Merge policy regression.
Replace legacy
ExpressionAnalyzerwith the modern Analyzer framework for standalone expression compilation across storage metadata, MergeTree operations, and query planning.This also rejects invalid
CHECKconstraints containing forbidden subqueries or table names, includingx IN other_table; directx IN (SELECT ...)remains supported. Key and skip-index expressions reject wildcards and column matchers at DDL time.Because key and skip-index expressions are now compiled by the Analyzer, a typo in one is reported with the Analyzer's wording (
Unknown expression identifier) instead ofMissing columns. The scope in those messages is the expression itself, so the synthetic table that the standalone-expression helper analyzes over is not exposed to the user. TTL expressions keep theTreeRewriterpath - a TTLWHEREclause may contain subqueries, which have to stay lazy - and therefore keep their previous wording.It also fixes a pre-existing crash on the read-in-order path.
ReadFromMerge::requestReadingInOrdercomputes one sorting-key prefix from the metadata of the tables aMergetable selected and hands it to everyReadFromMergeTreereachable from the child plans, including reads whose own sorting key is shorter, andReadFromMergeTree::requestReadingInOrderaccepted any prefix.spreadMarkRangesAmongStreamsWithOrderthenresizes the sorting-key expression list to that prefix, which grows the list and pads it with nullASTPtrs instead of cutting it, and indexes the column names past their end. AStorageAliaschild whose target is swapped between the two name resolutions makes the prefix and the key diverge; onmasterthat segfaults inTreeRewriter. The prefix is now refused at the single funnel every prefix arrives through, so the query falls back to a full sort - reads whose prefix comes from their own metadata cannot trip the guard.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Replace legacy
ExpressionAnalyzerwith the modern Analyzer framework for standalone expression compilation.CHECKconstraints with forbidden subqueries or table names, and key expressions with wildcards or column matchers, now fail withBAD_ARGUMENTSat DDL time. A typo in a key or skip-index expression is now reported asUnknown expression identifierwith amaybe you meanthint. Also fixed a crash when aMergetable asked a child table to read in order with a sorting-key prefix wider than that child's own sorting key.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/96886]