Skip to content

Apply a row policy that the read cannot evaluate before the query's PREWHERE and WHERE - #128043

Open
groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:fix-row-policy-outside-prewhere-contract
Open

groeneai wants to merge 15 commits into
ClickHouse:masterfrom
groeneai:fix-row-policy-outside-prewhere-contract

Conversation

@groeneai

@groeneai groeneai commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116248
Related: #114955

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):

A row policy on a column that the read cannot filter by (for example a column with a DEFAULT in a Memory, File, URL or object storage table, also under a Merge table) is now applied before the query's PREWHERE, WHERE and ALIAS columns, also in a serialized query plan, so they no longer run on the rows it hides and cannot print their values in an error. A WHERE condition with a stateful function such as rowNumberInAllBlocks is no longer fused with the filter below it, which returned wrong results.

Description

On 26.9.19.9, with CREATE ROW POLICY p ON t USING tenant = 'a' TO ALL on a File(Parquet) table whose tenant has a DEFAULT, SELECT count() FROM t WHERE toUInt64(payload) > 10 fails with Cannot parse string 'secret' as UInt64, a value the policy hides; a throwing predicate is an oracle over hidden rows. Memory (26.10+), Merge over such a table, and Log tables or DEFINER views with USING visible leak too, also in a serialized plan.

Such a policy runs after the read, but the PREWHERE went to the read, optimizePrewhere moved WHERE conjuncts into it, tryMergeFilters fused later filters into the policy's, and ALIAS columns were computed before it.

  • SelectQueryInfo::row_level_filter_after_read marks such reads, a Merge child's too. Their PREWHERE becomes a filter step after the policy; optimizePrewhere moves only conjuncts canBeMovedToTheFrontOfAndChain allows.
  • The policy's filter step is marked, and keeps the mark when merged, split, pushed down or rebuilt. Over a marked step or read, tryMergeFilters merges only a filter whose atoms and results can all move to the front, as the merged chain is not always split.
  • The policy step and a demoted PREWHERE precede Compute alias columns; a Merge child computes only the aliases its policy reads before the policy and its PREWHERE.
  • Filters with a stateful function are never merged: without a policy, (... HAVING cnt > 3) WHERE rowNumberInAllBlocks() < 100 returned 28 rows, not 100 (two 05218 cells updated).
  • A serialized plan marks the policy step too and carries the mark (Filter step version 1, refused for older peers).

Otherwise plans without a policy are unchanged. Not covered, as on master: a Merge table's own policy over child ALIAS columns with query_plan_enable_optimizations = 0, and serialized MergeTree reads (#114955).

05453 fails on master and passes randomized reruns.

🤖 Generated with Claude Code


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

groeneai and others added 7 commits October 27, 2026 23:20
A row policy on a column outside the read's PREWHERE contract (a column with a
DEFAULT in Memory, File, URL, object storage) is not pushed into the read and runs
as a filter step after it. An explicit PREWHERE, and every WHERE conjunct that
optimizePrewhere moved into the read, then ran before the policy on the rows it
hides, so a throwing predicate printed a hidden value or worked as an oracle.

- SelectQueryInfo::row_level_filter_after_read marks such a read (planner, and
  the Merge read of a child whose policy it applies after the read).
- The PREWHERE of such a read becomes a filter step after the policy.
- optimizePrewhere moves only conjuncts that canBeMovedToTheFrontOfAndChain
  allows, and nothing when the filter has an order-sensitive function.
- tryMergeFilters does not merge a stateful filter (not split into its AND
  chain, so the upper filter would see the rows the lower one rejects).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With a stateful upper filter merged into the lower one, the merged filter is not
split into its AND chain, so the upper condition is evaluated on the rows the
lower one rejects. On 05218's fixture, `... HAVING cnt > 3) WHERE
rowNumberInAllBlocks() < 100` returned 28 rows before the previous commit and 100
with `query_plan_merge_filters = 0`; it now returns 100 both ways, and the two
05218 cells that pinned the merged plan now see the HAVING filter unmerged. The
same merge let the query's own stateful conjunct reopen the row-policy leak:
`WHERE rowNumberInBlock() >= 0 AND toUInt64(payload) > 10` with
`short_circuit_function_evaluation = 'disable'` printed the hidden value against a
stateless policy. 05453 gains both cases.

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

A row policy that the read cannot take runs as a filter step right after the
read. Merging the query's filters into it was not safe: the merged AND chain is
not split with `query_plan_merge_filters = 0` (JOIN runtime filters merge
regardless of it) and never at a column atom such as `USING visible`, so a
merged condition ran on the rows the policy hides and printed their values.
Over a read whose row-level filter is applied after it, a filter is now merged
only when every atom of its AND chain and every other result it computes can
be moved to the front of the chain (canBeMovedToTheFrontOfAndChain), and, when
the lower filter has a column atom, so can every atom of the lower filter.
Other reads merge as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The planner computed the ALIAS columns of a table between its read and a row
policy that the read could not take, and a Merge table computed the ALIAS
columns of a child before the child's row policy, so an alias such as
`toUInt64(payload)` was evaluated on the rows the policy hides and could print
their values. The policy filter is now added right after the read, before the
alias columns; a Merge child computes before its policy only the aliases the
policy reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A read step that keeps no query info (Log, StripeLog, a DEFINER view with a
row policy on the view) cannot say that a row policy is applied right after
it, so the merge rule of the previous commits did not apply there and a
condition merged into such a policy still ran on the rows it hides. The
filter step that applies the policy is now marked, keeps the mark when it is
merged, split or pushed down, and the rule applies over it as well. Plans
without a row policy are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test runner turns query_plan_merge_filters off in some runs. Then the
query's filters are not merged into the row policy's filter, and the cases
that need that merge pass whether or not the policy is applied first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove comments that restate a function or variable name and condense three multi-line comments to one line.

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 by an independent model (engine: codex; 6 findings over 5 rounds) plus my own review.

# Sev Finding Verdict Evidence / action
1 ❌ A policy that is a column (USING visible) was fused with the query's WHERE by tryMergeFilters; the AND-chain split never splits column atoms, so with short_circuit_function_evaluation = 'disable' the WHERE ran on hidden rows AGREE, fixed @ 01537b5 see row 3 (same fix)
2 ❌ The same in the default mode once the merged chain has two non-column atoms (also PREWHERE, additional_table_filters, the policy's own throwing atom) AGREE, fixed @ 01537b5 see row 3 (same fix)
3 ❌ JOIN runtime filters merge filters even with query_plan_merge_filters = 0, which also turns the AND-chain split off, so a policy fused with toUInt64(payload) > 10 ran it on hidden rows under short_circuit_function_evaluation = 'disable' AGREE, fixed @ 01537b5 over a read with a late row-level filter, a filter is merged only if its atoms and results pass canBeMovedToTheFrontOfAndChain (also a lower filter's, when it has a column atom); 05453 arms
4 ⚠️ (own review) The round-2 column-atom rule applied to every plan: a no-policy MergeTree (SELECT * FROM t WHERE flag) WHERE toUInt64(s) > 10 lost the PREWHERE move of the outer condition AGREE, fixed @ 01537b5 rule limited to reads with a late row-level filter; no-policy plans as on master (05453 EXPLAIN arm)
5 ❌ ALIAS columns were computed between the read and a late policy (parsed ALIAS toUInt64(payload), query_plan_enable_optimizations = 0) AGREE, fixed @ dbc9ecf the policy filter is added before Compute alias columns; 05453 arms
6 💡 With a child policy, a Merge table's PREWHERE now runs after FINAL DISAGREE the late policy already runs after FINAL there, and a direct read defers PREWHERE behind a deferred policy the same way (ReadFromMergeTree::isPrewhereDeferredAfterFinal)
7 ⚠️ (own review) A Merge child still computed its ALIAS columns before its late policy AGREE, fixed @ dbc9ecf only the aliases the child's policy reads are computed before it (a policy may read one, 02763_row_policy_storage_merge_alias); 05453 arms
8 ❌ (own review, then the gate) Reads without query info (Log, StripeLog, a DEFINER view with a view policy) missed the merge rule, so a column policy with a two-atom WHERE still leaked in the default mode AGREE, fixed @ 26bd675 the late-policy filter step is marked and keeps the mark through merge, split and push-down; the rule applies over it; 05453 arms
9 ⚠️ The runner turns query_plan_merge_filters off in 5% of runs, and then the 05453 arms that need a merged filter pass without exercising the fix AGREE, fixed @ 7aae06e -- Random settings limits: query_plan_merge_filters=(1, None); the two arms that test = 0 set it per query

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

Bounce cap reached: published as is after the final fix round. Its one commit (row 9, a test-only settings clamp) was not re-gated; no residual findings.

Session id: cron:clickhouse-review-self-slot-58:20261028-102000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05453 on master: Code: 6 ... Cannot parse string 'secret' (WHERE / PREWHERE on Memory, File(Parquet), Merge child policy, Merge own policy), Code: 395 for throwIf, [1] for the stateful merge. Every run.
b Root cause explained? A policy over a column outside supportedPrewhereColumns() is planted as a filter step above the read; the query's PREWHERE still went to the read and optimizePrewhere moved WHERE conjuncts into it, so they ran on hidden rows. A filter with a stateful function was fused with the one below it and never split into its AND chain.
c Fix matches root cause? Yes. The read knows a row-level filter follows it: its PREWHERE becomes a filter step after the policy, and only conjuncts that canBeMovedToTheFrontOfAndChain allows are moved (none when the filter is order-sensitive). tryMergeFilters does not fuse stateful filters. No error is swallowed.
d Test intent preserved / new tests added? New 05453: every leaking arm (Memory, File(Parquet), Merge child and own policy, throwIf, order-sensitive and stateful policies and conjuncts, a column policy USING visible in every short_circuit_function_evaluation mode, a JOIN runtime filter with query_plan_merge_filters = 0, ALIAS columns, Log, a DEFINER view, Merge over Log), precision arms (a safe conjunct still moved, a no-policy plan still moving to PREWHERE, a no-policy stateful merge) and a negative control. query_plan_merge_filters is clamped on, so the merge arms are never vacuous (checked in system.query_log). Two 05218 cells keep their queries and expect the unmerged plan; 05234 unchanged and passes.
e Both directions demonstrated? Yes. Master: 05453 and the two 05218 cells fail; fix: pass. Removing each code change on its own reddens exactly its arms (merge-rule scope, alias order, the upper filter's other outputs, Merge child aliases, the policy-step mark, the mark on merge); the previous round's binary fails exactly the new arms.
f Fix is general across code paths? Direct reads (planner), Merge child and own policy (flag forwarded with the query info). The merge rule holds over the marked policy step (kept when merged, split, or pushed through a Union) and over flagged SourceStepWithFilter reads: measured fixed for Log, StripeLog, Buffer over Log, a DEFINER view and Merge over Log. Remote reads: no leak. Serialized plans still leak (#114955 family), stated in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? Throwing predicates (toUInt64, throwIf), every short_circuit_function_evaluation mode, query_plan_merge_filters = 0/1 (including a JOIN runtime filter), rand() and rowNumberInBlock() policies, a column policy alone or in an AND chain, PREWHERE, additional_table_filters, ALIAS columns (also of a Merge child; 02763_row_policy_storage_merge_alias still works), JOIN shapes, lazy materialization, max_block_size = 1; 50/50 randomized. A condition all of whose atoms can be moved to the front (payload != 'zzz') is still merged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, protocol or serialized-plan change, no new rejection. Plans change only over a read with an unpushed policy and for adjacent filters with a stateful function; only a policy step carries the mark. Without a policy, EXPLAIN is byte-identical to master on MergeTree and Memory; the no-policy Log plan and the 05056 parallel-replicas plan are identical to the previous head.
i Invariants and contracts preserved? The SelectQueryInfo contract "prewhere condition should not be executed over filtered rows" now holds for unpushed policies. The demoted step passes every read column through and keeps remove_prewhere_column.

Session id: cron:clickhouse-impl-self-slot-57:20261028-080000

@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b8ba6b]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 2/2) FAIL
04780_json_subcolumn_index_match_not_quadratic FAIL cidb
La Casa Del Dolor (amd_msan) FAIL
Logical error: Directory 'A' is virtual (STID: 6611-5d35) FAIL cidb

AI Review

Summary

The PR applies row policies that cannot run inside a read before the query's PREWHERE, WHERE, and unrelated ALIAS expressions, preserves the policy barrier through plan rewrites and serialization, and keeps evaluation-sensitive filters separate. Reviewed head 7b8ba6b097a764de99f4ffb570836afe2184ddc1 and all prior discussion. Earlier findings are addressed or adequately explained; no new actionable findings remain. Focused checks using the PR-head CI binary passed for direct and Merge alias reads, serialized reads, and deferred PREWHERE with aliases.

Final Verdict

Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @alexey-milovidov, could you review this and add the can be tested label so CI runs? A row policy the read cannot take (for example on a DEFAULT column of a Memory or File table) runs as a filter after the read, but the query's PREWHERE, the WHERE conjuncts moved into it, filters merged into the policy's and ALIAS columns were evaluated on rows the policy hides, so a throwing condition printed their values; now the PREWHERE is a filter step after the policy, the ALIAS columns it does not read are computed after it, and only conditions safe on the rows it rejects are moved into the read or merged with it. It touches the same PlannerJoinTree/StorageMerge code as my #128013 (the Merge child case).

@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Oct 28, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 28, 2026
@yariks5s yariks5s self-assigned this Oct 28, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Processors/QueryPlan/FilterStep.h Resolved
A logical plan (`serialize_query_plan = 1`) of a storage whose PREWHERE support depends
on the columns (`Memory`, `File`, `URL`, object storage) or of a table function carried
the row policy as an ordinary filter step, and `FilterStep::serialize` did not write the
late row-level filter mark. The node that executes the plan rebuilds the read without the
query info flag, so it merged the query's `WHERE` / `PREWHERE` into the policy's step and
`optimizePrewhere` moved conjuncts of the policy and of the query into the read's PREWHERE.
A value the policy hides was then printed in an error again, e.g.
`SELECT count() FROM cluster('test_shard_localhost', db, t) WHERE toUInt64(payload) > 10
SETTINGS serialize_query_plan = 1, prefer_localhost_replica = 0` on a `Memory` table with
`tenant String DEFAULT 'a'` and policy `tenant = 'a'`, the same on a `Log` table with
`USING visible`, and a policy `visible AND toUInt64(payload) < 1000` even without a `WHERE`.

- The logical-plan policy step goes through the same path as a policy the read cannot
  take: it is marked and added before the alias columns, still ahead of the PREWHERE step.
- `FilterStep::serialize` writes the mark as flag bit 2 at `Filter` step version 1 (plan
  version 21), `deserialize` restores it. A marked step is refused for an older peer, which
  would ignore the bit, like a `ReadFromMergeTree` read with the query condition cache
  disabled.
- On that node the mark is the only barrier, so it is kept where the plan is rebuilt:
  `optimizePrewhere` treats a marked filter over the read like a flagged read and keeps the
  mark on the filter it leaves when it moves only some conjuncts, and lazy materialization
  keeps it on the filters it re-creates. Otherwise the merges forced after JOIN runtime
  filters and after lazy materialization (both even with `query_plan_merge_filters = 0`)
  fused the query's condition into what was left of the policy.

Also apply a PREWHERE that the read cannot take right after the policy, before the alias
columns, as the read did: with `query_plan_enable_optimizations = 0`,
`SELECT sum(parsed) FROM t PREWHERE payload != 'bad'` with `parsed ALIAS toUInt64(payload)`
computed the alias for the row the PREWHERE drops and failed.

Found by the automated review on ClickHouse#128043.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... and removed comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. labels Oct 28, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

The residual listed in the description (a Merge table's own row policy runs after the child tables compute their ALIAS columns when query_plan_enable_optimizations = 0) is in the same code as this PR: a fix would apply that policy inside each child plan before the aliases it does not read, as this PR already does for a child's own policy in ReadFromMerge::convertAndFilterSourceStream. A plain Log child is enough, on master and on this PR:

CREATE TABLE tl (tenant String, payload String, parsed UInt64 ALIAS toUInt64(payload)) ENGINE = Log;
INSERT INTO tl (tenant, payload) VALUES ('a', '5'), ('b', 'secret');
CREATE TABLE ml (tenant String, payload String, parsed UInt64) ENGINE = Merge(currentDatabase(), '^tl$');
CREATE ROW POLICY pl ON ml USING tenant = 'a' TO ALL;
SELECT sum(parsed) FROM ml SETTINGS query_plan_enable_optimizations = 0; -- Cannot parse string 'secret' as UInt64

@yariks5s, should I add it to this PR, or open a separate PR after this one is merged?

…es not read

A `Merge` child whose row policy the read cannot take gets the query's PREWHERE as a
filter after the policy. That filter was added after the child's remaining ALIAS
columns, so with `query_plan_enable_optimizations = 0` they were computed for the rows
the PREWHERE drops: `SELECT sum(parsed), max(payload) FROM m PREWHERE payload != 'bad'`
over a `Memory` or `MergeTree` child with `parsed UInt64 ALIAS toUInt64(payload)` and
a policy that admits every row failed with `Cannot parse string 'bad' as UInt64`, while
master and the same query without the policy return `35 5`.

The PREWHERE now runs right after the policy, before those aliases, as on a direct
read. It reads only physical columns of a child: `StorageMerge::supportedPrewhereColumns`
rejects a column that is an ALIAS in a child and an ordinary column of the `Merge` table
(`ILLEGAL_PREWHERE`), and an ALIAS the `Merge` table declares itself reaches the child as
its expression over physical columns.

Found by the automated review on ClickHouse#128043.

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

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7b8ba6b09 with master 4aa16c68a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

680 translation units recompiled, 4741 s compile time in total, 680 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7901792

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
Stateless tests (amd_debug, parallel) / Logical error: Trying to deserialize data into Variant column with not global variants order (STID: 6636-4f2a) logical error, not from this PR (its diff does not touch JSON, Variant or the MergeTree readers): SHARED paths of a JSON column read through the columns cache of a Wide part. 14 runs on 12 PRs and master since 2026-10-26 #127867 (mine, open)
Stateless tests (amd_debug, parallel) / Server liveness check failed collateral of the abort above #127867 (the owner of the first row)
Finish Workflow / Post Hooks new_tests_check.py found no passed Bugfix validation job, because both functional arms were dropped by the first row and never ran #127867 (the owner of the first row)
Mergeable Check, PR praktika rollups of the rows above #127867 (the owner of the rows above)

praktika dropped 74 later jobs, including both Bugfix validation (functional tests) arms, because of the first row, so they did not run on this head. CH Inc sync is green.

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

fm4v added 2 commits November 11, 2026 12:18
…ide-prewhere-contract

# Conflicts:
#	src/Core/ProtocolDefines.h
#	src/Processors/QueryPlan/FilterStep.cpp
#	src/Processors/QueryPlan/FilterStep.h
#	src/Processors/QueryPlan/Optimizations/filterPushDown.cpp
#	src/Processors/QueryPlan/Optimizations/optimizeLazyMaterialization.cpp
#	src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp
#	src/Processors/QueryPlan/Optimizations/splitFilter.cpp
#	src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp
#	src/Storages/MergeTree/MergeTreeWhereOptimizer.h
#	src/Storages/StorageMerge.cpp
#	src/Storages/StorageMerge.h
…ide-prewhere-contract

# Conflicts:
#	src/Storages/SelectQueryInfo.h
@fm4v

fm4v commented Nov 17, 2026

Copy link
Copy Markdown
Member

@groeneai merge master and resolve the conflict in src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp (also re-check that the auto-merged src/Core/ProtocolDefines.h protocol revision does not collide with a revision master added since). CI on the previous head 1e9d528 was green (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=128043&sha=1e9d528eebfcae6389ddf2ed2090c83c462a6758&name_0=PR); please confirm 05453 and Bugfix validation pass on the new head.

…ide-prewhere-contract

Conflict in src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp: master moved
getSortingKeyNamesSafeBeforeFinal out of the anonymous namespace and reopened it
for isReadByTopKFilterOnly; canBeMovedBeforeRowLevelFilter now sits in that
reopened anonymous namespace.

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

Copy link
Copy Markdown
Collaborator Author

Merged master (3c5abca8d5fb) into the branch. New head 0a1b8d955e5e is a fast-forward of 1e9d528e (no force push), and the PR diff against master is unchanged: 19 files, +530/-44.

  • MergeTreeWhereOptimizer.cpp (the only conflict): Apply a row policy that uses currentUser() or now() before FINAL again #130536 moved getSortingKeyNamesSafeBeforeFinal out of the anonymous namespace and reopened it for isReadByTopKFilterOnly. canBeMovedBeforeRowLevelFilter now sits in that reopened namespace. The two call sites in analyzeImpl/analyze merged cleanly. The new grouping from Keep a PREWHERE guard on a subcolumn ahead of a throwing condition on its sibling #131054 and Keep the primary key conditions at the end of PREWHERE next to a condition that cannot use the key #131360 only regroups viable conjuncts, so a conjunct this PR keeps out of PREWHERE still stays out.
  • ProtocolDefines.h: no collision. DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_FILTER_ROW_LEVEL_MARK = 21 is the current, unreleased DBMS_QUERY_PLAN_SERIALIZATION_VERSION on master (26.10 ships 20, and there is no 26.11 branch yet). The gates master added at 21 since then (..._WITH_PARALLEL_SINGLE_LEVEL_MERGE_BY_INDEX, ..._WITH_DISTINCT_LIMIT_HINT) cover other steps and settings. Nothing else on master uses Filter step version 1 or flag bit 8, and the TCP protocol revision is not touched.
  • Local debug build of 0a1b8d955e5e: 05453 and 05218 pass, and both also pass 30/30 runs with randomized settings. On a master debug build (9b107508c683) both fail, which is what Bugfix validation checks (05453 fails with Code: 6 ... Cannot parse string 'secret' as UInt64). Across 378 prewhere/row-policy stateless tests there is no failure that master does not also have. The 10 touched TUs also pass -fsyntax-only with clang-23 and CI's warning flags.

For the v26.10-must-backport cherry-pick: 26.10 is at plan version 20, and its FilterStep::serialize writes only the remove_filter_column bit, so FilterStep.cpp will conflict. If the gate stays at 21 there, a 26.10 node never writes the mark, and a serialized plan carrying a late row policy fails with SUPPORT_IS_DISABLED instead of running.

CI is running on 0a1b8d955e5e. I'll confirm 05453 and Bugfix validation here once they finish.

master enabled modernize-use-nodiscard, so Build (arm_tidy) fails on
FilterStep::isRowLevelFilterAfterRead and
ReadFromMerge::RowPolicyData::requiresColumn.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Processors/QueryPlan/FilterStep.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

On head 9467f6470ec7, Bugfix validation (functional tests) passed on amd64 and aarch64, and 05453 passed in all 382 runs so far (15 jobs, including the flaky checks under asan, tsan, msan, debug and binary). The commit on top of the master merge only adds [[nodiscard]] to the two accessors this PR adds, because master enabled modernize-use-nodiscard (#126158) and Build (arm_tidy) failed on 0a1b8d955e5e.

The two [Blocker] findings of the latest AI review do not reproduce on this head; I replied in both threads with the measurements.

fm4v added 2 commits November 20, 2026 21:02
`tryMergeFilters` bailed out only for stateful functions, but a filter with a function that is not deterministic in the scope of the query (`rand64`, `generateUUIDv4`) or has observable side effects (`sleep`) also changes when it is evaluated on the rows the lower filter rejects. Use `isSensitiveToEvaluationCount` on both filters, which also looks into constant-folded lambdas.

Addresses ClickHouse#128043 (comment)
@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — inconclusive across 29 queries analysed

PR verdict: not_sure. 1 measured difference(s) not attributable to this PR. clickbench Q31: The measured difference cannot be attributed to this PR from the available source evidence. Q31 is a single-table scan of hits with one predicate, SearchPhrase <> '', and a GROUP BY WatchID, ClientIP aggregation. There is no row policy, ALIAS column, Merge engine or stacked filter. In the pinned test merge 8151d7a4 (PR head 1610353 against master 77566fdc), each runtime change is gated on a late row policy. This applies to src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp (row_level_filter_after_read gate), src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp …

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 31 not_sure 226 199 -11.9% <0.0001 aggregation: The measured difference cannot be attributed to this PR from the available source evidence. Q31 is a single-table scan of hits with one predicate, SearchPhrase <> '', and a GROUP BY WatchID, ClientIP aggregation. There is no row policy, ALIAS column, Merge engine or stacked filter. In the pinned test merge 8151d7a4 (PR head 1610353 against master 77566fdc), each runtime change is gated on a late row policy. This applies to src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp (row_level_filter_after_read gate), src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp …

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d5e5e7b6-5258-44cc-a5bd-0ac7a96a41eb
  • MIRAI run: 93777223-d80a-46ee-8b15-76661898847a
  • PR check IDs:
    • clickbench_554305_1795211820
    • clickbench_554311_1795211820
    • tpch_adapted_1_official_554348_1795211820
    • tpch_adapted_1_official_554368_1795211821

This branch has not been deployed

No deployments
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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants