Skip to content

Replace ExpressionAnalyzer with Analyzer for standalone expression compilation - #96886

Open
alexey-milovidov wants to merge 308 commits into
masterfrom
replace-expression-analyzer-with-analyzer
Open

alexey-milovidov wants to merge 308 commits into
masterfrom
replace-expression-analyzer-with-analyzer

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Feb 14, 2026 •

Copy link
Copy Markdown
Member

Replace legacy ExpressionAnalyzer with the modern Analyzer framework for standalone expression compilation across storage metadata, MergeTree operations, and query planning.

This also rejects invalid CHECK constraints containing forbidden subqueries or table names, including x IN other_table; direct x 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 of Missing 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 the TreeRewriter path - a TTL WHERE clause 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::requestReadingInOrder computes one sorting-key prefix from the metadata of the tables a Merge table selected and hands it to every ReadFromMergeTree reachable from the child plans, including reads whose own sorting key is shorter, and ReadFromMergeTree::requestReadingInOrder accepted any prefix. spreadMarkRangesAmongStreamsWithOrder then resizes the sorting-key expression list to that prefix, which grows the list and pads it with null ASTPtrs instead of cutting it, and indexes the column names past their end. A StorageAlias child whose target is swapped between the two name resolutions makes the prefix and the key diverge; on master that segfaults in TreeRewriter. 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):

  • Improvement

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

Replace legacy ExpressionAnalyzer with the modern Analyzer framework for standalone expression compilation. CHECK constraints with forbidden subqueries or table names, and key expressions with wildcards or column matchers, now fail with BAD_ARGUMENTS at DDL time. A typo in a key or skip-index expression is now reported as Unknown expression identifier with a maybe you meant hint. Also fixed a crash when a Merge table 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

  • Documentation is written (mandatory for new features)

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

@alexey-milovidov alexey-milovidov changed the title Replace ExpressionAnalyzer with Analyzer for standalone expression compilation [WIP] Replace ExpressionAnalyzer with Analyzer for standalone expression compilation Feb 14, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft February 14, 2026 07:49
@clickhouse-gh

clickhouse-gh Bot commented Feb 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [59c296f]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR replaces standalone ExpressionAnalyzer compilation with the Analyzer, adds constraint/key/index validation, preserves expression naming and filter headers, and guards read-in-order sorting-key prefixes. Reviewed PR head 59c296fd919190bbe835d09442d3870872d14a49 and the current code, including prior discussion. Two existing security blockers remain. Both already have open inline threads; no duplicate comments were posted.

Findings

❌ Blockers

  1. Constraint validation still reveals protected table metadata through ALTER TABLE … ON CLUSTER. src/Interpreters/InterpreterAlterQuery.cpp:723 dispatches before checkAddedConstraintPermissions at line 754, and the cluster callback at line 698 does not check constraints. With the default distributed_ddl_use_initial_user_and_roles = false, workers validate with full access. A user with CLUSTER and ALTER ADD CONSTRAINT on owned.t, but no visibility of secret.target, can submit ALTER TABLE owned.t ON CLUSTER cluster ADD CONSTRAINT c CHECK x IN secret.target: the worker's success for a Set target versus BAD_ARGUMENTS for another engine or an absent target discloses protected metadata. Run the constraint authorization as the submitting user in the cluster callback before enqueueing, using the resolved default database. The earlier local and Replicated-database fixes do not cover this return. Existing thread and remaining-path explanation.

  2. Alias expansion can change a row policy's lambda binding and disclose forbidden rows through Merge. src/Storages/StorageMerge.cpp:2416 invokes ColumnAliasesMatcher, whose guard at src/Interpreters/ColumnAliasesVisitor.cpp:66 protects only exact lambda argument names. For a table with tenant String, arr Array(Tuple(v String)), and a literal ALIAS column named z.v whose expression is tenant, the policy arrayExists(z -> z.v = 'a', arr) is rewritten to test tenant inside the lambda. The dependency check at StorageMerge.cpp:2427 accepts that rewritten expression. A row with tenant = 'a' and arr = [tuple('b')] is excluded by the correctly bound direct policy but admitted through Merge. Preserve compound identifiers rooted at bound lambda arguments during ColumnAliasesMatcher expansion. The helper defect predates the PR, but the changed policy-compilation path still reaches it. Existing unanswered thread.

Missing context / blind spots
  • ⚠️ Both remaining findings were verified by tracing the current source; their reproductions were not executed in this CI job because no ClickHouse binary is available. The available CI reports report no test failures, but the existing tests do not cover these two cases.
Tests
  • ⚠️ Extend 05621_check_constraint_set_table_access with a restricted-user ON CLUSTER case, with initiator-user preservation disabled, covering inaccessible Set, other-engine, and absent targets. All must fail authorization before enqueueing.
  • ⚠️ Add a direct-versus-Merge row-policy regression with the dotted ALIAS/lambda-field collision above. Both reads must exclude the forbidden row.
Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Feb 14, 2026
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Mar 17, 2026
Comment thread preprocessed_configs/config.xml Resolved
Comment thread contrib/NuRaft Resolved
@alexey-milovidov alexey-milovidov removed the submodule changed At least one submodule changed in this PR. label Mar 20, 2026
Comment thread src/Storages/ConstraintsDescription.cpp Resolved
Comment thread src/Planner/AnalyzeExpression.h Resolved
Comment thread src/Planner/AnalyzeExpression.cpp Resolved
Comment thread src/Planner/AnalyzeExpression.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/TTLDescription.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

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

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Hung check failure is fixed by #102008 and #102010, let's update the branch

alexey-milovidov added a commit that referenced this pull request Apr 24, 2026
…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]>
alexey-milovidov added a commit that referenced this pull request Apr 24, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Apr 25, 2026
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
Comment thread src/Planner/AnalyzeExpression.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageMerge.cpp Resolved
Comment on lines +85 to +86
auto storage = DatabaseCatalog::instance().tryGetTable(table_id, context);
return storage && castStorage<StorageSet>(storage, DeferredTable::Load);

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.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 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.

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.

[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.

alexey-milovidov and others added 3 commits November 11, 2026 00:01
# 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]>
alexey-milovidov and others added 4 commits November 12, 2026 07:09
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update, head is now d125d4780804:

  • Fixed the Build (arm_tidy, 1/4) failure (readability-duplicate-include in IndicesDescription.cpp).
  • Merged master (770 commits behind). The merge was clean, and the binary builds.
  • Addressed both open blocker threads. CHECK constraint validation and parallel_replicas_custom_key validation now check SHOW_TABLES before looking up a table, so neither can reveal whether a protected table exists. Added the tests 05621_check_constraint_set_table_access and 05622_parallel_replicas_custom_key_table_access.
  • Ran the PR's constraint and custom-key stateless tests locally against the new binary: they pass, except one that needs 127.0.0.2, which my local server does not listen on.

alexey-milovidov and others added 2 commits November 14, 2026 22:13
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update, head is now 620c4a5b4b18:

  • Merged master and resolved conflicts: the QueryAnalyzer constructor keeps master's view_source_in_subqueries_ and the PR's typo-hint parameters; WhatIfEstimator.cpp takes master's rework (it no longer rebuilds the index from the AST at estimate time); optimizeDirectReadFromTextIndex.cpp keeps the AST-valued capture map with UnorderedMapWithMemoryTracking; 04908_constraint_subquery_loading_dependency is deleted, as master reverted the feature it tested (Make a table read by a scalar subquery in a CONSTRAINT a loading dependency #114923 revert).
  • Fixed the Fast test failure of 05621_check_constraint_set_table_access: the test user needs TABLE ENGINE ON MergeTree now that table_engines_require_grant is enforced.
  • Built the merged tree and ran all the tests this PR adds or changes locally: they pass. No review threads are open.

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

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.

alexey-milovidov and others added 3 commits November 19, 2026 10:23
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update, head is now f787ad174dd9:

  • Merged master. The conflict in Planner.cpp comes from master moving the planner steps to PlannerSteps.cpp: took master's Planner.cpp, ported this PR's makeFilterKeepHeader change in addAdditionalFilterStepIfNeeded to PlannerSteps.cpp, and dropped the duplicate collectFiltersForAnalysis declaration from Planner.h (it is declared in PlannerSteps.h now).
  • Fixed Build (arm_tidy) and 05076_additional_table_filters_column_access: master added view_source_in_subqueries before check_access_rights in buildFilterQueryTree, so /*check_access_rights=*/ true in the parallel-replicas custom-key filter was bound to the wrong parameter and the column access check was skipped.
  • Fixed 05321_in_subquery_of_standalone_expression_under_materialized_view: analyzeExpression now substitutes the view source in the set subqueries of a standalone expression under a materialized view (and lets the analyzer read it in scalar subqueries), as interpretSubqueryWithAnalyzer does on master.
  • Built locally. Both failing tests, 04368_mergetree_projection_table_function_row_policy, and the tests this PR adds or changes pass locally. The only ones that failed need clusters or ZooKeeper that the local server does not have.

alexey-milovidov and others added 3 commits November 22, 2026 01:15
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update, head is now c3c261bdfccc:

  • Merged master (1668 commits behind) and resolved the conflicts: ReadFromMergeTree.cpp takes master's getSortingKeyPrefixExpression (the legacy ExpressionAnalyzer call this PR converted is gone there); sortBlockByKeyDescription in Iceberg/Utils.cpp takes master's per-key evaluation, ported to analyzeExpressionToActions; ProjectionsDescription.cpp takes master's version, which removed getSingleExpressionForProjections.
  • Fixed 05621_check_constraint_set_table_access in the DatabaseReplicated job. It was a real bug: a host of a Replicated database applies ALTER TABLE ... ADD CONSTRAINT without the submitting user, so CHECK x IN db.table was accepted or rejected with BAD_ARGUMENTS depending on a table the user may not see. The check now runs as the submitting user before the statement is enqueued.
  • Fixed 05571_key_subexpression_lambda_name in the plan-based parallel replicas job: the plan is drawn as a tree there, so the test uses extract instead of trim.
  • 05829_autopr_skip_index_on_read_in_subquery is not related to this PR; it was fixed in master by 94e368e ("Pin 05829 to query-based parallel replicas"), which this merge brings in.
  • Local verification: every source file this PR changes compiles on the merged tree, and 05571 passes with a local binary. The full binary was not rebuilt locally and 05621 was not re-run against a Replicated database, so those rely on CI. No review threads are open.

alexey-milovidov and others added 3 commits November 24, 2026 20:32
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update, head is now df939e47f2a7:

  • Merged master (2505 commits behind). The merge was textually clean but did not compile: master renamed the FunctionNode predicates, so AnalyzeExpression.cpp now uses isOrdinaryCall, isWindowCall and isAggregationCall (same meaning, the window check still runs first).
  • Fixed the Fast test failure of 01646_restart_replica_definition_error_keeps_table. The test was added in master by Fix a table disappearing after a failed SYSTEM RESTART REPLICA #131883 with CHECK x < (SELECT count() + 1000 FROM t_probe), a scalar subquery that this PR intentionally rejects with BAD_ARGUMENTS. It now uses the allowed form x NOT IN (SELECT ...). This changes what the test pins: the set of such a constraint 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 the INSERT reports UNKNOWN_TABLE.
  • Local verification: built the merged tree and ran the stateless tests this PR adds or changes plus 01646 against a local server with embedded Keeper. 43 pass. The other 18 fail only because that minimal server lacks the CI configuration (test clusters, a writeable access storage, system.query_log / system.text_log, a backup disk), so they rely on CI.
  • CH Inc sync was red on the previous head and was not investigated in this pass; it will re-run on this push.
  • No review threads are open.

One observation outside this PR's scope, seen on this branch only (not re-checked on master): a definition error raised inside StorageFactory::get rather than in the columns or constraints analysis, e.g. TTL d + INTERVAL 1000 DAY DELETE WHERE x < (SELECT count() FROM db.t_probe) after t_probe is dropped, still leaves the table detached after a failed SYSTEM RESTART REPLICA. The pre-detach analysis added by #131883 covers columns and constraints only.

|| !occursOutsideLambdaArguments(expanded_expr, column_name, {});
});

if (reads_only_storage_columns)

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.

[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.

This branch was successfully deployed

1 active deployment
staging - docs — 59c296fd Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants