Skip to content

Apply a Merge child's row policy once, and reject it on a child that processes the query itself - #125765

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:merge-child-row-policy-applied-once
Oct 14, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:merge-child-row-policy-applied-once

Conversation

@groeneai

@groeneai groeneai commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #125580
Related: #112326

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A row policy on a Distributed table (or another table that processes the query itself) read through a Merge table now makes queries to the Merge table fail with ILLEGAL_PREWHERE for the users the policy applies to, like queries to that table itself. Before, the Merge table applied such a policy after the table had already sorted, limited and computed extremes, so queries could return wrong rows and show values of hidden rows in extremes. Define the row policy on the underlying tables of the remote servers and on the local child tables instead. This also fixes NOT_FOUND_COLUMN_IN_BLOCK on every query over a Merge table whose child has a row policy when the Merge table also reads a Distributed table.

Description

On 26.8.21.12, every query on a Merge table over a MergeTree table with a row policy and a Distributed table fails with NOT_FOUND_COLUMN_IN_BLOCK; when the row policy is on the Distributed child, ORDER BY a LIMIT 2 returns no rows and extremes = 1 prints values of rows the policy hides:

CREATE TABLE t (a UInt64, b UInt64) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT number, if(number = 5, 1000, number) FROM numbers(10);
CREATE TABLE d AS t ENGINE = Distributed(test_shard_localhost, currentDatabase(), t);
CREATE TABLE m AS t ENGINE = Merge(currentDatabase(), '^d$');
CREATE ROW POLICY p ON d USING a != 5 TO ALL;
SELECT a, b FROM m ORDER BY a SETTINGS extremes = 1; -- extremes: 0 0 / 9 1000

Selecting only a throws Got 1 in extremes chunk, expected 2 (#125580).

Root cause. ReadFromMerge added each child's row policy as a filter on top of the child's plan, whatever built it. With a Distributed sibling, a local child is planned by the interpreter, which already applies its policy; the second copy runs over a header without the policy's columns. A child that processes the query itself (Distributed, tables over one) sorts, limits, aggregates and computes extremes before that filter.

Change. A child plan built by the interpreter records that it applies its own policy, and the Merge skips its filter. A child with a row policy whose own processing stage is above FetchColumns is rejected with ILLEGAL_PREWHERE for every query, as a direct read is since #112326; the CREATE ROW POLICY documentation says so.

Validation. The new test fails on master on every line and passes with the fix, also with serialize_query_plan = 1, parallel replicas and a Replicated database. No other Merge or row-policy stateless test changes its result.


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

Version info

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

groeneai and others added 3 commits October 14, 2026 10:45
…processes the query

`ReadFromMerge::convertAndFilterSourceStream` added every child's row policy as a
`FilterStep` on top of the child plan, whatever built that plan.

When a `Merge` table also reads a `Distributed` table its stage is above
`FetchColumns`, so `createPlanForTable` builds a local child (e.g. MergeTree) with
`InterpreterSelectQueryAnalyzer`, whose planner already applies the child's policy
below its own aggregation. The `Merge` then applied it a second time over the
processed header, and every query failed with `NOT_FOUND_COLUMN_IN_BLOCK`. The child
plan now records that the interpreter built it, and the `Merge` skips its own copy.

A child that reports a stage above `FetchColumns` itself (`Distributed`, and tables
over one) sorts, limits, aggregates and computes extremes before the `Merge` sees a
row, so a filter above it was applied too late: `ORDER BY ... LIMIT` returned no
rows, `extremes = 1` printed values of rows the policy hides or threw
`Got 1 in extremes chunk, expected 2`, and aggregates failed with
`NOT_FOUND_COLUMN_IN_BLOCK`. Such a child is now rejected with `ILLEGAL_PREWHERE`,
the rule a direct read of that table follows since ClickHouse#112326.

Related: ClickHouse#125580
Related: ClickHouse#112326

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

The CREATE ROW POLICY documentation described the policy of a Merge child
that reads remotely as applied above the child's read, which this branch
replaces with an ILLEGAL_PREWHERE error for the users the policy applies to.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the comment above the Merge child row-policy rejection to one line; the cross-reference to the direct-read rule lives in the previous commit message.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (REVIEW lane): 1 finding AGREEd and fixed, 1 noted, 0 open
Finding Verdict
⚠️ The CREATE ROW POLICY docs (ParserCreateRowPolicyQuery.cpp, section "Tables that read from other tables") still said a remotely-reading Merge child gets its policy applied late and may return too few rows; this PR rejects that read with ILLEGAL_PREWHERE AGREE, docs source updated (generated page left to the docs robot)
💡 The rejection also covers plain projections that returned correct rows before Noted: same rule as a direct read of that table since #112326; stated in the description
💡 extremes showing a hidden row's value is a row-policy disclosure, so the category could be Critical Bug Fix Left as Bug Fix; I do not pick Critical Bug Fix myself, a maintainer can relabel it

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master, SELECT a FROM m ORDER BY a LIMIT 2 over a Merge whose Distributed child has a row policy returns no rows, extremes = 1 prints 9 1000 (a hidden row's value) or throws Got 1 in extremes chunk, expected 2, and with a policy on a MergeTree child next to a Distributed sibling every query fails NOT_FOUND_COLUMN_IN_BLOCK. Every run, default settings.
b Root cause explained? ReadFromMerge added each child's row policy as a filter on the child's plan whatever built it: an interpreter-built child already applies its own policy (second application over a processed header), and a child that processes the query itself sorts, limits, aggregates and computes extremes before that filter.
c Fix matches root cause? Yes. The Merge skips its filter for an interpreter-built child, and rejects a policy child whose own stage is above FetchColumns with ILLEGAL_PREWHERE, as a direct read of it is rejected since #112326. No catch, no extremes pass-through.
d Test intent preserved / new tests added? New stateless test 05400_merge_child_row_policy: a block for a policy child next to a Distributed child (rows, aggregates, LIMIT, extremes, IN-subquery policy, nested Merge policy) and a block for a policy on a Distributed child (rejected). Existing tests unchanged.
e Both directions demonstrated? Yes. Every line fails on master and passes with the fix; reverting the skip fails all 7 lines of the first block, removing the refusal fails all 5 lines of the second. 50/50 randomized runs pass.
f Fix is general across code paths? Yes: both branches of createPlanForTable (interpreter and storage->read), the JOIN path, nested Merge children, prefer_localhost_replica 0/1. MergeTree-only Merge reads keep their path and results.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for the inputs that matter here: LIMIT, aggregates, extremes, IN-subquery policies, multi-column disclosure; no type-dependent code is touched. Also green with serialize_query_plan = 1, parallel replicas and a Replicated database.
h Backward compatible? (maintainer-approved exception only) A plain projection over a Merge whose Distributed child has a row policy now gets ILLEGAL_PREWHERE, the same answer as reading that Distributed table directly; any LIMIT, aggregate or extremes on that path already returned wrong results. No setting or format change.
i Invariants and contracts preserved? A child's row policy is applied exactly once, by whoever reads its rows. The refusal is thrown before any child plan is built; processing stages are unchanged. All Merge and row-policy stateless tests keep their results.

Session id: cron:clickhouse-impl-self-slot-57:20261014-094500

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a92563f]

Summary: ✅


AI Review

Summary

This fixes duplicate child row-policy filtering in Merge and rejects policies on children that process queries beyond FetchColumns, preventing incorrect results and disclosure through extremes. No actionable findings at commit a92563f0536ea7704b6edabff483b6348be6e574. The new regression test matches its reference with default settings and serialize_query_plan = 1 using the PR-head Fast test binary; focused checks also cover Memory children, disabled optimizations, constant-false policies, joins, and remote wrappers.

Missing context / blind spots
  • ⚠️ Full sanitizer and distributed CI results were not yet available. Completed results would close the remaining CI coverage gap; focused local regression evidence is available.
Final Verdict

Status: ✅ Approve. No required code changes identified.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 14, 2026
@groeneai

groeneai commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @PedroTadim, could you review this? A Merge table applied a child's row policy a second time above a child the interpreter had already filtered, and too late above a Distributed child that sorts, limits and computes extremes itself; it now skips the duplicate and rejects the latter with ILLEGAL_PREWHERE, as a direct read is since #112326. CI has not started: the PR also needs the can be tested label, which I cannot add.

@yariks5s yariks5s self-assigned this Oct 14, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Oct 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Oct 14, 2026

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.

Ok. Technically, it is a backward-incompatible change. But a workaround is possible - set up the row policy on the remote and child tables instead of the Merge table. This is a natural way to handle row policies on Merge tables, so I expect no problems.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed. I changed the changelog category to Backward Incompatible Change and added this workaround to the changelog entry.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 14, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 14, 2026
Merged via the queue into ClickHouse:master with commit 55f3778 Oct 14, 2026
347 of 349 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 4, 2026
… PREWHERE and WHERE

`ReadFromMerge` applied the row policy of a local child as a `FilterStep` above
the child's read. The query's PREWHERE is forwarded into that read, and the
query's WHERE is pushed below the Merge, merged with the policy filter by the
child plan's optimization and moved into the read's PREWHERE as one unordered
conjunction. Either way the query's condition was evaluated on the rows the
policy hides: a condition that throws on a value (`toUInt64(payload) > 10`,
`throwIf`) printed hidden values and works as an oracle over hidden rows. A
direct read of the same table is not affected, because the planner gives the
read the policy as `SelectQueryInfo::row_level_filter`, which the reads
evaluate as a separate step before every PREWHERE step. ClickHouse#125765 fixed the
children that process the query themselves; a local child read at
`FetchColumns` still got the late filter.

Now the child's read gets the policy as its row-level filter whenever the
planner's own push-down rule says the storage can evaluate it there, and the
late `FilterStep` is not planted:

- The rule (`supportsPrewhere`, not remote, every column inside the PREWHERE
  contract) was written out twice, in the planner and in the old interpreter.
  It is now `canPushDownRowPolicyFilter`, used by both and by `Merge`.
- `RowPolicyData::makeRowLevelFilter` returns the policy as a `FilterDAGInfo`,
  or nothing when the rule fails or a column is not physical. When the Merge
  table has a policy of its own (forwarded to every child as
  `row_level_filter`), both are AND-ed into one filter that keeps every input
  column, as ClickHouse#102860 proposes; this also removes the
  `NOT_FOUND_COLUMN_IN_BLOCK` of ClickHouse#102650.
- The policy's IN-subquery sets are still built by a step above the read
  (`addCreatingSetsStep`); a Buffer child's in-memory read needs it.
- `ALIAS` columns in the policy are expanded before analysis, since a read
  cannot produce them.

When the read cannot evaluate the policy (e.g. a `Memory` child's policy over
a `DEFAULT` column) the previous path is kept. A direct read of such a table
keeps the policy as a WHERE filter and orders it the same way; that is the
planner's behaviour and is not changed here.

Behaviour changes, both matching a direct read: a Merge child's plan shows a
`Row level filter` instead of a `Filter` step, and
`apply_row_policy_after_final = 0` now applies a Merge child's policy before
FINAL.

Test: 05453_merge_child_row_policy_before_prewhere, eight arms (MergeTree
PREWHERE and WHERE, Memory, FINAL, IN subquery over Buffer, ALIAS, policies on
both tables, nested Merge) plus a control showing the condition throws on the
hidden value while it is visible.

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

Labels

can be tested Allows running workflows for external contributors comp-storage-merge Merge table engine (logical union over tables) and related mechanics. 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.

4 participants