Repository navigation
Conversation
Closes ClickHouse#106099 A row policy whose USING expression is a bare physical column reference (e.g. CREATE ROW POLICY pol ON t USING c0 TO ALL) made every query that reads that column on master fail with: Code: 49. DB::Exception: Duplicate column name c0 in row policy actions output. (LOGICAL_ERROR) The filter actions DAG built by buildFilterInfo (Planner/Utils.cpp) and generateFilterActions (Interpreters/InterpreterSelectQuery.cpp) appends every required table column as an output so that filtered columns can still be read after the filter step. When the filter expression is a bare column, that node is already the filter output, so the same ActionsDAG::Node appears in the outputs list twice. FilterTransform already handles this: Block::erase(filter_column_name) removes one of the entries, leaving the other as the passthrough. PR ClickHouse#100586 ("Position based unused column removal") added a name-based duplicate check at the top of ReadFromMergeTree::removeUnusedColumns that rejected this legitimate pattern. Relax the check to use the node pointer in addition to the result name: same-pointer duplicates (the filter+passthrough trick) are allowed, while two distinct nodes with the same result name (a real bug for the position-based optimization) still throw. The position-based logic later in removeUnusedColumns operates on output_header (table columns, always uniquely named), not on the filter DAG outputs, so a same-pointer duplicate does not affect it. A second 26.x regression in projectionsCommon.cpp::findInOutputs makes projection optimization throw ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER on any filter column whose type is not UInt8/Nullable(UInt8), even though FilterTransform itself accepts every type that satisfies canBeUsedInBooleanContext. That made SELECT count() FROM t (and every other aggregation) fail on a table with a USING <int_column> row policy once the validator stopped masking it. Return nullptr instead of throwing, so the optimizer gracefully gives up and the normal read path runs. Regression test 04301_106099_row_policy_bare_column_duplicate.sql covers the reproducer from the issue, the SELECT *, SELECT count(), SELECT <other column>, enable_analyzer = 0 and = 1 variants, and the existing wrapped-USING workarounds (c0 + 0, c0 != 0, materialize(c0)).
|
Pre-PR validation gate (session (a) Deterministic repro? Yes. (b) Root cause explained? Yes, see the PR description. Two distinct 26.x regressions stack: PR #100586 ( (c) Fix matches root cause? Yes. (1) The validator is relaxed to use node pointer + result name, so legitimate same-pointer duplicates are tolerated while different-node same-name duplicates (the real failure mode for position-based optimization) still abort. (2) The projection helper returns (d) Test intent preserved? Yes. Existing row policy tests still pass: (e) Bidirectional demonstration? Yes. Stashed the two |
|
cc @antaljanosbenjamin @novikd could you take a look? The first regression is in |
|
Workflow [PR], commit [210a352] Summary: ❌
AI ReviewSummaryThis PR fixes bare-column row policy and Missing context / blind spots
Findings
Tests
Final VerdictStatus: Minimum required action: fix the lazy-FINAL row-level filter clone so it honors the bare-column |
|
@groeneai Why not just ensure the same column is not added twice? |
|
@antaljanosbenjamin Tested it. Producer-side dedup works for The legacy Three options:
I lean toward (3) since it matches your question, but it touches |
|
@groeneai Do the third. |
Per @antaljanosbenjamin's suggestion on PR ClickHouse#106104, prevent the same column from being added twice at the source instead of relaxing the downstream validator. The previous commit relaxed `ReadFromMergeTree::removeUnusedColumns` to tolerate same-pointer duplicates in the filter DAG outputs. That worked but kept the duplicate around in every downstream consumer. This change eliminates the duplicate at the producers: * `Planner/Utils.cpp::buildFilterInfo` (analyzer path) -- when the filter expression is one of the inputs (bare-column case), skip the redundant passthrough push and set `remove_filter_column = false` so `FilterTransform` does not erase the column we want to keep. * `Interpreters/InterpreterSelectQuery.cpp::generateFilterActions` (legacy path) -- same logic: detect the bare-input filter result, skip its passthrough push, and set `do_remove_column = false`. * `Interpreters/ExpressionAnalyzer.cpp` -- drop the unconditional `row_policy_info->do_remove_column = true;` override that masked the producer-side decision. The producer now sets the correct value for both bare-column and computed-column policies. * `Processors/QueryPlan/ReadFromMergeTree.cpp` -- restore the strict name-based duplicate validator. Producer-side dedup makes same-pointer duplicates impossible in well-formed DAGs, so the original check from PR ClickHouse#100586 is safe again. Regression test improvements (per bot review): the data set now includes a row with `c0 = 0` and explicit `count()` / `countIf` queries. The test now catches both (a) the `LOGICAL_ERROR` reappearing AND (b) the policy silently not being applied -- the second mode would let the falsy row through, which a `count() == 3` assertion catches. The Cause 2 fix in `projectionsCommon.cpp::findInOutputs` (turn `ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER` into a graceful `nullptr` for non-`UInt8` filters) is unchanged and independent of the dedup approach. PR review: ClickHouse#106104 Issue: ClickHouse#106099
|
@antaljanosbenjamin Done in d338e52. Producer-side dedup:
Bot review on the test: addressed in the same commit. Data now includes Verified locally on a debug build:
The Cause 2 fix in Pre-PR validation gate (Option 3):
|
…Common The Option 3 fix in d338e52 made `findInOutputs` unconditionally return `nullptr` for non-`UInt8` filter columns instead of throwing, so projection optimization could give up gracefully when a row policy uses a column type like `Int8` (issue ClickHouse#106099). However, that also silently broke `02680_illegal_type_of_filter_projection`, which intentionally feeds a `Float64` `PREWHERE` to verify the system rejects it. Test was reported FAIL by Fast test; `ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER` also became an unused error code (Style check failure). Add a `lenient_type_check` parameter (default `false`) and pass `true` only from the `row_level_filter` call site. `PREWHERE` and `FilterStep` callers keep the original throw, so user-issued filters of the wrong type still surface `ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER` instead of silently falling back. Verified locally on debug build: - `02680_illegal_type_of_filter_projection`: throws `Code: 59` as expected. - `04301_106099_row_policy_bare_column_duplicate`: still matches reference under both `enable_analyzer = 0` and `enable_analyzer = 1`. - Row policy `USING` with `Int8`/`Float32`/`UInt16` columns all filter rows correctly via the lenient path. - Existing row policy tests pass: `01308_row_policy_and_trivial_count_query`, `01295_create_row_policy`, `01296_create_row_policy_in_current_database`. PR review: ClickHouse#106104
|
Pushed Fast test on Surgical fix: Pre-PR validation gatea) Deterministic repro? Yes.
Bugfix validation check was inconclusive on both |
The previous commit (75557e5) introduced two latent issues that the bot's inline review on PR ClickHouse#106104 flagged: 1. `generateFilterActions` did not actually dedup outputs for a row policy or `additional_table_filters` bare-column case. The producer-side loop iterated over `inputs`, which is already deduped by the analyzer, but it never reset the existing outputs list. When the prerequisite columns happened to include the filter column itself, the analyzer emitted the same output node twice and the strict validator restored in d338e5 fired `LOGICAL_ERROR "Duplicate column name c0 in row policy actions output"`. Reset `filter_outputs` to a single `filter_result_node` before re-exporting the remaining inputs. 2. The unconditional `additional_filter_info->do_remove_column = true` override at `InterpreterSelectQuery.cpp:1001` is exactly the case the bot warned about: when producer-side dedup leaves a single bare-input output, forcing remove makes `FilterTransform` erase the only copy and any downstream consumer reading the same column fails with `NOT_FOUND_COLUMN_IN_BLOCK`. Drop the override (bot's option b) so `generateFilterActions` decides the right value: `false` for a bare-input filter, `true` for a computed filter. The same override on `parallel_replicas_custom_filter` was always a no-op because that filter is generated as a computed expression -- drop it too for consistency. 3. `SELECT count() FROM t SETTINGS additional_table_filters = {'t':'<bare-int-column>'}` regressed under 75557e5 because the strict `findInOutputs` call in `projectionsCommon.cpp::buildImpl` for `FilterStep` throws `ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER` on non-`UInt8` filter columns. `FilterTransform` itself accepts any `canBeUsedInBooleanContext` type, so the strict check just makes projection optimization fail rather than degrade gracefully. Pass `lenient_type_check = true` for the `FilterStep` path so the optimizer bails to the normal read path. The PREWHERE call site above stays strict, so `02680_illegal_type_of_filter_projection` keeps surfacing the type error for explicit user `PREWHERE <non-bool>`. Regression test additions: - `04301_106099_row_policy_bare_column_duplicate.sql` now covers the bot's exact reproducer (`SELECT c0 ... SETTINGS additional_table_filters = {'t':'c0'}`) under both `enable_analyzer = 0` and `enable_analyzer = 1`, plus the matching `count()` case that previously hit `ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER`. Local validation (debug build, 20-run reliability check): - 04301 reproducer (rp bare-column + atf bare-column): 20/20 pass - 01295, 01308, 01710 (projection_row_policy + projection_additional_filters), 01851, 02131, 03033, 03591, 03641: pass unchanged - 02680 (PREWHERE Float64): still throws Code 59 as expected PR review: ClickHouse#106104 Issue: ClickHouse#106099
|
Addressed in
Regression test additions in
Pre-PR validation gate
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 49/52 (94.23%) | Lost baseline coverage: none · Uncovered code |
antaljanosbenjamin
left a comment
There was a problem hiding this comment.
In general reduce the number and lengthiness of comments. Make them concise and refrain from explaining other parts of the code: the other parts might change overtime which would make the comment misleading.
| -- Same producer-side dedup also runs for `additional_table_filters`. Without | ||
| -- the fix at `InterpreterSelectQuery.cpp` the override would force | ||
| -- `FilterTransform` to erase the only `c0` output, breaking `SELECT c0`. | ||
| SELECT c0 FROM t_106099 ORDER BY c0 SETTINGS additional_table_filters = {'t_106099':'c0'}, enable_analyzer = 0; |
There was a problem hiding this comment.
We need a test with row policy + additional_table_filters and probably prewhere and normal filters.
Two changes folded into one commit: 1. `projectionsCommon::findInOutputs`: in the keep-passthrough branch (`remove == false`), bail on projection when called from a lenient-mode caller. Without this, a `UInt8` bare-column row policy / additional table filter that is preserved as a passthrough was rewritten to constant `1` by the projection helper, so `SELECT c0` returned a column of `1`s instead of the original values (bot review on `a498f399b613`, 2026-05-29T23:45Z). 2. Reduce the number and length of inline comments per @antaljanosbenjamin's review (2026-06-02T09:04Z). Each comment now says what the local code does and why, without re-explaining `FilterTransform`, `ReadFromMergeTree::removeUnusedColumns`, `generateFilterActions`, `canBeUsedInBooleanContext`, or the constant-rewrite logic that lives elsewhere and may change. Test `04301_106099_row_policy_bare_column_duplicate` adds a `UInt8` projection block under both analyzer paths and both `USING` and `additional_table_filters` shapes: * Without forcing projection: result is the real values (`2`, `3`), not constant `1`. * With `force_optimize_projection = 1`: query throws `PROJECTION_NOT_USED`, proving the projection helper genuinely bailed rather than silently picking a different plan. Verified locally against the existing debug binary: 04301, 01308, 01710 projection row-policy, and 02680 illegal-type filter projection all pass.
|
@antaljanosbenjamin Addressed in 6132347. Each comment now states what the local code does and why, without explaining other code paths ( Same commit also addresses the bot's earlier UInt8 projection concern: when |
antaljanosbenjamin
left a comment
There was a problem hiding this comment.
It is getting too complicated. Let's revert all the changes and make ReadFromMergeTree not to remove unused columns in case of duplicated column names.
|
@groeneai can you resolve conflicts? |
|
@groeneai I resolved the conflicts for you |
| /// See issue #106099. | ||
| if (filter_input_node == filter_actions_outputs[0]) | ||
| { | ||
| remove_filter_column = false; |
There was a problem hiding this comment.
This makes do_remove_column = false part of the row-policy contract for bare input filters, but optimizeLazyFinal still rebuilds row-level filters for the set-building read and forces fixed->do_remove_column = true at src/Processors/QueryPlan/Optimizations/optimizeLazyFinal.cpp:469. For a ReplacingMergeTree FINAL query with query_plan_optimize_lazy_final = 1 and CREATE ROW POLICY ... USING id, cloneFilterSubDAG leaves a single id output; the set-building ReadFromMergeTree then applies the row policy and erases that only id before the primary-key projection, so the lazy-FINAL plan can hit NOT_FOUND_COLUMN_IN_BLOCK even though the normal read path now handles the same bare policy. Please preserve the original do_remove_column when cloning row-level filters here, or add an explicit pass-through output before forcing removal, and cover this with a lazy-FINAL regression using a bare-column row policy.
|
Probably #106438 is better |
|
@antaljanosbenjamin Agreed, closing this in favor of #106438. Your position-based pruning refactor is much cleaner than the Option 3 fixups, and your 04305 plus 02680 tests cover the same cases. Will monitor #106438. |
|
Superseded by #106438 (cleaner approach by @antaljanosbenjamin). |
Closes #106099.
A row policy whose
USINGexpression is a bare physical column reference (e.g.CREATE ROW POLICY pol ON t USING c0 TO ALL) made every query that readsc0fail on master withCode: 49. DB::Exception: Duplicate column name c0 in row policy actions output. (LOGICAL_ERROR). The bug is a 26.x regression and is independent ofenable_analyzer.Cause #1 — over-strict duplicate-output check.
buildFilterInfo(Planner/Utils.cpp) andgenerateFilterActions(Interpreters/InterpreterSelectQuery.cpp) append every required table input as an output of the filter actions DAG so that filtered columns remain available downstream. For a bare-columnUSINGthe filter result IS the input node, so the sameActionsDAG::Nodeends up in the outputs list twice.FilterTransformalready copes with this:Block::erase(filter_column_name)removes a single entry, leaving the other as the passthrough.PR #100586 (
Position based unused column removal) added aNameSetduplicate check at the top ofReadFromMergeTree::removeUnusedColumnsthat throws on this legitimate pattern. The fix relaxes it to use the node pointer in addition to the result name: same-pointer duplicates (the filter+passthrough trick) are allowed, while two distinct nodes with the same result name (a real bug for the position-based optimization) still abort. The position-based logic later inremoveUnusedColumnsoperates onoutput_header(table columns, always uniquely named), not on the filter DAG outputs, so a same-pointer duplicate does not affect it.Cause #2 — projection optimization throws on non-
UInt8filter columns. Once the validator stops masking the first bug,SELECT count() FROM t(and any other aggregation) still fails withCode: 59. ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER.projectionsCommon.cpp::findInOutputsrejects any filter whose type is notUInt8/Nullable(UInt8), even thoughFilterTransformitself accepts every type that satisfiescanBeUsedInBooleanContext.Int32,Int64, etc. are valid runtime filters. The fix returnsnullptrinstead of throwing, so the projection optimizer gracefully gives up and the normal read path runs.Regression test
04301_106099_row_policy_bare_column_duplicate.sqlcovers: the reproducer from the issue,SELECT *,SELECT count(),SELECT c0, sum(c1) GROUP BY c0,SELECT <other column>,enable_analyzer = 0and= 1, and the wrapped-USINGworkarounds (c0 + 0,c0 != 0,materialize(c0)).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
LOGICAL_ERROR"Duplicate column name in row policy actions output" when a row policyUSINGexpression is a bare column reference (e.g.USING c0) and the same column is read by the query. Also fixILLEGAL_TYPE_OF_COLUMN_FOR_FILTERthrown by projection optimization for any row policy whose filter type is notUInt8/Nullable(UInt8).Documentation entry for user-facing changes