Skip to content

Calculate projections with the Analyzer - #118375

Merged
alexey-milovidov merged 30 commits into
masterfrom
use-analyzer-for-projections
Oct 14, 2026
Merged

alexey-milovidov merged 30 commits into
masterfrom
use-analyzer-for-projections

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Related: #75728

Reimplementation of #75728, which was closed as a duplicate of #96886. It is not a duplicate: #96886 replaces ExpressionAnalyzer for standalone expression compilation (key, skip-index and constraint expressions), while this is about the SELECT of a projection, which is still interpreted by the legacy InterpreterSelectQuery.

ProjectionDescription::calculateByQuery — the code which computes a projection block on INSERT, on merge and during a mutation — now uses InterpreterSelectQueryAnalyzer.

The columns of a projection part are named after the expressions of the projection query as they are written, because the projection metadata (sample_block) is derived from the AST. The Analyzer names the columns of a plan by its own rules — a column by the identifier of its table expression (__table1.a), a constant with its data type appended (1_UInt8), a set by its key — so the result of the pipeline is renamed back to the names of the metadata by mapping every expression of the query tree to the name its AST gives. Two more differences have to be reconciled: a tuple at the top level of GROUP BY, which the Analyzer unwraps into separate keys, and the ORDER BY expression, which ASTProjectionSelectQuery::cloneToASTSelect appends to the SELECT list and which may therefore duplicate a projection column.

A column of the metadata missing from the result is now reported instead of being silently dropped by the part writer, which would write a projection part without that column and read it back as the default value of its type. This check is what makes the change verifiable: with it, every naming difference fails loudly at INSERT time rather than corrupting a projection.

The synthetic table expression which stands in for the missing FROM clause of a projection query borrows the name of system.one. The Analyzer plans a read from a table expression as a read from a table, so it checks the access rights and applies the quotas for it, and calculating a projection must not require anything beyond the rights of the query which writes the data. 05084_projection_privileges_with_analyzer covers that a user with only INSERT, SELECT and OPTIMIZE on the table can still write and read its projections.

Because the synthetic table expression borrows the name of system.one, a row policy or an additional_table_filters entry for that name used to follow the borrowed name into the projection pipeline and reshape the data written into the projection part — a persistent corruption which survived DROP ROW POLICY and OPTIMIZE TABLE ... FINAL, reported by @zlareb1 in #118375 (comment). A storage which only stands in for a data source inside the server is now marked with IStorage::isSyntheticDataSource, and both the Analyzer and the legacy interpreter skip the row policies and the additional_table_filters of its name. The legacy interpreter matters too: it still builds the description of the minmax_count projection, so a policy for system.one could make a table fail to attach. 05227_projection_calculation_ignores_additional_table_filters and 05228_projection_calculation_ignores_row_policy_on_system_one cover both halves. After a merge with master, the row policy lookup lives in the shared getRowPolicyFilterForStorage, so the check is made there.

05182_projection_positional_arguments_with_analyzer covers a projection whose GROUP BY uses positional arguments (enable_positional_arguments_for_projections) end to end — the columns written on insert and on merge, and the result read back from the projection — which was asked for in #118375 (comment). calculateByQuery analyzes the projection query as an initial one, because the Analyzer does not resolve positional arguments of a SECONDARY_QUERY. 05318_projection_positional_arguments_remote_insert covers a remote INSERT.

Note: the messages of the two commits which answer this feedback cite those two links by wrong identifiers; the correct ones are the two above.

getAggregatingProjectionInfo in optimizeUseAggregateProjection still uses InterpreterSelectQuery. Switching it needs the same names on the optimizer side, because the aggregate descriptions and the aggregation keys it returns are used as the names of the columns to read from the projection part; without that, no aggregate projection matches any more. That is left for a separate change.

All 248 stateless tests matching projection pass, and 05083_projection_calculation_with_analyzer produces byte-identical output on master and on this branch, including every column name of every projection part.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Version info

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

`ProjectionDescription::calculateByQuery` interpreted the `SELECT` of a projection
with the legacy `InterpreterSelectQuery`. Use `InterpreterSelectQueryAnalyzer`.

The columns of a projection part are named after the expressions of the projection
query as they are written, because the projection metadata (`sample_block`) is
derived from the AST. The Analyzer names the columns of a plan by its own rules - a
column by the identifier of its table expression (`__table1.a`), a constant with its
data type appended (`1_UInt8`), a set by its key - so the result of the pipeline is
renamed back to the names of the metadata by mapping every expression of the query
tree to the name its AST gives. Two more differences have to be reconciled: a
`tuple` at the top level of `GROUP BY`, which the Analyzer unwraps into separate
keys, and the `ORDER BY` expression, which `ASTProjectionSelectQuery::cloneToASTSelect`
appends to the `SELECT` list and which may therefore duplicate a projection column.

A column of the metadata missing from the result is now reported instead of being
silently dropped by the part writer, which would write a projection part without
that column and read it back as the default value of its type.

The synthetic table expression which stands in for the missing `FROM` clause of a
projection query borrows the name of `system.one`. The Analyzer plans a read from a
table expression as a read from a table, so it checks the access rights and applies
the quotas for it, and calculating a projection must not require anything beyond the
rights of the query which writes the data.

Related: #75728

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [16d8cb3]

Summary: ✅


AI Review

Summary

This PR switches ProjectionDescription::calculateByQuery from the legacy interpreter to the Analyzer, then closes the resulting behavioral gaps around column naming, positional arguments, lightweight deletes, and synthetic-source side effects such as row policies, additional_table_filters, and parallel_replicas_custom_key. I reviewed the current code, the full PR diff, prior discussion threads, and the current green Praktika report, and I do not see an unresolved correctness, safety, or performance blocker in the current revision. The remaining open human threads are about implementation shape (__tableN renaming and the use of WithMergeableState), not about a broken contract in the shipped behavior.

Final Verdict
  • Status: ✅ Approve
  • No new inline findings to post in this run.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 6, 2026
@zlareb1

zlareb1 commented Sep 6, 2026

Copy link
Copy Markdown
Member

TL;DR: Because StorageProjectionSource borrows the name system.one and the calculation now goes through the planner as a real table read, row policies and additional_table_filters keyed on system.one are applied to the projection input. A filtering policy silently persists wrong projection aggregates at default settings, and a policy written against the real system.one column makes every INSERT into every table with a projection throw. Measured on the PR-head CI binary (a4c29278); a pre-PR build is immune to all three.

1. A row policy on system.one silently poisons persisted projection parts, at pure defaults.

CREATE TABLE t (a UInt64, b String, PROJECTION p (SELECT b, sum(a), count() GROUP BY b))
ENGINE = MergeTree ORDER BY a SETTINGS materialize_projections_on_insert = 1;
CREATE ROW POLICY rp ON system.one USING a != 0 TO ALL; -- resolves against the projection source's columns
INSERT INTO t SELECT number % 3, toString(number % 2) FROM numbers(10);

SELECT b, sum(a), count() FROM t GROUP BY b ORDER BY b SETTINGS optimize_use_projections = 0;
-- 0	5	5
-- 1	4	5     (ground truth)

SELECT b, sum(a), count() FROM t GROUP BY b ORDER BY b;
-- 0	5	3
-- 1	4	3     (wrong: served from the projection, which was built over the filtered input)

The wrong state is persistent: it survives DROP ROW POLICY and OPTIMIZE TABLE t FINAL (a merge combines the stored projection states, it does not recompute them from the source data), so a transient policy permanently corrupts the projection until it is rebuilt by hand. The same poisoning happens with SETTINGS additional_table_filters = {'system.one' : 'a != 0'} on the INSERT — and that is an ordinary setting, so a profile-level value poisons every insert the profile makes.

2. A policy written against the real column of system.one breaks inserts loudly. CREATE ROW POLICY rp ON system.one USING dummy = 0 TO ALL permits every row of the real table (SELECT count() FROM system.one still returns 1), but the projection source has no dummy column, so every INSERT into every table with a projection fails with UNKNOWN_IDENTIFIER.

3. An always-false filter suppresses materialization silently. With additional_table_filters = {'system.one' : '0'} the insert succeeds but writes no projection part at all; queries silently stop using the projection, and force_optimize_projection = 1 reports PROJECTION_NOT_USED.

The sensitivity of FROM-less SELECT to system.one policies is pre-existing (a USING 0 policy already makes SELECT 1 return no rows on pre-PR builds too), but there the effect is transient and query-scoped; here it flows into persisted parts. Since the borrowed name is only needed for the access-rights check, perhaps the synthetic read could skip row policies and additional_table_filters (SelectQueryOptions has ignore_access_check but no analogous knob for these two), or the planner could exempt a storage that is not registered in the catalog.

@clickhouse-gh clickhouse-gh Bot added the comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). label Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 16d8cb3d7 with master 900576b4c (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

313 object files changed (+165.07 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ProjectionsDescription.cpp.o 586.56 KiB 691.00 KiB +104.43 KiB (+17.80%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

alexey-milovidov and others added 3 commits September 11, 2026 05:59
…tion

The source of a projection calculation borrows the name of `system.one`, which is
what a `SELECT` without a `FROM` clause reads from, so that the access rights and
the quotas of the synthetic read are those of `system.one`. But a row policy and
an `additional_table_filters` entry are keyed by the name of a table as well, so a
policy or a filter for `system.one` was applied to the data being written into a
projection part.

The effect is a persistent corruption at default settings: a filtering policy on
`system.one` makes an `INSERT` build the projection over the filtered input, and the
wrong aggregates survive both `DROP ROW POLICY` and `OPTIMIZE TABLE ... FINAL`,
because a merge combines the stored states instead of recomputing them from the
source data. A policy written against the real column of `system.one` (`dummy`) is
worse in a different way - the source of the calculation has no such column, so
every `INSERT` into every table with a projection fails with `UNKNOWN_IDENTIFIER`.

A synthetic storage which only stands in for a data source inside the server is now
marked with `IStorage::isSyntheticDataSource`, and both the Analyzer and the legacy
interpreter skip the row policies and the `additional_table_filters` of its borrowed
name. The legacy interpreter matters too: it still builds the description of the
`minmax_count` projection, so a policy for `system.one` could make a table fail to
attach.

Reported by zlareb1 in
#118375 (comment)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…gation_in_order`

`enable_positional_arguments_for_projections` was only covered by
`03758_positional_argument_agg_projection`, which stops at `ADD PROJECTION`: it never
inserts data, so it would not notice a projection with a positional `GROUP BY` being
calculated incorrectly. The new test walks the whole path - the columns written into
the projection part on insert and on merge, and the result the optimizer reads back
from it - and compares the answer served from the projection with the answer of the
table itself.

The projection optimization does not match an aggregate projection when the
aggregation is done in order, and it is not supported with parallel replicas, so both
tests which force a projection pin the settings the test randomization may flip.
`05083_projection_calculation_with_analyzer` failed in CI with `PROJECTION_NOT_USED`
for exactly this reason, with `--optimize_aggregation_in_order 1` identified as the
culprit by the randomization diagnosis:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118375&sha=a4c29278f8b4cb12e953f58dfa864be005fd34ad&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
#118375

The previous commit answers
#118375 (comment)
(its own message links the comment by a wrong identifier), and this test answers
#118375 (comment)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Confirmed and fixed in 395ca86, thank you - the reproduction is exact, and I reproduced all three of your cases on a control binary built from the previous head before fixing them.

The root cause is the one you point at: the source of the calculation borrows the name of system.one so that the synthetic read is checked against the rights and the quotas of system.one, but a row policy and an additional_table_filters entry are keyed by the name of a table as well, so both followed the borrowed name into the projection pipeline.

The fix marks a storage which only stands in for a data source inside the server with a new IStorage::isSyntheticDataSource, and skips the row policies and the additional_table_filters of its name for such a storage. This is your second suggestion ("the planner could exempt a storage that is not registered in the catalog") rather than new SelectQueryOptions flags, because the exemption is a property of the storage and not of the query: the name is borrowed, so no policy for that name can ever be about the rows it produces.

The legacy interpreter is guarded the same way, and that turned out to matter beyond INSERT: it still builds the description of the minmax_count projection, so a policy for system.one could make a table fail to attach.

Regression test: 05183_projection_calculation_ignores_query_filters. It covers your case 1 (a filtering row policy on system.one, applied to a dedicated user so the test stays parallel-safe) and the additional_table_filters half of it, comparing the answer served from the projection against the answer of the table itself. Against a control binary both sections differ exactly as you reported (count() of 3 instead of 5), and they pass with the fix.

I did not add coverage for additional_result_filter: I checked it on the control binary with both an aggregate and a filtered normal projection, and it never reaches the projection pipeline (the step is not added for the processing stages the calculation uses), so there is nothing to fix there.

Case 2 (UNKNOWN_IDENTIFIER on every INSERT) and case 3 (an always-false filter writing no projection part) follow from the same exemption and are gone with it.

alexey-milovidov and others added 2 commits September 18, 2026 07:46
…s user

The Fast test of the previous head failed in four unrelated tests with
`Table system.one has row policies, but none of them are for the current
user` (`ACCESS_DENIED`). Test `05183_projection_calculation_ignores_query_filters`
created a row policy on `system.one` for a dedicated user, and with
`throw_on_unmatched_row_policies` enabled in the test config every other
user is denied a `FROM`-less `SELECT` while such a policy exists, so the
policy poisoned the tests running in parallel. A row policy on a shared
system table is a server-wide side effect and cannot be made parallel-safe.

The test itself also failed: the dedicated user lacked the
`TABLE ENGINE ON MergeTree` grant that `table_engines_require_grant`
demands in CI.

The test is split into two:
- `05227_projection_calculation_ignores_additional_table_filters` keeps the
  `additional_table_filters` half, which is query-scoped and parallel-safe;
- `05228_projection_calculation_ignores_row_policy_on_system_one` keeps the
  row policy half, tagged `no-parallel`, with the missing grant, and the
  policy is dropped before the checking queries.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118375&sha=7c56d6c4c182add107c2111f6747f4914bbe7b4e&name_0=PR&name_1=Fast%20test
PR: #118375

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Storages/ProjectionsDescription.cpp Resolved
Comment thread src/Storages/ProjectionsDescription.cpp Resolved
alexey-milovidov and others added 3 commits October 2, 2026 07:42
…ojections

Master moved the row policy lookup into the shared helper `getRowPolicyFilterForStorage`
(`src/Storages/getEffectiveRowPolicyFilter.cpp`), so the `isSyntheticDataSource` check of this
PR for row policies is moved there, which covers both the Analyzer and the legacy interpreter.
The `additional_table_filters` checks stay where they were.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ulateByQuery`

The Analyzer does not resolve positional arguments of a `SECONDARY_QUERY` (and of a context
where they are marked as already resolved), so a projection with `GROUP BY 1` created with
`enable_positional_arguments_for_projections` failed with `LOGICAL_ERROR` when the data came
from a remote `INSERT`. `fillProjectionDescriptionByQuery` already forced `INITIAL_QUERY`;
do the same in `calculateByQuery`. `05318_projection_positional_arguments_remote_insert`
covers it and fails without the fix.

Also document why `removeDuplicateProjectionColumns` ignores aliases: the projection metadata is
built with `ignoreAlias`, so `a AS x, a AS y` is stored as the single column `a`.
`05317_projection_alias_columns_sharing_expression` covers that.

#118375 (comment)
#118375 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Register an `EXIT` trap which drops the row policy, the table and the user, so a failure in the
middle of the test cannot leave a policy which denies every `FROM`-less `SELECT` to later tests.

#118375 (comment)

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

@alexey-milovidov alexey-milovidov left a comment

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.

The implementation is reasonable.

@alexey-milovidov alexey-milovidov self-assigned this Oct 2, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
@KochetovNicolai
KochetovNicolai removed this pull request from the merge queue due to a manual request Oct 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
@alexey-milovidov
alexey-milovidov removed this pull request from the merge queue due to a manual request Oct 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@KochetovNicolai wants to review.

Comment thread src/Storages/ProjectionsDescription.cpp Outdated
* of the files in the projection part (see `sample_block`).
*
* Collects the map from the names the Analyzer gives to the expressions of `query_tree` to the
* names the projection stores them under, so that the result of the pipeline can be renamed back.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't like the way we use prefixes like __table1 first, and then rename them back. We should not do it in the first place.

There is only one table possible, so adding unique prefixes can be skipped.
We can do it by passing a special flag to the analyzer/planner, or by implementing a small, specific projections planner.

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.

🕵 Agreed that naming the columns without the __tableN prefixes in the first place would be cleaner than renaming them back afterwards. Both options (a flag for the Analyzer/Planner that skips the table-expression prefixes and the type suffixes of constants when there is a single table expression, or a dedicated small planner for projections) are larger design changes, and you asked for @novikd's opinion, so I am leaving this thread open for that decision instead of picking one unilaterally. The current rename-back step is guarded: a missing column and a duplicated name both throw a LOGICAL_ERROR.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Both options are larger design changes

I agree, and I would like to have it.

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.

🕵 Thanks. A step in that direction is in 6d55918: a normal projection without WHERE (the most common kind) no longer goes through the planner at all, since it is only executed up to FetchColumns - its columns are taken from the source block directly, so there is no naming and no renaming back for it. This also fixed a real bug found by the AST fuzzer, where the Analyzer folded isNull of a non-Nullable column and did not read that column. The rename-back step now remains only for aggregate projections and projections with WHERE. Choosing between a flag for the Analyzer/Planner and a dedicated small projection planner for those is the design decision still open with @novikd, so this thread stays open for it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai, tracking the sequential-job timeout in #123849. The Fast test failure on 0c38d08 was a wrong expected value in the new test 05356_projection_calculation_ignores_parallel_replicas_custom_key (the sum for b = '1' is 4); fixed in cce65a6, and master is merged in. The three remaining open threads from @KochetovNicolai (__tableN naming, WithMergeableState, name collisions) are a design decision pending @novikd's opinion.

Comment thread src/Storages/ProjectionsDescription.cpp Resolved
The internal query which calculates an aggregate projection or a projection
with `WHERE` runs only up to `WithMergeableState`, and a normal projection
without `WHERE` does not use the planner at all, so the post-filter of
`additional_result_filter` (added by the `Planner` only in the second stage)
is never applied to it. Pin this with a test, as requested in review.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118375&sha=6780f0aba96d67a857dfa5897562c7d82d5b517d&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. 05210_lightweight_update_materialized_cte_in_ignore fails with UNKNOWN_TABLE (Unknown table expression identifier '_materialized_cte_c_...') under parallel replicas; on 2026-10-12 it fails in the same job on master and in many unrelated PRs, so it is not caused by this PR.

Also addressed the latest review about additional_result_filter (it is not applied to the projection calculation; pinned by a new test in f1edc7d). The three remaining threads by @KochetovNicolai are the open design question (a dedicated projection planner or an Analyzer flag instead of renaming the __tableN names back) and are left for @novikd and a human decision.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #123121 (mine, open).

This is the same signature as #112642: query 26 (line 79) of 05210 fails with UNKNOWN_TABLE on the initiator's _materialized_cte_c_* because the query sent to the replicas can start before the initiator has materialized the CTE, which is why all 96 reruns passed. It is the only failure on 6780f0a and is not caused by this PR.

#123121 is waiting for review from @ novikd and @ devcrafter.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai for linking #123121 for the 05210 failure.

The only failure on f1edc7d was test_storage_iceberg_concurrent/test_concurrent_reads.py::test_concurrent_reads (FILE_DOESNT_EXIST: the Iceberg metadata file is missing in MinIO), in Integration tests (arm_binary, 1/4). It is unrelated to this PR. It looks like the problem fixed by #125448, where a reused Spark JVM kept the previous module's cached s3a:// filesystem. That fix is now on master, so I merged master in 16d8cb3. The merge was clean, and the touched translation units compile.

The three open threads by @KochetovNicolai (__tableN naming, WithMergeableState, name collisions) are still the open design question about a dedicated projection planner or an Analyzer flag. They need a decision from @novikd and a human.

@CLAassistant

CLAassistant commented Oct 13, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Why do I like this implementation? - Because it is small and serves the purpose (getting rid of the old analyzer).
It allows us to get both things at once: a small and harmless change first, and pursuing the dreams of @KochetovNicolai and @novikd next.

@alexey-milovidov alexey-milovidov self-assigned this Oct 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 13, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

PS. I also dislike __tableN naming; it is trash.

Merged via the queue into master with commit e4ca8d1 Oct 14, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the use-analyzer-for-projections branch October 14, 2026 00:26
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 14, 2026
…ild-normal-projection-stale

Conflicts with ClickHouse#118375 ("Calculate projections with the Analyzer") in
`ProjectionsDescription::calculateByQuery` and `05176`.

ClickHouse#118375 keeps the `WHERE _row_exists = 1` injection for the stages that run
the query and adds a second `_row_exists` filter in its new `FetchColumns`
fast path. This branch already drops the deleted rows from the source block
once, for every projection type, before either path runs, so the merge keeps
master's Analyzer pipeline and fast path and removes the now redundant
injection and fast-path filter. The single mechanism is the one requested in
the review of this PR.

`05176`: keep this branch's expectations (the estimator now matches the real
rebuilt projection, 2 marks); take master's comment wording.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 15, 2026
05340 is also used by ClickHouse#124912 and by master's
05340_projection_lightweight_delete_rebuild_normal_projection (ClickHouse#118375).
05401 is free on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 17, 2026
Building a projection's metadata analyzes its query in place: with
`enable_positional_arguments_for_projections` on, the positional arguments
are replaced in the stored query, and with it off, `1` stays a constant
`GROUP BY` key. `calculateByQuery` then resolved positional arguments again
by the setting of the INSERT, merge or mutation that calculates the
projection, so an integer literal could be re-read as a position:
`GROUP BY 'a', 1` built off and calculated on reads `1` as `'a'`, and
`SELECT 2, 1 GROUP BY 1` built on (stored key `1`) reads it as `2`.

Released versions reject such an INSERT with NOT_FOUND_COLUMN_IN_BLOCK;
master, since the metadata check of ClickHouse#118375, throws a LOGICAL_ERROR
(found by BuzzHouse, STID 4238-495c).

Analyze the stored query with positional arguments disabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to punithns97/ClickHouse that referenced this pull request Nov 8, 2026
… name

A subquery is named by the hash of its AST (`__subquery_<hash>`). The
projection metadata is named from the stored projection query, analysed in
place, while `calculateByQuery` (since ClickHouse#118375) renames the columns of the
Analyzer pipeline to names built by converting the query tree back to AST.
That conversion does not reproduce the subquery (a subquery without `FROM`
gets `FROM system.one`, other shapes hash differently too), so a projection
column like `b IN (SELECT ...)` was calculated as `in(b, __subquery_X)` while
the metadata describes `in(b, __subquery_Y)`, and every INSERT,
MATERIALIZE PROJECTION or merge rebuilding a projection with `WHERE` or an
aggregate projection failed with LOGICAL_ERROR (found by the AST fuzzer on
the `05515_global_subquery_projection_where` seed). On 26.9 the same INSERT
silently stored 0 in such a column.

The unresolved names of the functions are now taken from the AST each query
tree node was built from, which is the very AST the metadata was named from;
`toAST` stays the fallback for a node without one (the `tuple` wrapper added
around a tuple `GROUP BY` key).

The names are keyed by node, so a resolution that replaces the `IN` node loses
them: `rewrite_in_to_join` does, so `calculateByQuery` pins it to 0 next to the
other settings it pins. Creating the table under `rewrite_in_to_join = 1`
gives the same metadata names (they come from `InterpreterSelectQuery`, which
does not read it), so `fillProjectionDescriptionByQuery` needs no pin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants