Skip to content

Apply the row policy of a Merge table's local underlying table before PREWHERE and WHERE - #128013

Merged
fm4v merged 7 commits into
ClickHouse:masterfrom
groeneai:merge-child-row-policy-before-prewhere
Nov 4, 2026
Merged

fm4v merged 7 commits into
ClickHouse:masterfrom
groeneai:merge-child-row-policy-before-prewhere

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #102650
Closes: #125912
Closes: #125027
Related: #125765
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):

Fixed a Merge table evaluating the query's PREWHERE and WHERE on rows that a row policy of a local underlying table hides. A condition that throws on a value, such as toUInt64(column) > 10, printed values of the hidden rows. The policy is now applied by the underlying table's read before PREWHERE, as for a direct read of that table.

Description

On 26.8.16.41, with a policy USING tenant = 'a' on a MergeTree table t and m = Merge(currentDatabase(), '^t$'), SELECT count() FROM m PREWHERE toUInt64(payload) > 10 (and the WHERE form) fails with Cannot parse string 'secret', a value of a hidden row, while the same query on t returns 2. With throwIf it answers any question about hidden rows.

Root cause: ReadFromMerge applied a child's policy as a FilterStep above the child's read. The forwarded PREWHERE runs inside that read, and a pushed-down WHERE is merged with the policy filter into PREWHERE. #125765 covered only children that run the query themselves.

Change: the child's read gets the policy as its row-level filter, evaluated before PREWHERE, whenever the planner's push-down rule allows it (now one helper for the planner, InterpreterSelectQuery and Merge). A policy on the Merge itself is combined with the child's into one filter, as #102860 does; this also removes the NOT_FOUND_COLUMN_IN_BLOCK of #102650. ALIAS columns and their subcolumns in a policy are expanded first. With apply_row_policy_after_final = 0 a child's policy now runs before FINAL, as for a direct read. Two policies keep the late filter, as before: one the read cannot evaluate (a Memory DEFAULT column, late on a direct read too) and one over an ALIAS of a virtual column (_table).

Validation: a new test of thirteen arms (MergeTree, Memory, Memory DEFAULT, FINAL under both settings, IN over Buffer, ALIAS over a column, its subcolumn and _table, a lambda argument named like it, policies on both tables, nested Merge with one and two policy levels) fails on master in all but the two late-filter and the lambda-argument arms, and passes here and in 50 randomized runs, DBReplicated and plan-based parallel replicas. 175 row-policy and Merge tests: no new failures.


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

Version info

  • Merged into: 26.11.1.1287-master (included in 26.11 and later)

groeneai and others added 6 commits October 27, 2026 19:56
… 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]>
…arded one

`RowPolicyData::makeRowLevelFilter` found the child policy's filter node by
name after `ActionsDAG::merge`. The forwarded row-level filter can itself be
another `RowPolicyData`'s filter: for a `Merge` over a `Merge` with policies on
the inner `Merge` and on the leaf table, both are named `__row_policy_filter`.
`merge` lists the forwarded outputs first, so the lookup returned the forwarded
node and the filter became `and(F, F)`. The leaf policy was dropped and, as the
read was marked as applying the policy, the late filter was skipped too, so
rows hidden by the leaf policy were returned.

The child policy's filter is now aliased under a name that does not occur
among the forwarded DAG's inputs and outputs before the merge.

Test: a new arm of 05453 (nested `Merge`, policies at both levels; rows and
PREWHERE).

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

The FINAL arm of 05453 had one row per key, so FINAL deduplicated nothing and
could not show whether a child's policy ran before or after FINAL. The child's
policy is now the read's row-level filter, so the default "after FINAL" comes
from `ReadFromMergeTree::isRowPolicyDeferredAfterFinal`.

New arm: a versioned `ReplacingMergeTree` with merges stopped and two parts for
one key, the newer version hidden by the policy. Through the `Merge` table,
`apply_row_policy_after_final = 1` returns 0 and `= 0` returns 1, as a direct
read of the table does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…REWHERE contract stays above the read

`canPushDownRowPolicyFilter` refuses a policy either when the storage has no
PREWHERE support or when a policy column is outside its
`supportedPrewhereColumns`. Only the first refusal was tested through `Merge`.

New arm: a `Memory` child whose policy reads a `DEFAULT` column, which
`StorageMemory::supportedPrewhereColumns` excludes. Rows cannot tell a
pushed-down policy from a late one here, so the arm checks the plan: the child
read of the plain `Memory` arm has a row-level filter, the `DEFAULT` arm's read
has none.

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

`RowPolicyData` expanded `ALIAS` columns in the child's policy
unconditionally. The expansion is analysed over the table's ordinary columns
only, so an `ALIAS` such as `tv ALIAS concat(_table, ':', tenant)` made every
query on the `Merge` fail with `Missing columns: '_table'`.

Expand `ALIAS` columns with the virtual columns visible to the expansion, and
keep the expansion only if the result reads ordinary columns. Otherwise the
policy is analysed over the `ALIAS` column as before, and is applied above the
read. A policy over a virtual column itself is still rejected, as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the new comments in StorageMerge and ColumnsDescription to their invariants; drop one that restated a function name.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review: my own cold review plus an independent model (engine: codex; 8 findings in total).

# Sev Finding Verdict Evidence / action
1 ❌ A Merge over a Merge with row policies on the inner Merge and on its underlying table gave both policy filters the same column name, so the combined row-level filter dropped the underlying table's policy (StorageMerge.cpp, makeRowLevelFilter) AGREE, fixed @ d3275e3 the child policy column is named uniquely against the forwarded filter; new test arm with policies at both levels of a nested Merge
2 ⚠️ The FINAL test arm has one row per key, so it cannot show whether a child's policy runs before or after FINAL AGREE, fixed @ ff2d765 versioned duplicate-key ReplacingMergeTree arm with both apply_row_policy_after_final values
3 ⚠️ No test shows that a child policy over a column outside the read's PREWHERE contract (a Memory DEFAULT column) stays above the read AGREE, fixed @ 9c1005c EXPLAIN arm: no row-level filter in that child's read, with the physical-column Memory arm as the positive control
4 💡 Use Critical Bug Fix for a row-policy disclosure DISAGREE that category is chosen by maintainers, not proactively by me
5 💡 A Merge over a Buffer whose destination declares a column with another type now hands the Buffer both the child policy and the PREWHERE over that column DISAGREE (out of scope) the resulting double conversion is in StorageBuffer::read, also reachable by a direct read, fails with an exception, and is fixed by #113624
6 ❌ Expanding a child policy's ALIAS columns analyses an ALIAS over a virtual column (_table) without virtual columns, so every query on such a Merge fails with UNKNOWN_IDENTIFIER (StorageMerge.cpp, RowPolicyData) AGREE, fixed @ e5ec77b the expansion is kept only when it reads ordinary columns, else the policy is analysed as before; new test arm with an ALIAS over _table
7 ❌ A child policy written directly over a virtual column (USING _part_offset < 100) is rejected when the child is read through a Merge (StorageMerge.cpp, RowPolicyData) DISAGREE (out of scope) master rejects it the same way (the policy is analysed over the declared columns only, unchanged here); the query fails closed and no hidden row is evaluated; supporting virtual columns in a child policy is a separate change
8 💡 A child policy over an ALIAS of a virtual column keeps the late filter, so the query's PREWHERE still runs on that child's hidden rows, while a direct read pushes the policy down AGREE, disclosed this is master's ordering for that policy, unchanged; named in the description

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261027-224300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A Merge over a MergeTree table with a row policy, SELECT count() FROM m PREWHERE toUInt64(payload) > 10 fails with Cannot parse string 'secret' on every run on master (and on 26.8.16.41, 26.3.42.3); the new test fails 10 of 10 randomized runs on master.
b Root cause explained? Yes. ReadFromMerge applied a child's policy as a FilterStep above the child's read, while the forwarded PREWHERE (and the pushed-down WHERE, merged with the policy filter and moved into PREWHERE) is evaluated inside that read, on the hidden rows.
c Fix matches root cause? Yes. The child's read gets the policy as its row-level filter, the mechanism the planner uses for a direct read, which the reads evaluate before PREWHERE. No guard, no rejection, no setting.
d Test intent preserved / new tests added? New test with eleven arms plus a control that proves the condition does throw on the hidden value while it is visible. No existing test changed.
e Both directions demonstrated? Yes. Master: every arm but the two late-filter ones (Memory DEFAULT, ALIAS over _table) throws on a hidden value. Fix: every arm returns the direct read's result; 50 of 50 randomized runs. Eight mutations each redden their arm.
f Fix is general across code paths? Yes. One push-down rule, shared by the planner, the old interpreter and Merge; covered MergeTree family, Memory, Buffer, nested Merge, FINAL, IN subquery, ALIAS, policies on both tables. Remote children and children that process the query themselves are unchanged (#125765).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. LowCardinality and Nullable policy columns, a Nullable filter result, bare Bool policies, a column named __row_policy_filter, apply_row_policy_after_final 0 and 1 on a versioned ReplacingMergeTree (as for a direct read), and policies over a Memory DEFAULT column and an ALIAS of _table, which stay above the read.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or error code. A Merge child's plan now shows Row level filter instead of a Filter step, and apply_row_policy_after_final = 0 applies to a Merge child as it does to a direct read.
i Invariants and contracts preserved? Yes. The read's output columns are unchanged, a read with a row-level filter records nothing in the query condition cache, IN sets are still built before the read, and plan-based parallel replicas return the same results.

Session id: cron:clickhouse-impl-slot-5:20261027-222600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @pufit, could you review this and add the can be tested label so CI runs? A Merge table applied a local underlying table's row policy as a filter above that table's read, so the query's PREWHERE and WHERE were evaluated on rows the policy hides (a throwing condition printed their values); the read now gets the policy as its row-level filter, as a direct read does.

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [333c437]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR moves a child table's row policy for a Merge read into the child's row-level filter whenever the child can evaluate it, so PREWHERE and pushed-down WHERE no longer inspect rows hidden by that child policy. I re-read the current diff, the new regression test, the prior inline thread, and the PR discussion; the current head matches that contract, the previously reported ALIAS-subcolumn gap is fixed, and I do not see a remaining correctness issue in the touched paths.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-storage-merge Merge table engine (logical union over tables) and related mechanics. labels Oct 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 28, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
`replaceAliasColumnsInQuery` expands only identifiers that name a declared
column, so a child policy such as `USING a.t = 'a'` with `a` an `ALIAS` column
kept reading `a.t`. The read cannot produce that, so the policy stayed a filter
above the read, and the query's `PREWHERE` still ran on the hidden rows first.

Rewrite such a subcolumn into `getSubcolumn(a, 't')` before the `ALIAS`
expansion, as the analyzer resolves it, including inside lambda bodies. A
subquery, and an identifier whose name or any dotted prefix of it is a lambda
argument, are left as they are, since they do not name this table's columns;
such a policy keeps the late filter, as before.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 333c437

Every failure below has an owner: a fixing PR (mine 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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 53 of 81 runs in the last 6 hours are red, on 51 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

Both Bugfix validation (functional tests) jobs, all five stateless flaky check builds and AST fuzzer (amd_release, oracle) passed on this head.

Session id: cron:our-pr-ci-monitor:20261028-200004

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

Verified with the CI binary of 333c437 against master a018bd2bbaa6:

  • The reproducer from the description, plus throwIf(payload = 'secret') in WHERE, FINAL with apply_row_policy_after_final = 0, an IN (SELECT ...) child policy combined with a policy on the Merge table, and a MergeTree + Log pair of children: master throws on the hidden rows in every case, this PR returns the policy-filtered counts.
  • #102650, #125912 and #125027 reproduce on master and are fixed here, so I added them as Closes:.

The only red check is Build profile diff, an infrastructure failure (LogClusterNotReady).

@fm4v
fm4v added this pull request to the merge queue Nov 3, 2026
Merged via the queue into ClickHouse:master with commit cce2803 Nov 4, 2026
177 of 179 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 4, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 4, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 4, 2026
Backport #128013 to 26.10: Apply the row policy of a `Merge` table's local underlying table before `PREWHERE` and `WHERE`
PedroTadim added a commit that referenced this pull request Nov 5, 2026
…is not on this branch

On this branch a `merge` child's row policy is applied above the child's read, so with a
`Distributed` sibling raising the stage it fails with NOT_FOUND_COLUMN_IN_BLOCK even without a view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 5, 2026
…is not on this branch

On this branch a `merge` child's row policy is applied above the child's read, so with a
`Distributed` sibling raising the stage it fails with NOT_FOUND_COLUMN_IN_BLOCK even without a view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…is not on this branch

On this branch a `merge` child's row policy is applied above the child's read, so with a
`Distributed` sibling raising the stage it fails with NOT_FOUND_COLUMN_IN_BLOCK even without a view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…is not on this branch

On this branch a `merge` child's row policy is applied above the child's read, so with a
`Distributed` sibling raising the stage it fails with NOT_FOUND_COLUMN_IN_BLOCK even without a view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…local underlying table before `PREWHERE` and `WHERE`
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

6 participants