Skip to content

Fix LOGICAL_ERROR for bare-column row policy filters - #106104

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fork/groeneai/fix-106099-row-policy-bare-column-duplicate
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fork/groeneai/fix-106099-row-policy-bare-column-duplicate

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Closes #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 c0 fail on master with Code: 49. DB::Exception: Duplicate column name c0 in row policy actions output. (LOGICAL_ERROR). The bug is a 26.x regression and is independent of enable_analyzer.

Cause #1 — over-strict duplicate-output check. buildFilterInfo (Planner/Utils.cpp) and generateFilterActions (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-column USING the filter result IS the input node, so the same ActionsDAG::Node ends up in the outputs list twice. FilterTransform already 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 a NameSet duplicate check at the top of ReadFromMergeTree::removeUnusedColumns that 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 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.

Cause #2 — projection optimization throws on non-UInt8 filter columns. Once the validator stops masking the first bug, SELECT count() FROM t (and any other aggregation) still fails with Code: 59. ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER. projectionsCommon.cpp::findInOutputs rejects any filter whose type is not UInt8 / Nullable(UInt8), even though FilterTransform itself accepts every type that satisfies canBeUsedInBooleanContext. Int32, Int64, etc. are valid runtime filters. The fix returns nullptr instead of throwing, so the projection 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, SELECT *, SELECT count(), SELECT c0, sum(c1) GROUP BY c0, SELECT <other column>, enable_analyzer = 0 and = 1, and the wrapped-USING workarounds (c0 + 0, c0 != 0, materialize(c0)).

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 policy USING expression is a bare column reference (e.g. USING c0) and the same column is read by the query. Also fix ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER thrown by projection optimization for any row policy whose filter type is not UInt8 / Nullable(UInt8).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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)).
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260529-113000):

(a) Deterministic repro? Yes. CREATE TABLE t (c0 Int32) ENGINE = MergeTree ORDER BY tuple(); CREATE ROW POLICY pol ON t USING c0 TO ALL; SELECT c0 FROM t throws Code: 49. LOGICAL_ERROR on master 100% of the time on debug builds (aborts the server). With the patches in this PR, all reproducer queries from issue #106099 return the expected rows.

(b) Root cause explained? Yes, see the PR description. Two distinct 26.x regressions stack: PR #100586 (Position based unused column removal, 2026-05-27) added a name-based duplicate-output check that rejects the historical filter+passthrough pattern, and the projection helper at projectionsCommon.cpp:129 (introduced 2026-03-30) throws ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER for any non-UInt8 filter column even though FilterTransform accepts every canBeUsedInBooleanContext type.

(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 nullptr instead of throwing, so the optimizer gracefully gives up and the normal read path handles the query.

(d) Test intent preserved? Yes. Existing row policy tests still pass: 01308_row_policy_and_trivial_count_query, 01295_create_row_policy, 01296_create_row_policy_in_current_database, 01710_projection_row_policy. The new test 04301_106099_row_policy_bare_column_duplicate covers the reproducer, SELECT *, SELECT count(), GROUP BY, SELECT <other column>, enable_analyzer = 0 and = 1, and the wrapped-USING workarounds.

(e) Bidirectional demonstration? Yes. Stashed the two src/Processors/QueryPlan/... patches, rebuilt from origin/master state, ran the regression test against the unfixed binary — the server crashed with Logical error: 'Duplicate column name c0 in row policy actions output' (exit code 134 / SIGABRT). Restored the patches, rebuilt, re-ran — test passes 20/20 with randomization.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @novikd could you take a look? The first regression is in ReadFromMergeTree::removeUnusedColumns (PR #100586) and the second is in projectionsCommon.cpp::findInOutputs — both in comp-query-optimizer.

@clickhouse-gh

clickhouse-gh Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [210a352]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
01710_normal_projection_fix1 FAIL cidb
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED
Build (arm_msan) DROPPED

AI Review

Summary

This PR fixes bare-column row policy and additional_table_filters handling by deduplicating filter DAG outputs and making projection analysis bail out when it cannot safely normalize a kept filter column. The final projection fix addresses the previous UInt8 constant-rewrite concern, but the new do_remove_column = false contract is still not preserved by the lazy-FINAL set-building path.

Missing context / blind spots
  • ⚠️ I could not run a focused SQL regression locally because this workspace does not contain a built clickhouse binary; the lazy-FINAL finding is based on tracing current code paths.
Findings

⚠️ Majors

  • [src/Planner/Utils.cpp:616] The bare row-policy fix makes do_remove_column = false the way a single bare input column survives filtering, but optimizeLazyFinal rebuilds row-level filters for its set-building read and forces fixed->do_remove_column = true in src/Processors/QueryPlan/Optimizations/optimizeLazyFinal.cpp:469. For ReplacingMergeTree FINAL with query_plan_optimize_lazy_final = 1 and a row policy like USING id, cloneFilterSubDAG leaves only the id filter output; the set-building ReadFromMergeTree then erases that only id before the primary-key projection, so the lazy-FINAL plan can hit NOT_FOUND_COLUMN_IN_BLOCK while the normal read path works. Preserve the original do_remove_column when cloning the row-level filter, or add an explicit pass-through output before forcing removal.
Tests
  • ⚠️ Add a focused lazy-FINAL regression with ReplacingMergeTree FINAL, query_plan_optimize_lazy_final = 1, and a bare-column row policy on a primary-key column to prove the set-building branch keeps the column needed by the primary-key projection.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: fix the lazy-FINAL row-level filter clone so it honors the bare-column do_remove_column contract, and add the regression above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 29, 2026
@antaljanosbenjamin

Copy link
Copy Markdown
Member

@groeneai Why not just ensure the same column is not added twice?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@antaljanosbenjamin Tested it. Producer-side dedup works for buildFilterInfo (Planner/Utils.cpp:564-566): skip the redundant push when filter_input_node == filter_actions_outputs[0] and flip remove_filter_column = false. With strict validator restored, all enable_analyzer = 1 queries from the reproducer pass.

The legacy generateFilterActions path is harder. ExpressionAnalyzer.cpp:2096 unconditionally sets do_remove_column = true, so stripping the duplicate there breaks enable_analyzer = 0: FilterTransform erases the only c0 and the query fails with NOT_FOUND_COLUMN_IN_BLOCK. The override would need to become conditional on "filter is a computed column, not a bare input".

Three options:

  1. Current PR (validator relax only): smallest change; both paths keep the duplicate.
  2. Producer dedup in buildFilterInfo plus validator relax for the legacy duplicate.
  3. Producer dedup in both paths plus conditional override in ExpressionAnalyzer.cpp:2096.

I lean toward (3) since it matches your question, but it touches do_remove_column propagation. Which do you prefer and I'll push the follow-up commit?

@antaljanosbenjamin antaljanosbenjamin added the can be tested Allows running workflows for external contributors label May 29, 2026
@antaljanosbenjamin

Copy link
Copy Markdown
Member

@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
@groeneai

Copy link
Copy Markdown
Collaborator Author

@antaljanosbenjamin Done in d338e52.

Producer-side dedup:

  • Planner/Utils.cpp::buildFilterInfo (analyzer): when filter_input_node == filter_actions_outputs[0], skip the redundant passthrough push and set remove_filter_column = false.
  • Interpreters/InterpreterSelectQuery.cpp::generateFilterActions (legacy): same logic, plus do_remove_column = false so FilterTransform keeps the column.
  • Interpreters/ExpressionAnalyzer.cpp: dropped the unconditional row_policy_info->do_remove_column = true; override so the producer's decision survives.
  • Processors/QueryPlan/ReadFromMergeTree.cpp: restored the strict name-based duplicate validator from PR Position based unused column removal #100586.

Bot review on the test: addressed in the same commit. Data now includes (0, 0) and explicit count() / countIf(c0 = 0) queries, so the test fails not only on LOGICAL_ERROR reappearance but also if the bare-column policy silently stops being applied (a count() == 3 mismatch catches it).

Verified locally on a debug build:

The Cause 2 fix in projectionsCommon.cpp::findInOutputs (graceful nullptr for non-UInt8 filters) is unchanged.

Pre-PR validation gate (Option 3):

  • Deterministic repro: yes -- single SQL file, no randomization sensitivity.
  • Root cause: bare-column filter expressions produce a same-pointer duplicate in FilterDAGInfo::actions.getOutputs() because the producers (buildFilterInfo / generateFilterActions) unconditionally append every input as a passthrough output without checking whether it is already the filter result; PR Position based unused column removal #100586's name-based validator then rejects it.
  • Fix matches root cause: producers now skip the redundant push and set do_remove_column consistently with whether the filter column was a bare input.
  • Test intent preserved/strengthened: the c0 = 0 row addition keeps the original LOGICAL_ERROR coverage and adds policy-applied coverage.
  • Both directions demonstrated: locally confirmed via direct queries and via the test file diff against the new reference.
  • General fix (not symptom): both planner paths fixed at the source; symmetric subsystems (additional_filter_info, parallel_replicas_custom_filter_info) are unaffected because their explicit do_remove_column = true sets are kept for the non-bare cases they target (those are passed-in ASTPtr row-level filters, never the bare-input case).

…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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 75557e5 to address the CI failures on the prior Option 3 fixup.

Fast test on 02680_illegal_type_of_filter_projection + Style check ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER is defined but not used: same root cause. The Option 3 commit turned the type check in findInOutputs from throw into a blanket return nullptr. Row policy USING <int_column> now works, but a user-issued PREWHERE with a non-UInt8 filter type also stopped erroring -- which is exactly what 02680 was added to verify.

Surgical fix: findInOutputs gets a lenient_type_check parameter (default false). Only the row_level_filter call site passes true. PREWHERE and FilterStep callers keep the original throw, so user-issued filters of the wrong type still surface ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER.

Pre-PR validation gate

a) Deterministic repro? Yes. 02680 query reproduces the throw on demand on the new build.
b) Root cause explained? The blanket return nullptr covered three call sites; row policies need leniency but PREWHERE/FilterStep do not.
c) Fix matches root cause? Differentiates the three call sites via lenient_type_check, only relaxing the one for row policies.
d) Test intent preserved? Both 02680 (throw expectation) and 04301 (row policy passthrough) keep their original semantics. 04301 was not weakened.
e) Both directions demonstrated?

  • 02680: throws Code: 59 ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER (matches reference's serverError annotation).
  • 04301: matches reference under both enable_analyzer = 0 and 1.
  • Sweep: 01308_row_policy_and_trivial_count_query, 01295_create_row_policy, 01296_create_row_policy_in_current_database all pass on the new build.
  • Row policy USING with Int8 / Float32 / UInt16 columns all filter rows correctly.
    f) Fix is general? Yes. Only the row policy code path takes the lenient branch; sibling code paths (additional_filter_info, parallel_replicas_custom_filter_info) do not use bare-input filters and are unaffected.

Bugfix validation check was inconclusive on both d338e52 and the prior ff66be3 (server core dump while running the regression test against master HEAD -- the LOGICAL_ERROR on the bare-column path crashes the debug binary instead of throwing cleanly). That state predates this commit and is the same on both prior commits; it does not block the actual functional CI.

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
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed in a498f399b613 — three fixes layered on top of Option 3:

  1. generateFilterActions dedup actually deduplicates now. The previous loop iterated over inputs (which is already deduped by the analyzer) but never reset the outputs list, so 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" on every SELECT c0 against a USING c0 policy. Resetting filter_outputs = {filter_result_node} before re-exporting the remaining inputs fixes this.

  2. Dropped the unconditional additional_filter_info->do_remove_column = true override at InterpreterSelectQuery.cpp:1001 (your option (b)). generateFilterActions now sets the correct value: false for a bare-input filter, true for a computed filter. The matching override on parallel_replicas_custom_filter_info was always a no-op (that filter is generated as a computed modulo(...) = 0 expression) — dropped for consistency.

  3. Made the FilterStep call site in projectionsCommon::buildImpl lenient about non-UInt8 filter columns. SELECT count() FROM t SETTINGS additional_table_filters = {'t':'<bare-int-column>'} regressed under the previous fixup because the strict findInOutputs call for FilterStep threw ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER even though FilterTransform itself accepts any canBeUsedInBooleanContext type. 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 in 04301:

  • SELECT c0 FROM t SETTINGS additional_table_filters = {'t':'c0'} under both enable_analyzer = 0 and 1 (your reproducer)
  • Matching count() cases that previously hit ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER

Pre-PR validation gate

  • (a) Deterministic repro? Yes. Without a498f399b613 the row policy + SELECT c0 reproducer aborts on ReadFromMergeTree::removeUnusedColumns' duplicate-name validator (LOGICAL_ERROR, Signal 6 in debug). SELECT count() with bare additional_table_filters deterministically returns Code 59 ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER. Both repros are in 04301.
  • (b) Root cause explained? Yes, three causal chains: (1) the previous dedup loop iterated over inputs but never reset outputs, missing the analyzer's prereq-induced duplication; (2) the unconditional override at line 1001 overruled the producer's correct decision for bare-input filters; (3) the strict findInOutputs at projectionsCommon.cpp:212 rejected non-UInt8 filter columns even though FilterTransform accepts them, breaking projection optimization for bare-integer additional filters.
  • (c) Fix matches root cause? Yes. Reset outputs at the producer; drop the overriding writes; pass lenient_type_check = true at the single call site that matters. No widened assertions or no-random-* tags.
  • (d) Test intent preserved AND strengthened? Yes. 02680 still throws as before (PREWHERE call site stays strict). 04301 now covers additional_table_filters bare-column + count() shapes that previously failed silently in CI.
  • (e) Both directions demonstrated locally? Yes. Built build/programs/clickhouse debug binary; 04301 is 20/20 passes against the new reference. 02680 still returns Code 59. DB::Exception: Illegal type Float64 of column ... for filter. Existing tests 01295, 01308, 01710_projection_row_policy, 01710_projection_additional_filters, 01851, 02131, 03033, 03591, 03641 all pass unchanged.
  • (f) Fix is general, not a narrow patch? Yes. The dedup fix at generateFilterActions covers the legacy analyzer for both row_policy and additional_table_filters callers. The analyzer-path equivalent in Planner/Utils.cpp::buildFilterInfo already had the right behavior (resets outputs to expression_nodes before adding passthroughs). The lenient findInOutputs change at projectionsCommon.cpp:212 covers every projection-optimization call into a FilterStep, not just bare-Int32; PREWHERE and the row-level-filter call sites are untouched.

Comment thread src/Planner/Utils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented May 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.90% 77.00% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 49/52 (94.23%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@antaljanosbenjamin antaljanosbenjamin left a comment

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.

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;

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.

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.
@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

@antaljanosbenjamin Addressed in 6132347. Each comment now states what the local code does and why, without explaining other code paths (FilterTransform, ReadFromMergeTree::removeUnusedColumns, generateFilterActions, canBeUsedInBooleanContext, the constant-rewrite logic).

Same commit also addresses the bot's earlier UInt8 projection concern: when findInOutputs would have rewritten a passthrough filter column to constant 1, lenient-mode callers now bail on projection so SELECT c0 returns the real values. Test 04301_106099_row_policy_bare_column_duplicate adds a UInt8 projection block under both analyzer paths.

@antaljanosbenjamin antaljanosbenjamin self-assigned this Jun 2, 2026

@antaljanosbenjamin antaljanosbenjamin left a comment

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.

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.

@antaljanosbenjamin

Copy link
Copy Markdown
Member

@groeneai can you resolve conflicts?

@antaljanosbenjamin

Copy link
Copy Markdown
Member

@groeneai I resolved the conflicts for you

Comment thread src/Planner/Utils.cpp
/// See issue #106099.
if (filter_input_node == filter_actions_outputs[0])
{
remove_filter_column = false;

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.

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.

@antaljanosbenjamin

Copy link
Copy Markdown
Member

Probably #106438 is better

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

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

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #106438 (cleaner approach by @antaljanosbenjamin).

@groeneai groeneai closed this Jun 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Row policy with a bare-column USING expression: LOGICAL_ERROR "Duplicate column name ... in row policy actions output" (26.x regression)

2 participants