Repository navigation
Calculate projections with the Analyzer - #118375
Conversation
`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]>
|
Workflow [PR], commit [16d8cb3] Summary: ✅
AI ReviewSummaryThis PR switches Final Verdict
|
|
TL;DR: Because 1. A row policy on 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 2. A policy written against the real column of 3. An always-false filter suppresses materialization silently. With The sensitivity of |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes313 object files changed (+165.07 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units706 translation units recompiled, 5567 s compile time in total, 706 of them have a recent master baseline. |
…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]>
|
🕵 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 The fix marks a storage which only stands in for a data source inside the server with a new The legacy interpreter is guarded the same way, and that turned out to matter beyond Regression test: I did not add coverage for Case 2 ( |
…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]>
…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
left a comment
There was a problem hiding this comment.
The implementation is reasonable.
|
LGTM |
|
@KochetovNicolai wants to review. |
| * 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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.
There was a problem hiding this comment.
Both options are larger design changes
I agree, and I would like to have it.
There was a problem hiding this comment.
🕵 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.
|
🕵 Thanks @groeneai, tracking the sequential-job timeout in #123849. The Fast test failure on 0c38d08 was a wrong expected value in the new test |
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]>
|
🕵 @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. Also addressed the latest review about |
|
The fix is already in progress: #123121 (mine, open). This is the same signature as #112642: query 26 (line 79) of #123121 is waiting for review from @ novikd and @ devcrafter. |
|
🕵 Thanks @groeneai for linking #123121 for the The only failure on f1edc7d was The three open threads by @KochetovNicolai ( |
|
Why do I like this implementation? - Because it is small and serves the purpose (getting rid of the old analyzer). |
|
PS. I also dislike |
…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]>
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]>
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]>
… 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]>
Related: #75728
Reimplementation of #75728, which was closed as a duplicate of #96886. It is not a duplicate: #96886 replaces
ExpressionAnalyzerfor standalone expression compilation (key, skip-index and constraint expressions), while this is about theSELECTof a projection, which is still interpreted by the legacyInterpreterSelectQuery.ProjectionDescription::calculateByQuery— the code which computes a projection block onINSERT, on merge and during a mutation — now usesInterpreterSelectQueryAnalyzer.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: atupleat the top level ofGROUP BY, which the Analyzer unwraps into separate keys, and theORDER BYexpression, whichASTProjectionSelectQuery::cloneToASTSelectappends to theSELECTlist 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
INSERTtime rather than corrupting a projection.The synthetic table expression which stands in for the missing
FROMclause of a projection query borrows the name ofsystem.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_analyzercovers that a user with onlyINSERT,SELECTandOPTIMIZEon the table can still write and read its projections.Because the synthetic table expression borrows the name of
system.one, a row policy or anadditional_table_filtersentry 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 survivedDROP ROW POLICYandOPTIMIZE TABLE ... FINAL, reported by @zlareb1 in #118375 (comment). A storage which only stands in for a data source inside the server is now marked withIStorage::isSyntheticDataSource, and both the Analyzer and the legacy interpreter skip the row policies and theadditional_table_filtersof its name. The legacy interpreter matters too: it still builds the description of theminmax_countprojection, so a policy forsystem.onecould make a table fail to attach.05227_projection_calculation_ignores_additional_table_filtersand05228_projection_calculation_ignores_row_policy_on_system_onecover both halves. After a merge withmaster, the row policy lookup lives in the sharedgetRowPolicyFilterForStorage, so the check is made there.05182_projection_positional_arguments_with_analyzercovers a projection whoseGROUP BYuses 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).calculateByQueryanalyzes the projection query as an initial one, because the Analyzer does not resolve positional arguments of aSECONDARY_QUERY.05318_projection_positional_arguments_remote_insertcovers a remoteINSERT.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.
getAggregatingProjectionInfoinoptimizeUseAggregateProjectionstill usesInterpreterSelectQuery. 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
projectionpass, and05083_projection_calculation_with_analyzerproduces byte-identical output onmasterand on this branch, including every column name of every projection part.Changelog category (leave one):
Workflow [PR]
Sync PR [sync-upstream/pr/118375]
Version info
26.10.1.2341-master(included in26.10and later)