Repository navigation
Conversation
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]>
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.
Severity: ❌ blocker / 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 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261028-080000 |
|
Workflow [PR], commit [7b8ba6b] Summary: ❌
AI ReviewSummaryThe PR applies row policies that cannot run inside a read before the query's Final VerdictStatus: ✅ Approve |
|
cc @antaljanosbenjamin @alexey-milovidov, could you review this and add the |
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]>
|
The residual listed in the description (a 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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units680 translation units recompiled, 4741 s compile time in total, 680 of them have a recent master baseline. |
CI finish ledger - 7901792Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
praktika dropped 74 later jobs, including both Session id: cron:our-pr-ci-monitor:20261028-223002 |
…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
|
@groeneai merge master and resolve the conflict in |
…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]>
|
Merged
For the CI is running on |
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]>
|
On head The two |
`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)
|
📊 Cloud Performance Report
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 … clickbenchFlagged queries (1 of 43)
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
|
Related: #116248
Related: #114955
Changelog category (leave one):
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
DEFAULTin aMemory,File,URLor object storage table, also under aMergetable) is now applied before the query'sPREWHERE,WHEREandALIAScolumns, also in a serialized query plan, so they no longer run on the rows it hides and cannot print their values in an error. AWHEREcondition with a stateful function such asrowNumberInAllBlocksis 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 ALLon aFile(Parquet)table whosetenanthas aDEFAULT,SELECT count() FROM t WHERE toUInt64(payload) > 10fails withCannot parse string 'secret' as UInt64, a value the policy hides; a throwing predicate is an oracle over hidden rows.Memory(26.10+),Mergeover such a table, andLogtables orDEFINERviews withUSING visibleleak too, also in a serialized plan.Such a policy runs after the read, but the
PREWHEREwent to the read,optimizePrewheremovedWHEREconjuncts into it,tryMergeFiltersfused later filters into the policy's, andALIAScolumns were computed before it.SelectQueryInfo::row_level_filter_after_readmarks such reads, aMergechild's too. TheirPREWHEREbecomes a filter step after the policy;optimizePrewheremoves only conjunctscanBeMovedToTheFrontOfAndChainallows.tryMergeFiltersmerges only a filter whose atoms and results can all move to the front, as the merged chain is not always split.PREWHEREprecedeCompute alias columns; aMergechild computes only the aliases its policy reads before the policy and itsPREWHERE.(... HAVING cnt > 3) WHERE rowNumberInAllBlocks() < 100returned 28 rows, not 100 (two05218cells updated).Filterstep version 1, refused for older peers).Otherwise plans without a policy are unchanged. Not covered, as on master: a
Mergetable's own policy over childALIAScolumns withquery_plan_enable_optimizations = 0, and serializedMergeTreereads (#114955).05453fails on master and passes randomized reruns.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/128043]