Skip to content

Apply a row policy to a read shipped as a serialized query plan - #114955

Closed
groeneai wants to merge 61 commits into
ClickHouse:masterfrom
groeneai:fix-row-policy-serialized-query-plan-112891
Closed

groeneai wants to merge 61 commits into
ClickHouse:masterfrom
groeneai:fix-row-policy-serialized-query-plan-112891

Conversation

@groeneai

@groeneai groeneai commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator

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 SELECT row policy on a shard-local table being ignored when the read is shipped to the executing server as a serialized query plan (serialize_query_plan = 1, with process_query_plan_packet enabled there). Reads through a Distributed table with prefer_localhost_replica = 0, and reads over parallel replicas, returned rows the policy excludes. Closes #112891.

Description

Closes: #112891

What breaks. On 26.9 and master, with a policy USING y < 5 on a 10-row MergeTree table, SELECT count() through a Distributed table with serialize_query_plan = 1 returns 10, not 5. With parallel replicas, a policy fixing the first sorting key column can fail the query with a LOGICAL_ERROR: Coordination mode mismatch ...: got Default, expected WithOrder (job) or Got read request from replica N for unknown stream (job).

Root cause. A policy the initiator pushes into the read (SelectQueryInfo::row_level_filter, for a storage that filters it in PREWHERE) is lost, because the shipped read is a bare ReadFromTableStep.

The change. The step records whether a filter step of the plan carries the policy (#122503 adds one for Memory). If not, the executing node plans the read again, as for Merge, and applies its own policy once. A read planned again does not reapply a policy a step applies; its own additional_table_filters entry, evaluated here, and the sender's if different, replace the sender's entry step, or follow the read's own steps (positions recorded). For a Merge or remote table the node checks its own grants and max_columns_to_read on the selected columns the step carries and its grants on the shipped filter. These ride in ReadFromTable step version 1, written only from plan version 21, so older peers get the old bytes.

SelectQueryOptions::subquery() also resets ignore_rename_columns, which fixes a Merge table with an IN (SELECT ...) policy (NOT_FOUND_COLUMN_IN_BLOCK, on master too).

Residual. A policy the initiator ships as a step governs that read, not the executing server's own. From an older initiator, or over such a step if the entry's column types differ between servers, a nondeterministic entry is applied twice. For a shipped plain-table read the executing server checks no grant or max_columns_to_read, as on master.

Measured arms
arm, serialize_query_plan = 1 before after
policy y < 5, MergeTree on 26.9 10 5
nondeterministic policy shipped as a step (Log, MATERIALIZED column) once once
26.9 initiator, Memory, nondeterministic policy once once
Merge table, policy x IN (SELECT ...) NOT_FOUND_COLUMN_IN_BLOCK [0,3,6,9]
Merge table, additional_table_filters x = randConstant() % 100000, also x = (SELECT randConstant() % 100000 FROM numbers(1)) 0 rows (twice) 1 row
Merge table, PREWHERE x < 5, entry throwIf(x >= 5) = 0 throws 5
parallel replicas, ORDER BY (a, b), policy a = 'nomatch', ORDER BY b LOGICAL_ERROR, mode mismatch 0 rows
same, policy a = 'engineering', remote replica's request first LOGICAL_ERROR, unknown stream 2 rows

Two servers, Merge table (test_serialized_query_plan_receiver_grants): a receiver without the grant on a selected or additional_table_filters column gives ACCESS_DENIED with both settings, as on master; a user without a grant on the policy column still reads; the receiver's own READONLY additional_table_filters (10, not 45) and max_columns_to_read (TOO_MANY_COLUMNS, not 90) hold with both settings, and so does its READONLY max_threads = 1 in a shared entry x < getSetting('max_threads'), also under a Merge policy (1, not 2), and a shared entry whose scalar subquery reads a table, a dictionary or a file that differs between the nodes (3, not 7), and an entry y IN (SELECT v FROM lim) reads the lim of the receiver's own current database (2 rows, not UNKNOWN_DATABASE).

Mutations: recording no step turns the step-shipped arms into double application; replanning an unknown placement makes the 26.9 initiator arm apply the policy twice; writing the bit at step version 0 fails the gtest. --test-runs 50 with randomized settings: 300/300.


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

groeneai and others added 9 commits August 14, 2026 20:37
A SELECT row policy on a shard-local table was not applied when the read
reached the executing replica as a serialized query plan: a Distributed
read with prefer_localhost_replica = 0, or a read distributed over
parallel replicas, returned rows the policy excludes.

The initiator resolves the policy into SelectQueryInfo::row_level_filter,
because a plain MergeTree table accepts filter push-down into the read.
Under build_logical_plan the leaf becomes a placeholder ReadFromTableStep,
which has no field for that filter, so it is dropped and never serialized.
On the executing node replaceReadingFromTable rebuilds the read through
storage->read() with a hand-built SelectQueryInfo that never sets
row_level_filter. Each side assumes the other applied the policy.

Rebuild such a read through the reconstructed-query path resolveStorages
already uses for remote and Merge storages. That path runs the ordinary
planner, so the policy is resolved in the executing node's own access
context, together with the read-column widening, the FINAL row-policy
deferral and the PREWHERE ordering guard. The predicate is keyed on the
storage's PREWHERE-column contract rather than a concrete type, so it
covers forwarding wrappers and reproduces the initiator's push-down
decision only where that decision is node-invariant. Storages that refuse
push-down keep the direct read path, so their policy, which is already
shipped as a filter step, is not applied twice.

No wire format change and no protocol version bump, so mixed-version
replicas are unaffected. Reads of tables with no policy are unchanged.

Serializing the filter instead would need a plan-serialization version
bump, and RemoteQueryExecutor disconnects replicas below
DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_PARALLEL_REPLICAS, which is
defined as the current version - so the bump would drop every older
replica from all parallel-replica queries. Deciding on the initiator is
not possible either, since effective row policies are resolved per node.

A policy that exists only on the receiver, on a storage whose
PREWHERE-column contract is not nullopt, can still be missed; telling that
case apart needs the plan to carry whether a policy step was already
emitted, which this change does not add.

Closes: ClickHouse#112891
The two tests added with the fix could each go green on an unfixed binary,
because CI randomization can remove the conditions the leak needs.

The Distributed test never pinned the analyzer, but a shipped plan is only
built when it is on (SelectStreamFactory.cpp), and the old-analyzer stateless
job skips a test only on a no-old-analyzer tag. Measured on the unfixed binary
with the analyzer off: every leak arm returned the filtered value.

The parallel-replica test pinned neither parallel_replicas_local_plan nor
automatic_parallel_replicas_mode, both randomized by clickhouse-test. A remote
replica receives the plan only inside canUseLocalPlanForParallelReplicas, so a
draw of 0 shipped no plan at all and all arms passed on the unfixed binary.

The FINAL arms had one row per key, so FINAL deduplicated nothing and all four
printed the same result: they proved neither the policy ordering nor any
difference between the two apply_row_policy_after_final values. Two rows per
key with distinct versions restores that, split across two inserts so the rows
on disk do not depend on optimize_on_insert, which only merges within a block.

The Memory exactly-once arm used a deterministic policy, which returns the same
count applied once or twice and so could not detect the double application it
guards. A nondeterministic policy over 100000 rows keeps about half the rows
once and a quarter twice; the test classifies rather than comparing counts.

Every arm was re-run on the unfixed and fixed binaries under the new pins.
… read

The columns of a shipped plan are a read list, not the list of columns the
query selects: a row policy widens it with the columns the policy itself
reads. Replanning that read ran the column-level SELECT check over the wider
list, so a user granted only the columns it selects was refused with
ACCESS_DENIED where the non-serialized path answered. The columns the user
does select are authorized where the plan is built, and a user with no grant
on the table is still refused there, so the check on the executing node only
ever saw columns nobody asked for.

Reachable only through a cluster carrying a <secret>: without one the
executing node runs as the interserver default user, whose grants are
unrestricted, so nothing was checked against the querying user at all.

Also covers additional_table_filters running exactly once on the replanned
read, which nothing asserted, and drops a stale comment in
04652_nested_merge_prewhere_type_mismatch_2 that described the leak this
branch fixes as a standing bug.
A row policy may contain an IN subquery. Its set is registered while the
filter is built (buildFilterInfo -> collectSets), but the reconstructed read
is planned only to QueryProcessingStage::FetchColumns, and the planner returns
for that stage before it adds the step that builds such sets. The read then
referenced a set nobody built and execution reached function `in` with a
not-ready set.

Export addBuildSubqueriesForTableFilterSets from the planner and call it for
the reconstructed read, in the row-policy branch only. It reuses the planner's
own set-step builder, so the CTE-materialization and limit handling of that
builder are unchanged, and no step is emitted for a read whose filters
reference no subquery.

Building that set exposed two options leaking from the read into the set's own
plan. ignore_table_access_check is now reset by SelectQueryOptions::subquery():
a subquery names its own tables, so its column list is the user's own and must
be checked, and the non-serialized path does refuse when the grant is missing.
ignore_rename_columns is reset in a local copy at the call site, since a set's
plan is consumed through column identifiers while this read's output names have
to match the shipped plan's.

Tests: 04908 covers the subquery policy on the local, serialized and
non-serialized paths. 04910 now aggregates per shard, because the CI
interserver-secret cluster has two shards pointing at the same server, so the
old assertion depended on the shard count rather than on the policy; it also
gains no-fasttest, since that cluster requires SSL, which the Fast test build
does not have.

Co-Authored-By: Claude Fable 5 <[email protected]>
The receiver replan cleared additional_table_filters wholesale so that this
table's entry, which the initiator already lowered into an explicit filter step
of the shipped plan, would not be resolved a second time. The policy's own IN
subquery is planned under that same context, and a table reached only from
inside the policy had no plan shipped for it, so its entry was never lowered
and clearing it dropped the filter outright. With serialize_query_plan = 1 such
a read returned the rows the filter excludes; without it the filter applied.

Drop only the entries that name the table being replanned, using the same key
forms parseAdditionalFilterAstIfNeeded matches, so the double application stays
prevented while entries for other tables survive to be resolved.

The two effects are pinned by separate arms of
04910_row_policy_serialized_query_plan_grants: removing the scoping reddens the
new subquery arm alone, and removing the suppression entirely reddens the
existing atf nd arm alone.
The entry for the table being replanned arrives as an explicit filter step of the
shipped plan, so resolving it again on the executing node would filter twice. That
suppression was applied by rewriting the setting on the context handed to the
interpreter, and every planner below inherits that context: buildFilterInfo takes a
Context::createCopy for the policy's query tree while the interpreter is being
constructed, and set building plans each subquery from a context descended from the
same copy. A read the policy's own filter performs therefore lost the entry too.

Keying the suppression by entry, as it was, cannot separate two reads of the same
table: the root read, whose entry was already lowered into the shipped plan, and a
read of that table reached only through the policy's filter, for which nothing was
lowered. Both key on one name.

Carry the suppression on the read's own SelectQueryOptions instead, checked where the
root read parses the setting. Options do not descend into subqueries, and subquery()
resets the flag next to the access-check flag it already resets, so a nested read
resolves its own entries and the two obligations no longer collide.

The Distributed-view inlining path is left ungated: a policy is replanned only for a
storage supporting PREWHERE, and StorageView does not, so a view read cannot carry
the flag.
Two diagnostics and three documentation pages told the reader that a row policy on an
underlying table is not applied to a read shipped as a serialized plan, and to keep
serialize_query_plan at 0 for users whose policies must be enforced. That is no longer
true for the storages the reader is being pointed at.

The diagnostics keep their own subject, which is unchanged: a policy on a table that
delegates reading to remote servers cannot be pushed into the shipped read. Their
advice to define the policy on the underlying tables is now unconditional, so the
trailing clause is removed rather than replaced.

The row-policy reference page keeps a warning, now carrying the limitation that
remains: whether a policy present only on the executing server is applied depends on
the engine of the table the initiator sees, so the tables behind one Distributed table
should share an engine. The links to the issue this closes are dropped.
Both tests assert the values a filtered read produces, and shipping the query as text
filters correctly too, so a run that never shipped a plan produces the same output as
one that did. Pinning the settings makes the route eligible; nothing observed it. A
change to the gate that selects the route, or to the parallel-replicas local-plan
precondition, would leave every assertion satisfied.

The initiator records a used row policy only where it resolved one, which is what
building the plan for shipping makes it do; shipping text leaves the policy to the
executing node and records nothing. Assert that, and for parallel replicas assert that
a replica reported reading marks, which only a replica given a read task does. Replicas
run against their own default database, so their rows are reached through the
initiator's row.

Both are asserted as booleans, so randomized settings cannot move the expected value.
The route oracles added in the previous commit read the initiator's own
query_log row. The initiator records a used row policy while it BUILDS the
plan, and attaching that plan to the shard is a separate later step
(SelectStreamFactory stores Shard::query_plan; ReadFromRemote selects the
QueryPlan stage only when it is non-null), so a regression that built the plan
and failed to attach it would leave the counter populated, fall back to text
shipping, and keep every arm of both tests green. The parallel-replicas arm had
the same gap one layer out: ParallelReplicasReadMarks is reported by any replica
given a read task, plan or text.

Both oracles now assert on the executing node instead, through the TRACE
message TCPHandler logs after deserializing a runnable plan, joined to the run
via the receiver's initial_query_id. Verified by suppressing plan attachment at
both attachment sites while leaving construction intact: only the two new lines
flip, every value arm and the sqp=0 negative control are unchanged, and the
retired initiator-side oracle still returns its reference values.

Also rewrites the row-policy reference paragraph whose rationale contradicted
the warning added in this pull request eight lines below it. Remote execution is
shipped as query text or as an already-built read plan; in neither form can the
wrapper apply its own policy filter, which is why such reads are rejected rather
than silently unfiltered.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (7 rounds, adjudicated)

Independent cold review plus a second-model gate on every round, adjudicated against the recorded
evidence. Verdicts below are mine.

# Finding Verdict
⚠️ Both serialized-plan route oracles flush the logs once and immediately join the secondary query's query_log row. SYSTEM FLUSH LOGS waits only through the index present at flush time, and a secondary row can be published after the initiator has returned, so a valid received-plan event can read as absent. AGREE, not fixed in this PR
❌ The route oracles observed used_row_policies, which the initiator records while BUILDING the plan; a regression that built the plan and failed to attach it would ship green. AGREE, fixed: both oracles now assert the executing node's Received query plan, joined by initial_query_id. Proven by suppressing attachment at both attachment sites with construction intact: only those two lines flip, every value arm and the serialize_query_plan = 0 control are unchanged.
❌ Replanning ran the column-level SELECT check over the policy-widened read list, refusing a user granted only the columns actually selected. AGREE, fixed; 04910 asserts both refusals still hold for either setting.
❌ A policy containing an IN subquery referenced a set nobody built, because a FetchColumns plan returns before the planner's own set-building step. AGREE, fixed.
❌ Suppressing the read table's additional_table_filters entry also suppressed it for a read reached only through the policy's own filter. AGREE, fixed: the suppression is carried on the read's SelectQueryOptions, which do not descend into subqueries.
❌ A storage whose PREWHERE-column contract is not nullopt would be replanned on a verdict that is not node-invariant, double-applying the shipped filter. AGREE, fixed: the predicate is restricted to nullopt-contract storages; Memory arms pin that the direct path is kept, using a nondeterministic policy so one application is distinguishable from two.
❌ Several arms could pass on an unfixed binary once CI randomization removed the conditions the leak needs (analyzer off, parallel_replicas_local_plan = 0, one row per key under FINAL, a deterministic exactly-once policy). AGREE, fixed; every arm re-run on both binaries under the new pins.
❌ The reference page said remote-backed tables only ship query text, contradicting the warning this PR adds eight lines below. AGREE, fixed.
💡 Document the two missed engine classes by internal predicate rather than by example. DISAGREE: that names an implementation detail with no user-facing lever.
💡 The isRowPolicyPushedIntoRead header comment exceeds the per-block length guide. DISAGREE: it is the API contract, and the node-invariance restriction is the safety argument for the predicate.
💡 No test arm for the table-function read path. DISAGREE: getEffectiveRowPolicyFilter requires a database on the storage id and a resolved table function has none, so that path is structurally unchanged.
💡 The residual paragraph did not say the limitation is pre-existing. AGREE, fixed in the description.

The one open item. The flush race above is a test-determinism defect in the two new route
assertions, not in the fix: it fails closed (a missing row reads as 0 against an expected 1, so
the test reddens), so it can cost a CI rerun but cannot hide a regression or affect the change
itself. The remedy is a bounded flush-and-retry loop around both oracles, the idiom already used in
00177_memory_bound_merging. Flagging it rather than folding it in, since the review budget for this
PR is spent; happy to push it in this PR if you would rather it land here.

Session id: cron:clickhouse-review-slot-9:20260815-135500

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [96d9e1f]

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro Yes. count() through the Distributed table returns 10 on master and 5 with the fix, every run, from a single queries file. No randomization needed. A policy containing an IN subquery is equally deterministic: it returns the policy-filtered array on the local and non-serialized paths and raised Not-ready Set is passed on the serialized one before the set-building fix.
b Root cause explained Yes. The initiator puts the policy in SelectQueryInfo::row_level_filter; the placeholder ReadFromTableStep has no field for it, so it is dropped and never serialized; the receiver rebuilds the read with a hand-built SelectQueryInfo that never sets it.
c Fix matches root cause Yes. The read is rebuilt on the receiver either way; the change selects the rebuild path that can resolve the policy for this input class. No widened bounds, no skip tag, no guard at the symptom.
d Test intent preserved, tests added Yes. Three new stateless tests. Each was shown unable to pass without the code it covers by deleting that code and watching it redden: removing the set-building call makes the subquery-policy arm abort with Not-ready Set is passed, and removing the additional_table_filters suppression entirely turns the exactly-once arm from ONCE to TWICE, and leaving that suppression unscoped reddens the policy-subquery filter arm alone ([0,1,2] becomes [0,1,2,3,4,5,6,7,8,9]), so the two arms pin opposite halves of one rule; an arm covering a read of that same table reached through the policy's own filter reddens ([2] becomes []) when the suppression is applied to the whole read rather than to the root read alone. Two route oracles were added because every value assertion is satisfied by the text-shipping fallback too, and both assert on the node that executes the read rather than on the initiator's decision to ship a plan: suppressing plan attachment at both attachment sites, while leaving plan construction intact, reddens only those two lines and leaves every value assertion and the negative-control arm green. The grant test aggregates per shard, so its assertion tracks the policy rather than the shard count; run against a one-shard cluster it fails, which is what proves it is topology-correct rather than merely passing. No existing test weakened or removed; the row-policy and serialized-plan suites pass unchanged, as do all 14 stateless tests that use column-level GRANT SELECT(...). Each test pins the settings its own arms depend on (analyzer for the shipped plan, local plan for parallel replicas), verified by showing the unpinned form passes on the unfixed binary. The FINAL arms differ per apply_row_policy_after_final value, the exactly-once guards use nondeterministic filters, and the grant arms were shown to fail on the unfixed binary, so none can pass without exercising what it covers.
e Both directions demonstrated Yes. Every arm was run on the master binary and the fixed binary with the same server and the same queries; both tests fail on master.
f General across code paths Yes. Both producers of a shipped plan (Distributed via SelectStreamFactory, parallel replicas via ParallelReplicasLocalPlan) were enumerated from source and are covered by the single receiver-side change; the placeholder step has exactly one construction site. Storages where the initiator refuses push-down were verified to keep the direct path.
g Generalizes across inputs Yes. Measured on both binaries for policy columns of type LowCardinality(String), Nullable(UInt32), Array(UInt32), ALIAS, MATERIALIZED, plus always-true and always-false policies, an empty table and a single-row table. Both additional_table_filters key forms that parseAdditionalFilterAstIfNeeded accepts (db.table, and bare table when the current database matches) are covered, alongside a multi-entry map in which one entry names the replanned table and another names a table the policy reads. Master leaks on all six non-trivial cases; the fix matches the non-serialized result. Also measured across grant shapes (all columns, only the selected column, only the policy column, none) and both cluster forms, including the cross-replication Distributed(cluster, '', table) spelling whose table identifier carries no database.
h Backward compatible Yes. No setting default changed, no SettingsChangesHistory.cpp entry needed, no wire format change and no protocol version bump, so mixed-version replicas are unaffected.
i Invariants and contracts preserved Yes. Read limits still enforced (max_rows_to_read = 1 raises TOO_MANY_ROWS, matching the non-serialized path, where master returned rows silently). The table lock is still taken before either branch. The FINAL row-policy deferral and the PREWHERE ordering guard operate unmodified. additional_table_filters and a receiver-side policy are each applied exactly once, asserted by nondeterministic-filter arms whose ability to detect a second application was shown by removing the guard and watching them redden. The exactly-once suppression is scoped to the entries naming the table being replanned, so an entry for a table reached only through the policy's own filter, for which no plan was shipped, is still resolved and matches the non-serialized path. The suppression is carried on the read's own options rather than on a context, so it cannot descend into the reads the policy's filter performs, including a read of the same table: measured on all three transports (local, text-shipped, plan-shipped) agreeing, where the context-wide form diverged. Access control is preserved rather than relaxed: the columns a query selects are authorized where the plan is built, and a user without SELECT on the table read is refused there, so only the re-check of columns the user never selected is skipped, and only for a policy-bearing read. Verified on a cluster carrying a <secret>, where the executing node runs as the querying user rather than the interserver default. The skip does not reach a policy's own IN subquery: SelectQueryOptions::subquery() resets the flag, so the subquery's tables are checked, matching the non-serialized path, which refuses when that grant is missing.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vitlibar, could you review this? A SELECT row policy on a shard-local table is resolved into SelectQueryInfo::row_level_filter, which the placeholder ReadFromTableStep has no field for, so it is dropped when the plan is serialized and the executing node rebuilds the read without it; this routes such a read through the reconstructed-query path resolveStorages already uses for remote and Merge storages, so the policy is resolved in the executing node's own access context. Related: #107745 fixes the same bug by serializing the filter instead, which needs a plan-serialization version bump.

The route assertions joined a log row written by the secondary query on the
executing node, after a single SYSTEM FLUSH LOGS on the initiator. That flush
only waits through the rows that exist when it runs (SystemLog.cpp takes
last_log_index at flush time) and the initiator returns before the secondary
row is published, so a correct binary could read 0 and the test would fail.

A .sql file cannot loop, so both oracles move to a new .sh test that retries
the flush until the executing node's own query_log row is visible, following
00177_memory_bound_merging.sh. It prints the number of secondary queries next
to how many of them ran a received plan, so a zero caused by an invisible row
is distinguishable from a zero caused by a text-shipped read.

Verified by suppressing plan attachment at both attachment sites while leaving
plan construction intact: the two positive arms go 1 -> 0 and 2 -> 0, the
serialize_query_plan = 0 negative control stays 0, and the retired oracles in
04908 redden on the same mutation, so no detection power is lost. 200/200 at
--test-runs 50 on the restored binary.

The docs change removes a contradiction this PR introduced: access-rights.mdx
and the support-center copy claimed the underlying-table policy applies for
every engine, while the warning added to row-policy.mdx states it is missed for
engines that do not accept filter push-down.
The style check requires a current_database predicate on any
system.query_log read in a stateless test, and the new route oracle in
04909 had none.

A plain current_database = currentDatabase() cannot be used here: the
oracle reads the *secondary* queries of a distributed or parallel-replica
read, and those rows log current_database = 'default' rather than the
test database. Measured on both arms of this test, that predicate takes
the oracle to 0 rows in every arm, which passes the style check while
making the test assert nothing.

Use current_database IN ['default', currentDatabase()], the idiom already
used for secondary-query rows in 04366, 03701 and 03704. Verified that
the oracle's output is bit-identical to the unfiltered form on all three
arms, and that replacing it with the plain equality reddens the test.
The receiver rebuilds the read as a SELECT that names every column of the
shipped plan's header, which the row policy has already widened past the
columns the query selects. Its planner then counts those columns against
max_columns_to_read, while the ordinary path checks the limit before the
policy widens the read.

So a query that succeeds locally and with serialize_query_plan = 0 was
rejected with TOO_MANY_COLUMNS once the read arrived as a serialized
plan, which is the same asymmetry between the two paths this fix exists
to remove. Measured against pristine master: the local and sqp = 0 arms
return 5 on both binaries, and only the sqp = 1 arm changed.

Skip the limit for that reconstructed read, the way the column-level
access check is already skipped for it, and for the same reason: the
column list there is a read list, not a list of columns the user asked
for, and the limit was applied to the user's own selection where the plan
was built. A selection that genuinely exceeds the limit is still
rejected, on both paths.
The warning listed `Memory`, `Buffer` and `File` as engines where a policy
defined on the executing server is missed. Measured per engine against
pristine master, the list was wrong in both directions: `Memory` and
`File(TSV)` return the filtered count on all three paths, while
`File(Parquet)` and `Buffer` return unfiltered rows under
`serialize_query_plan = 1` even with the same policy on every server.

The engine name alone does not decide it. What decides it is whether the
storage supports `PREWHERE` for only part of its columns, which for `File`
and the object storage engines depends on the format. Describe that
condition instead of listing engines, and give the workaround, verified to
return the filtered count for both affected engines.

This is master behaviour and is unchanged here; the warning is what was
inaccurate.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 31d3eb8, three commits.

The style check was right: the new route oracle read system.query_log with no
current_database predicate. The plain = currentDatabase() cannot be used here, because the
oracle reads the secondary queries of a distributed or parallel-replica read and those rows log
current_database = 'default'. Measured, it takes every arm of that test to 0, so it would have
passed the check and asserted nothing. Used current_database IN ['default', currentDatabase()]
instead, as in 04366, and confirmed the oracle's output is unchanged on all three arms.

Two fixes came out of reviewing that push, both worth flagging:

  1. A read that arrived as a serialized plan was rejected with TOO_MANY_COLUMNS where the same
    query succeeded locally and with serialize_query_plan = 0. The receiver rebuilds the read
    naming every column of the shipped header, which the policy has already widened, and the limit
    is otherwise checked before that widening. Against pristine master the local and sqp = 0 arms
    are identical and only sqp = 1 changed, so this was mine. max_columns_to_read now skips that
    reconstructed read, the way the column-level access check already does and for the same reason;
    a selection that genuinely exceeds the limit is still rejected on both paths. Covered by a new
    arm in 04908 that reddens if the bypass is removed.

  2. The docs warning I added listed Memory, Buffer and File as engines where a policy defined
    on the executing server is missed. Measured per engine, that was wrong in both directions:
    Memory and File(TSV) filter correctly on all three paths, while File(Parquet) and Buffer
    return unfiltered rows even with the same policy everywhere. The engine name does not decide it,
    the PREWHERE-column contract does, and for File and object storage that depends on the
    format. The warning now states that condition and gives the workaround. That behaviour is
    master's and unchanged here.

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 186a82c84 with master c9e18d017 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 831894676; 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.

Object file sizes

90 object files changed (+407.37 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/resolveStorages.cpp.o 180.57 KiB 298.16 KiB +117.58 KiB (+65.12%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromTableStep.cpp.o 69.71 KiB 94.46 KiB +24.75 KiB (+35.50%)
src/CMakeFiles/dbms.dir/Planner/PlannerJoinTree.cpp.o 915.16 KiB 936.57 KiB +21.41 KiB (+2.34%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -344.0 s (-6%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 31d3eb8

CI is fully finished on this head: 177 check runs, 161 success, 16 skipped, 0 failed checks.
Every check-run conclusion is success or skipped.

The CIDB test-level enumeration reports four FAIL rows on this commit, all inside the
Bugfix validation (functional tests, *) jobs. Those are not failures: bugfix validation runs
the regression tests against the pre-fix master binary and inverts the per-test verdict
(invert_bugfix_validation_status in ci/jobs/functional_tests.py), so a per-test FAIL
recorded in CIDB is exactly the "bug reproduced without the fix" proof the job exists to
produce. Both arch jobs report Failed: 3, Passed: 2 pre-inversion and both finished
success, i.e. the bug reproduced on amd64 and aarch64 and the validation passed.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64) / 04652_nested_merge_prewhere_type_mismatch_2 inverted-verdict reproduction on the pre-fix binary, job conclusion success fixed in this PR @ 31d3eb8
Bugfix validation (functional tests, amd64) / 04909_row_policy_serialized_plan_route inverted-verdict reproduction on the pre-fix binary, job conclusion success fixed in this PR @ 31d3eb8
Bugfix validation (functional tests, aarch64) / 04652_nested_merge_prewhere_type_mismatch_2 inverted-verdict reproduction on the pre-fix binary, job conclusion success fixed in this PR @ 31d3eb8
Bugfix validation (functional tests, aarch64) / 04909_row_policy_serialized_plan_route inverted-verdict reproduction on the pre-fix binary, job conclusion success fixed in this PR @ 31d3eb8

No check on this head needs an external owner.

Session id: cron:our-pr-ci-monitor:20260816-113000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 31d3eb8

Correcting my previous ledger comment on this head: I had the direction of the
Bugfix validation inversion backwards. The corrected reading is below.

CI is fully finished on this head: 177 check runs, 161 success, 16 skipped, 0 failed checks.
Every check-run conclusion is success or skipped, and the CIDB check-level enumeration
(check_status IN ('failure','error')) is empty.

Bugfix validation stores the INVERSE of each test's real outcome, so a stored OK means the
test failed on the master binary (bug reproduced, validated) and a stored FAIL means it passed
on master (that test did not demonstrate the bug). Projecting every row of the run, identically
on amd64 and aarch64:

Stored Test Meaning
OK 04908_row_policy_serialized_query_plan validated (pre-fix reason: The query succeeded but the server error '158' was expected)
OK 04908_row_policy_serialized_plan_parallel_replicas validated (pre-fix reason: result differs with reference)
OK 04910_row_policy_serialized_query_plan_grants validated (pre-fix reason: result differs with reference)
FAIL 04652_nested_merge_prewhere_type_mismatch_2 did not demonstrate the bug on master
FAIL 04909_row_policy_serialized_plan_route did not demonstrate the bug on master

That split is corroborated by the job's own pre-inversion summary, Failed: 3, Passed: 2, and by
the fact that the three stored-OK rows are the only ones carrying a failure reason in their
info (951, 2239 and 15923 bytes); the two stored-FAIL rows have empty info.

So three of five regression tests reproduce the bug on master, on both arches, and both per-arch
jobs finished success, which satisfies the validation contract and confirms the pr-bugfix
category.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64 + aarch64) / 04652_nested_merge_prewhere_type_mismatch_2 passes on master, so it does not demonstrate the bug; it is a pre-existing test this PR extends, not the PR's demonstration case own test, addressed in this PR
Bugfix validation (functional tests, amd64 + aarch64) / 04909_row_policy_serialized_plan_route passes on master, so this new test does not demonstrate the bug by itself own test, addressed in this PR

No other check on this head needs an owner, and no external owner is required.

Session id: cron:our-pr-ci-monitor:20260816-113000

@yariks5s yariks5s self-assigned this Aug 16, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Resolves the one conflict, in `src/Planner/PlannerJoinTree.cpp`.

Master extended `getEffectiveRowPolicyFilter` in place so that a `StorageAlias`
also contributes the SELECT policy of its target table, joined with
`combineRowPolicyFilters`. This branch had moved that function to
`src/Planner/Utils.cpp`, because the node that executes a shipped plan resolves
the policy through `isRowPolicyPushedIntoRead` and needs the same definition.

The resolution keeps the move and carries master's alias handling into the moved
copy unchanged. `buildRowPolicyFilterIfNeeded`, which decides the initiator-side
push-down, and `isRowPolicyPushedIntoRead`, which decides whether the executing
node plans the read again, both call this one function, so the receiver predicate
stays narrower than the initiator condition. Keeping only this branch's side of
the conflict would have dropped the alias policy from both.

Master also removed the `enable_analyzer = 0` arm of
`04652_nested_merge_prewhere_type_mismatch_2`; that removal is kept, alongside
this branch's rewrite of the comment above it.
Master turned `docs/reference/statements/create/row-policy.mdx` into a generated
region while this branch was open, so the two paragraphs rewritten here are now
generated output whose source of truth is the `CREATE ROW POLICY` registration in
`src/Parsers/Access/ParserCreateRowPolicyQuery.cpp`. Leaving the change in the
generated region would keep `system.documentation` publishing the obsolete claim
that an executing server never applies its own row policies, would be reverted by
the next regeneration, and fails the docs check without the
`pr-autogenerated-docs` label.

Carry the paragraphs into the registration and restore the generated region to
what regeneration produces. The nightly documentation autogeneration workflow
propagates the text into the page.

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

@groeneai

  1. [P1] A receiver’s READONLY filter can be skipped.
    readsServerState misses functions that read external state but return false from isDeterministicInScopeOfQuery. file is one such function.

    Put 7 in the initiator’s limit.txt and 3 in the receiver’s. Configure this additional filter in the receiver’s READONLY profile, and send the same entry from the initiator:

    x < (SELECT toUInt32(file(materialize('limit.txt'))))

    For rows x = 0…99999:

    Binary SQL shipping Plan shipping
    Previous head 507241e 3 3
    Current head 65fe843 3 7

    This reproduces through both Merge and a MergeTree with a row policy. Normalization removes the scalar result from the fingerprint, makes the different restrictions appear equivalent, and suppresses the receiver’s filter.

    Fix: preserve results that depend on receiver state. These determinism flags do not establish that an expression is independent of server state. Add this case to the receiver-profile tests.

  1. [P2] Scalar-subquery filters still run twice for additional valid forms.
    These filters must each select exactly one row from y = 0…99999:

    y = (SELECT randConstant() % 100000 FROM numbers(1))

    y = (SELECT randConstant(materialize(1)) % 100000)

    SQL shipping returned 1; plan shipping repeatedly returned 0, through both Merge and policy-bearing MergeTree.

    The server-state classification treats every table function—and the second form’s unfolded randConstant—as reading server state. It retains the independently generated scalar values, the hashes differ, and both filters execute.

    Fix: give an already shipped filter a stable identity that covers these forms, and add regression tests for them.

I would keep the analyzer-based row-policy replanning, but reconsider the filter-equivalence mechanism. Repeated evaluation and inference from function flags are producing errors in both directions: duplicating a filter and dropping a different receiver restriction.

…uting node

When the executing node plans a shipped read again (a `Merge` table, or a table with a row policy there), it applies
its own `additional_table_filters` entry. The plan also had the filter step that applied the sender's entry with the
values the sender evaluated, and the receiver skipped its own entry when it hashed equal to the sender's. The hash
could not tell values that depend on the node (`file`, a table, a dictionary, `getSetting`) from values that change
with each evaluation (`randConstant`, `rand`), so it dropped a receiver restriction in one direction
(`x < (SELECT toUInt32(file('limit.txt')))` in a READONLY profile: 7 rows instead of 3) and applied a filter twice in
the other (`x = (SELECT randConstant() % 100000 FROM numbers(1))`: 0 rows instead of 1).

Now `ReadFromTable` records where the sender's filter step is (its filter column and how many steps above the read).
The executing node always applies its own entry, replaces that step with one that keeps every row, and also applies
the sender's entry when it is not the same (compared as parsed ASTs). Each entry is evaluated once, with the state of
the executing node, as with the query text. The hash and the function-flag classification are removed.

The step is kept, and the receiver's entry is applied as well, when the sender does not record it (step version 0)
or when the sender's row policy step is under it, so that the policy still runs first.

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

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Changed in f2c2b1ed, following your last point: the filter-equivalence inference is gone.

ReadFromTable now records where the sender's additional_table_filters filter step is (its filter column and position). When the executing node plans the read again, it always applies its own entry, turns that step into one that keeps every row, and also applies the sender's entry if its parsed text differs. Each entry runs once, with the state of the executing node, as with the query text. additionalFilterHash and the function-flag classification are removed.

  1. x < (SELECT toUInt32(file(materialize('limit.txt')))), 7 on the initiator and 3 on the receiver, READONLY receiver entry plus the same entry from the query: 3 with both settings, through Merge and through a MergeTree with a policy (65fe843: 7). Added to test_serialized_query_plan_receiver_grants.
  2. y = (SELECT randConstant() % 100000 FROM numbers(1)) and y = (SELECT randConstant(materialize(1)) % 100000): 1 row with both settings on both routes (65fe843: 0). Added to 05482, with an arm under a PREWHERE of the query, which is a filter step between the read and the entry.

Remaining case: when the initiator's own row policy is a filter step under the entry (a policy on the Merge table itself on the initiator), the step stays so that the policy still runs first, and a nondeterministic entry is applied twice. An initiator that writes step version 0 behaves the same. Neither case skips a restriction.

Also checked on two servers: rand(), getSetting, a dictionary and a node-local table in the entry, an ALIAS column, a READONLY entry formatted differently from the query's, and a master initiator. PR stateless tests x3 and the integration test (20/20) pass.

groeneai and others added 4 commits November 5, 2026 21:33
…om the step that no longer filters

When the executing node applies the entry in the read it plans again, the filter step that applied the sender's entry
becomes a step that keeps every row. `removeUnusedActions` keeps an `ARRAY_JOIN` node even when no output needs it, so
that step still repeated the rows, and the entry `arrayJoin([1, 1])` gave 400 rows instead of 200 (both through a
table with a row policy and through `Merge`). The `ARRAY_JOIN` nodes the remaining outputs do not use are removed with
`removeNodes`, as `filterPushDown.cpp` does for a filter moved into a join.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t no longer filters

When the executing node turns the sender's filter step of an entry into a step that keeps every
row, the `IN` subquery sets of that filter stay in the `DelayedCreatingSetsStep` that `makeSets`
put at the root of the plan, so `addPlansForSets` still builds them, next to the set of the
receiver's own plan of the read. With a row policy on the table, a shipped
`y IN (SELECT number FROM numbers(10))` entry built two sets and read 30 rows instead of 20.

Drop such a set from that step once no column of the plan refers to it. A set the rest of the
plan still uses (the same subquery in `WHERE`) keeps another reference and is built as before.
The set plans are now resolved after the leaves, so a dropped one is not resolved either: with
an unqualified `IN (SELECT v FROM lim)` entry, the sender's set reads the table of its own
current database, which the executing node may not have (UNKNOWN_DATABASE), while the
executing node's own plan of the entry reads the table it resolves itself.
05480 checks that each secondary query builds one set, and the two-node integration test the
unqualified subquery.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 3 commits November 6, 2026 03:04
…ilter step was

The executing node applied the entries of a read it plans again inside that read, below the
filter steps the sender put between the read and the step of the entry, such as the `PREWHERE`
of the query, and the two do not commute in general: `PREWHERE rowNumberInAllBlocks() < 5` with
the entry `arrayJoin([1, 1])` counted 5 rows instead of 10, and `PREWHERE x < 5` with the entry
`throwIf(x >= 5) = 0` (`query_plan_enable_optimizations = 0`) threw on rows the `PREWHERE`
excludes. Both through a table with a row policy and through `Merge`; the second also on master
for `Merge`.

The planner now hands the filter it builds for the entries back to the caller, which puts it in
place of the sender's step, so it runs at the same position, once, with the values of the
executing node. If it needs a column that is not there (an entry of the executing node on a
column the query does not read), or a type differs, it runs on the read as before, and the
sender's step keeps every row. 05480 checks both orders through `Merge` and through a table with
a policy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…er a policy step and for its own columns

`f187b4ca` put the filter of the entries in place of the sender's step only when the columns it
reads were there, and never over a row policy step of the sender, so two cases still evaluated
an entry of the executing node elsewhere:
- It needed a column the sender's step does not get (an entry of the executing node on a column
  the query does not read). It then still ran on the read, below the `PREWHERE` of the query:
  a READONLY entry `y < 1000 AND arrayJoin([1, 1])` with `PREWHERE rowNumberInAllBlocks() < 5`
  counted 5 rows instead of 10, and `throwIf(y >= 5) = 0` with `PREWHERE x < 5` threw.
- Over the sender's policy step (a policy on a `Merge` table) the sender's step stayed and
  stood for an entry of the executing node with the same text, so an entry that depends on the
  executing node, such as `x < getSetting('max_threads')` with a READONLY `max_threads = 1`
  there, was evaluated with the sender's value: 2 rows instead of 1.

Such columns are now carried from the read to the sender's step, through the expression and
filter steps in between, and the filter replaces that step over a policy step too, where the
policy still runs first. Only if that fails (a type differs) does the filter run on the read as
before. 05480 checks the first case through `Merge`, through a table with a policy and over a
`Merge` policy, and the two-node integration test checks the second.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… sender has none

An `additional_table_filters` entry that only the executing node has (READONLY in its user's
profile, none on the initiator) was applied inside the read that node plans again, so below the
shipped PREWHERE, policy and ALIAS column steps. An entry that does not commute with them gave
other results than query text shipping: `y < 1000 AND arrayJoin([1, 1])` under
`PREWHERE rowNumberInAllBlocks() < 5` counted 5 rows instead of 10, and `toUInt32(s) < 5` under
`PREWHERE x < 5` threw CANNOT_PARSE_TEXT on rows the PREWHERE excludes. Same through `Merge`.

The sender now records in `ReadFromTable` step version 1 how many steps above the read belong to
it (ALIAS columns, PREWHERE, the policy, the custom key filter). With no step of the sender to
replace, the executing node inserts its filter after those steps, carrying the columns it needs
from the read as it already does in place of the sender's step. If the steps are not found or a
column type differs, the filter runs on the read as before. 05480 checks it through a table with
a policy, through `Merge` and over a `Merge` policy.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 186a82c

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 (arm_binary, ParallelReplicas, s3 storage, parallel) / 05401_quota_on_profile_events_query_result_cache flaky, not in this PR's diff: SelectQuery = 2/1 (QUOTA_EXCEEDED) on the cache hit, because a remote parallel replica's read of the populating query is charged to the test's quota user; 51 of 51 reruns passed; the same failure hit 13 other PRs and one master run today #129672 (mine, open)
Mergeable Check / PR praktika rollups of the row above #129672 (mine, open)

The FAIL rows of the four Bugfix validation jobs are this PR's new tests failing on master, as intended (all four jobs passed). CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261106-113004

@yariks5s

Copy link
Copy Markdown
Member

Change is too complex anyway. I'll try to rewrite it myself right now.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, I won't push to this branch meanwhile. The cases found during the review are covered by the tests here (04908-04910, 05480-05483 and the two-server test_serialized_query_plan_receiver_grants), if they help to check the rewrite.

@yariks5s

Copy link
Copy Markdown
Member

#131123

@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). I also added a small commit that switches the new code to the -WithMemoryTracking types where it meets the APIs changed there, so that it compiles. This update was made automatically.

@yariks5s

yariks5s commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

@nickitat re-implemented here: #131123

I feel like we don't need 2k lines to fix this bug. Let's close it. If you disagree we can discuss

@yariks5s yariks5s closed this Nov 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

No disagreement. I ran this PR's tests against #131123 (its diff applied on master a33e1c16): it fixes every case where master returns rows the policy excludes, and both parallel-replicas LOGICAL_ERRORs (Coordination mode mismatch, unknown stream), also with randomized settings. The other differences give the same result on master, so they are outside its scope: additional_table_filters on a Merge read or on the executing server, and a Merge table policy x IN (SELECT ...) that fails with NOT_FOUND_COLUMN_IN_BLOCK under serialize_query_plan = 1.

@yariks5s

Copy link
Copy Markdown
Member

@groeneai why then your Pull Request is much bigger than 131123? Please remember your mistakes (overcomplicating) from this PR, and let's never let it happen again

@groeneai

Copy link
Copy Markdown
Collaborator Author

Because I kept a premise the bug did not need: that the remote server applies its own row policy, as it does for a query shipped as text. For that, the PR planned the read again on the remote server, which brings in everything around the read (grants, additional_table_filters, max_columns_to_read, the PREWHERE order, applying each filter once). Each review finding then became one more special case with its own test: 580 source and about 1,460 test lines, against 70 and 71 in #131123. I had rejected what #131123 does, shipping the filter the initiator already built in a new ReadFromTable step version, instead of stating that semantic difference and letting you decide.

I've recorded the lesson: build the smallest change that fixes the reported bug, and when a fix keeps growing through review, step back instead of adding cases.

@yariks5s yariks5s reopened this Nov 20, 2026

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

re-implemented here: #131123

@yariks5s yariks5s closed this Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Row policy on the shard-local table is bypassed with serialize_query_plan = 1 on a non-local replica

5 participants