Skip to content

Fix logical error on Merge table with a bare-column row policy - #109843

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-row-policy-bare-column
Jul 30, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-row-policy-bare-column

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

Related: #102860

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 a logical error ("Cannot determine row level filter; 0 columns deleted, 0 columns added") when reading from a Merge table whose child table has a row policy whose filter is a bare existing column (for example CREATE ROW POLICY ... USING flag).

Description

Found by the AST fuzzer during Stress test (arm_msan) on master (STID 4390-4e70). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c1edd5f0ae54c332c83dd22bba93ee06f5e9409a&name_0=MasterCI&name_1=Stress%20test%20%28arm_msan%29

ReadFromMerge::RowPolicyData computed the row-policy filter column as "filter actions output columns minus input columns", assuming the filter always adds exactly one new column. When the policy expression is a bare existing column, the filter result column coincides with an input column, so that diff is empty and the assertion fires. Naively reusing the input column as the filter column is also wrong, because the filter column is removed from the stream after filtering, which would drop the data column and trigger "Duplicate column name ... in row policy actions output".

The fix wraps the filter result in a uniquely-named alias and uses that alias as the removable filter column, so the data columns always pass through. This matches the non-Merge row-policy path, where the filter column is a dedicated result column. Verified that the Merge output now matches the direct-table row-policy semantics for bare-column, expression, and compound policies.

A row policy whose filter is a bare existing column (e.g. USING flag)
aborted a SELECT over a Merge table with "Cannot determine row level
filter; 0 columns deleted, 0 columns added".

ReadFromMerge::RowPolicyData derived the filter column as "filter actions
output columns minus input columns", assuming the filter produces exactly
one new column. For a bare-column policy the result column coincides with
an input column, so the diff was empty and the assertion fired. Simply
reusing that input column as the filter column is also wrong: the filter
column is removed from the stream after filtering, which would drop the
data column and hit "Duplicate column name ... in row policy actions
output".

Wrap the filter result in a uniquely-named alias and use that as the
removable filter column, so the data columns always pass through. This
matches the non-Merge row-policy path, where the filter column is a
dedicated result column.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT * FROM <merge_table> where a child table has CREATE ROW POLICY ... USING <bool_column> aborts every time with "Cannot determine row level filter; 0 columns deleted, 0 columns added" (debug/sanitizer build).
b Root cause explained? ReadFromMerge::RowPolicyData derived the filter column as "filter actions output minus inputs", assuming the filter adds exactly one new column. A bare-column policy's result column equals an input column, so the diff is empty and the added.size() != 1 assertion fires.
c Fix matches root cause? Yes. The filter column must be a dedicated, removable column. The fix wraps the filter result in a uniquely-named alias and uses that as the filter column, so it is always distinct and data columns pass through.
d Test intent preserved / new test added? New stateless test 03500_row_policy_storage_merge_bare_column added, covering bare-column, expression, and compound policies over a Merge table.
e Demonstrated in both directions? Yes. Fails (aborts) on HEAD without the patch; passes with the patch (5/5 runs with randomization). Merge output verified to match direct-table row-policy semantics for all three policy shapes.
f Fix is general, not a narrow patch? Yes. The alias wrapping handles every policy expression uniformly (bare column, expression, compound, NOT), not just the one fuzzer input. Naively reusing the input column was rejected because it caused a second error ("Duplicate column name ... in row policy actions output").
g Generalizes across inputs (types, wrappers)? The filter column selection is type-agnostic (works for any expression result). Verified bare-column, a > 1, flag AND a < 3, NOT flag; all match the direct-table result.
h Backward compatible? Yes. No setting, format, or default change; internal filter-column naming only.
i Invariants and contracts preserved? Yes. The invariant that the row-policy filter column is a distinct column removable after filtering is now upheld on all paths (previously only when the policy added a new column). Data columns are preserved; matches the non-Merge row-policy path.

Session id: cron:clickhouse-worker-slot-2:20260708-203500

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @KochetovNicolai — could you review this? It fixes a logical error ("Cannot determine row level filter; 0 columns deleted, 0 columns added", AST-fuzzer-found on arm_msan stress) when a Merge table's child has a row policy whose filter is a bare existing column: RowPolicyData now aliases the filter result to a dedicated removable column instead of assuming the filter always adds a new column.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fea2b1f]

Summary: ✅


AI Review

Summary

This PR fixes StorageMerge row-policy handling when the filter is a bare existing column by introducing a dedicated helper alias, making that alias collision-safe against child columns, and trimming the filter DAG outputs so synthetic predicate columns do not leak. I re-checked the current StorageMerge code, the added stateless regressions, and all prior review threads; the previously raised correctness issues are addressed in the current diff, and I did not find a new unresolved contract violation.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
The generated __row_policy_filter alias was only checked against the
current DAG outputs, not the child table's real columns. A source table
with a real __row_policy_filter column of a different type would flow into
the same block as the alias on SELECT *, so Block::insert threw on the
duplicate name (AMBIGUOUS_COLUMN_NAME / block structure mismatch). Now the
name is also made unique against the child storage columns. Regression
test extended with a real __row_policy_filter String column.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in 13eb792. The helper name is now made unique against the child table's real columns too, not just the current DAG outputs:

NameSet reserved_names;
for (const auto & column : needed_columns)
    reserved_names.insert(column.name);

filter_column_name = "__row_policy_filter";
for (size_t i = 0; actions_dag.tryFindInOutputs(filter_column_name) != nullptr || reserved_names.contains(filter_column_name); ++i)
    filter_column_name = "__row_policy_filter_" + std::to_string(i);

Confirmed both directions on a debug build:

  • Without the fix, a child table with a real __row_policy_filter String column and USING flag aborts SELECT * through the Merge table with Block structure mismatch ... different types: __row_policy_filter UInt8 / __row_policy_filter String (AMBIGUOUS_COLUMN_NAME) — exactly the case you described.
  • With the fix, the alias is renamed to __row_policy_filter_0 and the query returns the filtered rows including the real column.

Added a stateless case for this in 03500_row_policy_storage_merge_bare_column.sql (child table with a physical __row_policy_filter String column, SELECT * through the Merge table).

Comment thread src/Storages/StorageMerge.cpp Resolved
The row-policy filter for a Merge child wrapped the policy predicate in a
__row_policy_filter alias and appended it to the actions DAG outputs. For an
expression policy such as USING a > 1 that left the raw predicate output
(greater(a, 1)) in the outputs next to the alias. FilterStep removes only the
alias, so the synthetic predicate column stayed in the stream and correctness
relied on later unused-column pruning.

With query_plan_enable_optimizations = 0 that pruning is skipped: a single
table leaked the predicate column, and a Merge over children with different
policies could fail in Pipe::unitePipes on mismatched headers.

Rebuild the post-filter outputs as the source (input) columns plus the alias,
dropping the raw predicate output regardless of plan optimizations. Added an
EXPLAIN-header regression with query_plan_enable_optimizations = 0.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in 4086b39. The post-filter outputs are now rebuilt as the source (input) columns plus the __row_policy_filter alias, dropping the raw predicate output (e.g. greater(a, 1)) instead of appending a second output. This holds regardless of query_plan_enable_optimizations, so a single table no longer leaks the synthetic column and a Merge over children with different policies keeps matching headers in Pipe::unitePipes.

Regression added to 03500_row_policy_storage_merge_bare_column with SETTINGS query_plan_enable_optimizations = 0: a Merge over children with differing policies (USING a > 1 and USING flag), plus an EXPLAIN-header assertion that the predicate does not survive past the filter:

SELECT count() FROM (EXPLAIN header = 1 SELECT * FROM 03500_m3 SETTINGS query_plan_enable_optimizations = 0) WHERE explain ILIKE '%greater(a, 1)%';

Returns 2 before the fix (predicate leaked into the child stream) and 0 after.

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4086b39

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, flaky check) — setup failure infra (port collision: Address already in use on 9000/8123/9181/9009 + RaftInstance: failed to accept ... error 125; leftover server held ports, our test 03500 never ran) #109707 (ours, open)
AST fuzzer (amd_msan) / query tree node does not have valid source node (STID 2945-38b2) flaky trunk fuzzer finding (2 unrelated PRs/30d, 0 master; not PR-caused) a fix task is created (investigating at full effort — fixing-PR link to follow here)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260709-043000

@groeneai

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for AST fuzzer STID 2945-38b2 (Column n UInt64 query tree node does not have valid source node) created: #109863 — a trunk analyzer bug (correlated recursive CTE with allow_experimental_correlated_subqueries=1), unrelated to this PR's Merge row-policy change.

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 12, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
A query-level column alias matching the helper name (SELECT flag AS
__row_policy_filter) is applied in the outer plan above the Merge child
read and never enters the child stream the row-policy filter operates
on, so it cannot clash with the generated helper alias. The helper name
is also already reserved against storage ALIAS columns via getAll().
Test confirms no AMBIGUOUS_COLUMN_NAME, correct rows, with and without
plan optimizations, single and multiple children.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

This scenario does not reproduce on HEAD. convertAndFilterSourceStream's aliases are storage ALIAS columns (storage_columns.getAliases()), not query SELECT aliases. A query-level SELECT flag AS __row_policy_filter is applied in the outer plan above the Merge child read, so it never enters the child stream the row-policy filter operates on and cannot collide with the helper alias. Storage ALIAS columns are already reserved: reserved_names is built from ColumnsDescription::getAll(), which includes ALIAS columns.

Verified SELECT flag AS __row_policy_filter FROM merge_table returns correctly filtered rows (no AMBIGUOUS_COLUMN_NAME) across: analyzer on/off, query_plan_enable_optimizations on/off, single child, and a Merge over children with differing policies (USING a > 1 | USING flag).

Added a regression in 03500_row_policy_storage_merge_bare_column (query alias equal to the helper name, single and multi-child, with and without plan optimizations) demonstrating this on HEAD. Commit 8e41051.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 8e41051

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Unit tests (asan_ubsan, function_prop_fuzzer) / FunctionsStress.stress — UBSan undefined-behavior at UTCTimestampTransform.cpp:153 fuzzer/UBSan (trunk, signed-int overflow in toUTCTimestamp/fromUTCTimestamp DateTime64; 48 PRs / 7 master, 14d; unrelated to this PR's StorageMerge diff) #109738 (ours, open)
Finish Workflow / Post Hooks infra (Config Workflow Pre/Post Hooks spike since 2026-07-03) a fix task is tracked at full effort (fixing-PR link to follow here)
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260714-093000

@alexey-milovidov

Copy link
Copy Markdown
Member

CI finish ledger — 31bfb2c

Every failure below has an owner. Only CH Inc sync is exempt (non-actionable for fork PRs).

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6): test_replicated_database/test.py::test_replicated_table_structure_alter Known flaky test, regression on master since 2026-07-10, unrelated to this PR (this PR only touches StorageMerge row-policy handling) Issue: #110036 — fixing PR in progress: #110145

Everything else is green on this run: Bugfix validation passed on both amd64 and aarch64 (the bug reproduces on master and is fixed by this branch), Mergeable Check is green, changed-line coverage is 17/17, AI Review verdict is ✅ Approve, and all review threads are resolved.

Comment thread src/Storages/StorageMerge.cpp Resolved
A child table can have a real quoted column whose name equals the row policy
predicate's column name, e.g. `greater(a, 1)` for USING a > 1. The row-policy
helper alias binds to the computed predicate node, not to that user column,
because the row-policy actions DAG's inputs are only the columns the predicate
references (a). The user column is not a node in that DAG, so it cannot shadow
the predicate function in findInOutputs, and the Merge filters on a > 1 rather
than on the user column. No silent wrong result and no AMBIGUOUS_COLUMN_NAME.

Values are chosen so a mis-bind would return a different set (a = 0, 1) than the
correct a > 1 (a = 2, 3), for both a UInt8 (would silently mis-filter) and a
String (would throw on the filter type) collision column.

Test-only: the reported defect does not reproduce on HEAD.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e7cbbd1

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. This PR's diff is src/Storages/StorageMerge.cpp (row-policy filter-alias uniqueness) + the 03500 regression test, so none of these are PR-caused.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables flaky (chronic trunk: 128 PRs + 19 master, 14d) a fix task is created (investigating at full effort — fixing PR link to follow here)
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (chronic trunk: 582 PRs + 118 master, 14d) #111029 (external, open)

Session id: cron:our-pr-ci-monitor:20260722-130000

@alexey-milovidov

Copy link
Copy Markdown
Member

CI finish ledger — 36009c0

Every failure below has an owner. Both are unrelated to this PR's change.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted): Assertion `px != 0' failed (STID 2982-48f0) Pre-existing trunk bug, unrelated to this PR: removeJoin strips the ORDER BY/GROUP BY expressions from the Merge per-child query but leaves the order_by_all/group_by_all flags set, so TreeRewriter's expandOrderByAll dereferences the null orderBy(). Reproduced with the minimal query SELECT * FROM m PASTE JOIN m AS a70 ORDER BY ALL (old analyzer, m = Merge) on the latest master binary (26.8.1.34) without this PR — same crash. The same STID also hit unrelated PRs #100173, #107736, #110633, #110760. The targeted fuzzer only reaches it here because it fuzzes this PR's Merge test tables. Fix already open: #109139 (same root cause, same file); revived it today with a fresh master merge, and verified its fix locally: the repro and its regression test pass on a fixed build.
Stateless tests (amd_tsan, parallel): 01039_mergetree_exec_time Transient kill-race, labeled flaky by the harness: expected TIMEOUT_EXCEEDED (159) but the query was killed in pending state (QUERY_WAS_CANCELLED, 394). The harness re-ran it 27× with the same randomized settings — all passed ("not reproducible, likely transient"). History: 3 hits in 90 days, all on unrelated PRs (#109360) or master. Transient; no code owner needed. Will get a tracking issue if the frequency grows.

Otherwise the PR is unchanged and merge-ready: approved by @alexey-milovidov, AI Review ✅ Approve, 0 unresolved threads, Bugfix validation OK on both arches, CH Inc sync green.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 36009c0

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Assertion px != 0 (STID 2982-48f0) TreeRewriter::analyzeSelect via StorageMerge::createChildrenPlans, trunk bug #109139 (ours, open)
Stateless tests (amd_tsan, parallel) / 01039_mergetree_exec_time query killed by timeout while pending, reported as the wrong status #110533 (ours, open)

Fast test, Style check and all Bugfix-validation jobs are green on this head.

Session id: cron:our-pr-ci-monitor:20260726-163000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_check_all_tables flaky (Integration amd_asan_ubsan, db disk, old analyzer): #111353 (merged 2026-07-22, backported to 26.7 by #111574).

The failure is the plain-rewritable metadata_dropped concurrent-create race, not anything in this PR. Every occurrence after that merge is on a build whose base predates it: I checked all 49 distinct commits that produced this failure since 2026-07-22 17:31Z, and 49 of 49 lack the fix. Merging master into this PR picks it up. Details: #111477 (comment)

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 17/17 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 7492281 Jul 30, 2026
179 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

🕵 This fix never reached any active release branch, and the row-policy logical error it fixes is still reachable on all five. pr-bugfix is "not backported by default", so no label was ever applied and no backport PR exists.

I reproduced it on the shipped release binaries (builds.clickhouse.com/<X.Y>/amd64/clickhouse) with a bare-column policy on a Merge table:

CREATE TABLE child1 (a UInt64, flag UInt8) ENGINE = MergeTree ORDER BY a;
INSERT INTO child1 VALUES (1,1),(2,0),(3,1);
CREATE TABLE merge_tbl (a UInt64, flag UInt8) ENGINE = Merge(currentDatabase(), '^child');
CREATE ROW POLICY p_bare ON child1 USING flag TO ALL;
SELECT * FROM merge_tbl ORDER BY a;

26.7, 26.6, 26.5 and 26.3 all give Code: 49 ... Cannot determine row level filter; 0 columns deleted, 0 columns added; 25.8 gives the same on a real server. Master returns the correct filtered rows under identical flags. Latest CI sighting is 26.6 Stress test (arm_ubsan) at 8aaee94c6d458033d84b4b3972479937addefb78: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.6&sha=8aaee94c6d458033d84b4b3972479937addefb78&name_0=ReleaseBranchCI&name_1=Stress%20test%20%28arm_ubsan%29

I simulated the port the way cherry_pick.py builds it (merge -s ours the release tip onto this PR's master base, then merge into the merge commit). It is clean on all five branches, and each resulting tree contains all five commits of this PR: 3 files, +236/-13, __row_policy_filter present 3 times, the old assertion gone, and the regression test plus its reference riding along. ActionsDAG::tryFindInOutputs already exists on 25.8, so no hand adaptation is needed there.

@alexey-milovidov, could you apply v25.8-must-backport here? Per select_backport_branches that expands to 26.7, 26.6, 26.5, 26.3 and 25.8, which is exactly the affected set. A narrower v26.6-must-backport would cover only 26.7 and 26.6.

One caveat: I verified the ports merge cleanly and contain the whole fix, but I did not build any release branch, so compilation is still for the backport PRs' own CI to confirm.

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

3 participants