Repository navigation
Conversation
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]>
Internal second-model review (7 rounds, adjudicated)Independent cold review plus a second-model gate on every round, adjudicated against the recorded
The one open item. The flush race above is a test-determinism defect in the two new route Session id: cron:clickhouse-review-slot-9:20260815-135500 |
Pre-PR validation gate
|
|
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.
|
Pushed The style check was right: the new route oracle read Two fixes came out of reviewing that push, both worth flagging:
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes90 object files changed (+407.37 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units644 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. |
CI finish ledger - 31d3eb8CI is fully finished on this head: 177 check runs, 161 success, 16 skipped, 0 failed checks. The CIDB test-level enumeration reports four
No check on this head needs an external owner. Session id: cron:our-pr-ci-monitor:20260816-113000 |
CI finish ledger - 31d3eb8Correcting my previous ledger comment on this head: I had the direction of the CI is fully finished on this head: 177 check runs, 161 success, 16 skipped, 0 failed checks.
That split is corroborated by the job's own pre-inversion summary, So three of five regression tests reproduce the bug on master, on both arches, and both per-arch
No other check on this head needs an owner, and no external owner is required. Session id: cron:our-pr-ci-monitor:20260816-113000 |
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
left a comment
There was a problem hiding this comment.
-
[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.
-
[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]>
|
Changed in f2c2b1ed, following your last point: the filter-equivalence inference is gone.
Remaining case: when the initiator's own row policy is a filter step under the entry (a policy on the Also checked on two servers: |
…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]>
…filters` step of the sender already applies
…e` table with a row policy
…prewhere_read_steps`
…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]>
…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]>
CI finish ledger - 186a82cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The Session id: cron:our-pr-ci-monitor:20261106-113004 |
|
Change is too complex anyway. I'll try to rewrite it myself right now. |
|
Understood, I won't push to this branch meanwhile. The cases found during the review are covered by the tests here ( |
# Conflicts: # src/Processors/QueryPlan/resolveStorages.cpp
…:removeNodes` after ClickHouse#129617 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01DFFRj3kqWUsA1C3A8DapeT
|
🕵 Merged |
|
No disagreement. I ran this PR's tests against #131123 (its diff applied on master |
|
@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 |
|
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, 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. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a
SELECTrow 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, withprocess_query_plan_packetenabled there). Reads through aDistributedtable withprefer_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 < 5on a 10-rowMergeTreetable,SELECT count()through aDistributedtable withserialize_query_plan = 1returns 10, not 5. With parallel replicas, a policy fixing the first sorting key column can fail the query with aLOGICAL_ERROR:Coordination mode mismatch ...: got Default, expected WithOrder(job) orGot 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 bareReadFromTableStep.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 forMerge, and applies its own policy once. A read planned again does not reapply a policy a step applies; its ownadditional_table_filtersentry, evaluated here, and the sender's if different, replace the sender's entry step, or follow the read's own steps (positions recorded). For aMergeor remote table the node checks its own grants andmax_columns_to_readon the selected columns the step carries and its grants on the shipped filter. These ride inReadFromTablestep version 1, written only from plan version 21, so older peers get the old bytes.SelectQueryOptions::subquery()also resetsignore_rename_columns, which fixes aMergetable with anIN (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
serialize_query_plan = 1y < 5,MergeTreeon 26.9Log,MATERIALIZEDcolumn)Memory, nondeterministic policyMergetable, policyx IN (SELECT ...)NOT_FOUND_COLUMN_IN_BLOCK[0,3,6,9]Mergetable,additional_table_filtersx = randConstant() % 100000, alsox = (SELECT randConstant() % 100000 FROM numbers(1))Mergetable,PREWHERE x < 5, entrythrowIf(x >= 5) = 0ORDER BY (a, b), policya = 'nomatch',ORDER BY bLOGICAL_ERROR, mode mismatcha = 'engineering', remote replica's request firstLOGICAL_ERROR, unknown streamTwo servers,
Mergetable (test_serialized_query_plan_receiver_grants): a receiver without the grant on a selected oradditional_table_filterscolumn givesACCESS_DENIEDwith both settings, as on master; a user without a grant on the policy column still reads; the receiver's own READONLYadditional_table_filters(10, not 45) andmax_columns_to_read(TOO_MANY_COLUMNS, not 90) hold with both settings, and so does its READONLYmax_threads = 1in a shared entryx < getSetting('max_threads'), also under aMergepolicy (1, not 2), and a shared entry whose scalar subquery reads a table, a dictionary or afilethat differs between the nodes (3, not 7), and an entryy IN (SELECT v FROM lim)reads thelimof the receiver's own current database (2 rows, notUNKNOWN_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 50with randomized settings: 300/300.Workflow [PR]
Sync PR [sync-upstream/pr/114955]