Skip to content

Do not analyze the shared row policy AST in place in Merge - #113563

Merged
KochetovNicolai merged 4 commits into
masterfrom
merge-row-policy-clone-ast
Aug 11, 2026
Merged

KochetovNicolai merged 4 commits into
masterfrom
merge-row-policy-clone-ast

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Related: #68569
Related: #68321
Related: #66467

Fixes a ThreadSanitizer data race found by the stress test:

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=66467&sha=b48cf3b340cdcc0e2275b3c1a5a4ba34034deb4d&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

The report is unrelated to that pull request (it is about the Chimp codec); the race is on master. There is no open issue for it. I could not find an existing fix - the closest one, #68321, fixed the same class of bug for the sampling key AST and closed #68569, where the same const_cast in ActionsVisitor was already questioned.

RowPolicyFilter::expression is the parsed policy condition owned by RowPolicyCache. It is parsed once, in RowPolicyCache::PolicyInfo::setPolicy, and then handed out as is: every query of every user reading the table gets the same AST nodes, and a policy defined on a whole database is shared by all of its tables. FiltersMixer combines the parsed conditions without copying them, so the pointer a query receives points straight into the cache.

ReadFromMerge::RowPolicyData passed that AST to TreeRewriter and ExpressionAnalyzer, both of which rewrite the AST they are given in place - they normalize identifiers, substitute the results of scalar subqueries for the subqueries themselves, and record ASTLiteral::unique_column_name. So reading a Merge table mutated the shared cache. This has two consequences.

A scalar subquery inside a policy is evaluated once and then frozen. This is deterministic and does not need any concurrency:

CREATE TABLE src (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO src SELECT number FROM numbers(10);
CREATE TABLE limits (v UInt64) ENGINE = MergeTree ORDER BY v;
INSERT INTO limits VALUES (3);
CREATE ROW POLICY p ON src USING x <= (SELECT max(v) FROM limits) TO ALL;
CREATE TABLE m (x UInt64) ENGINE = Merge(currentDatabase(), '^src$');

SELECT count() FROM m;      -- 4, correct
INSERT INTO limits VALUES (7);
SELECT count() FROM m;      -- 4, expected 8
SELECT count() FROM src;    -- 4, expected 8 - the direct read is affected too

The one SELECT through m replaced the subquery with the literal 3 in the cached policy AST, so the policy keeps that value for the rest of the server's lifetime, for every user and for direct reads of the table as well. Because the frozen value can be either more or less permissive than the current one, a policy can end up showing rows it is supposed to hide.

Concurrent queries race on the shared AST. ThreadSanitizer reported the write to ASTLiteral::unique_column_name from ActionsMatcher::visit, reached through ReadFromMerge::RowPolicyData, against a concurrent ASTLiteral::clone performed by buildQueryTree for another table protected by the same policy.

The fix is to analyze a clone. generateFilterActions in InterpreterSelectQuery already clones the policy expression for the same reason, as does MergeTreeDataSelectExecutor::getSampling for the sampling key, and ASTLiteral::clone resets unique_column_name precisely because it is per-analysis scratch state. ReadFromMerge::RowPolicyData was the last consumer of a row policy filter that rewrote the cached AST: the other ones either clone (the analyzer, through buildQueryTree), only visit it with a const visitor (StorageMergeTreeTextIndex), or only test isAlwaysTrue. After this change nothing writes to the shared AST - the only remaining mutable member of IAST is the atomic reference counter.

The new test 04812_merge_row_policy_shared_ast reproduces the frozen subquery: it prints 4 4 4 4 before the change and 4 4 8 8 after.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a row policy containing a scalar subquery being evaluated only once and then reused forever after the table had been read through a Merge table. The parsed policy condition is cached and shared by all queries, and reading it through Merge rewrote the cached expression in place, which also caused a data race between concurrent queries using the same policy.

Version info

  • Backported to: 26.7.4.22, 26.6.3.43, 26.5.7.39, 26.3.18.20, 25.8.30.17

`RowPolicyFilter::expression` is the parsed policy condition owned by
`RowPolicyCache`. It is parsed once, in
`RowPolicyCache::PolicyInfo::setPolicy`, and then handed out as is: every query
of every user reading the table gets the same AST nodes, and a policy defined on
a whole database is shared by all of its tables. `FiltersMixer` combines the
parsed conditions without copying them, so the pointer a query receives points
straight into the cache.

`ReadFromMerge::RowPolicyData` passed that AST to `TreeRewriter` and
`ExpressionAnalyzer`, both of which rewrite the AST they are given in place:
they normalize identifiers, substitute the results of scalar subqueries for the
subqueries themselves, and record `ASTLiteral::unique_column_name`. So reading a
`Merge` table mutated the cache. Two consequences:

- A scalar subquery in a policy was evaluated once and then frozen. With
  `CREATE ROW POLICY p ON src USING x <= (SELECT max(v) FROM limits)`, one
  `SELECT` through a `Merge` table over `src` replaced the subquery with its
  value in the cached AST, and every later query - including direct reads of
  `src` by other users - kept using that value for the rest of the server's
  lifetime.

- Concurrent queries raced on the shared AST. ThreadSanitizer reported the
  write to `ASTLiteral::unique_column_name` from `ActionsMatcher::visit`
  against a concurrent `ASTLiteral::clone` performed by `buildQueryTree` for
  another table protected by the same policy:
  https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=66467&sha=b48cf3b340cdcc0e2275b3c1a5a4ba34034deb4d&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
  #66467

Analyze a clone instead. `generateFilterActions` in `InterpreterSelectQuery`
already clones the policy expression for the same reason, as does
`MergeTreeDataSelectExecutor::getSampling` for the sampling key, and
`ASTLiteral::clone` resets `unique_column_name` precisely because it is
per-analysis scratch state. This was the last consumer of a row policy filter
that rewrote the cached AST: the other ones either clone (the analyzer, through
`buildQueryTree`), only visit it with a const visitor
(`StorageMergeTreeTextIndex`), or only test `isAlwaysTrue`.

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

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c810f42]

Summary: ✅


AI Review

Summary

This PR fixes a real Merge row-policy bug by cloning the cached RowPolicyFilter::expression before TreeRewriter and ExpressionAnalyzer can rewrite it in ReadFromMerge::RowPolicyData, and the new shell test covers the user-visible regression with a scalar subquery while qualifying the helper table for parallel-replicas execution. I did not find an actionable correctness, concurrency, or metadata issue in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit c810f42 - the build was skipped, reused from cache, or predates profile upload.

The test 04812_merge_row_policy_shared_ast failed in the ParallelReplicas
run of the stateless tests: the policy condition is analyzed anew on the
remote side of a parallel-replicas query, where the session default
database is not the test database, so the unqualified table of the scalar
subquery did not resolve (`Unknown table expression identifier
't_04812_limit'`, UNKNOWN_TABLE).

Convert the test to a shell test to interpolate the database name into
the `CREATE ROW POLICY` statement, because a parameterized identifier
inside the policy condition would be stored unsubstituted.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113563&sha=54e05810fa932e7718e3ad266795423362641c66&name_0=PR&name_1=Stateless%20tests%20(amd_llvm_coverage,%20ParallelReplicas,%20s3%20storage,%20parallel)
PR: #113563

Co-Authored-By: Claude Fable 5 <[email protected]>
@KochetovNicolai KochetovNicolai self-assigned this Aug 11, 2026
@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Aug 11, 2026
Merged via the queue into master with commit 767a27d Aug 11, 2026
181 checks passed
@KochetovNicolai
KochetovNicolai deleted the merge-row-policy-clone-ast branch August 11, 2026 11:33
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 11, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 11, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 11, 2026
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
Backport #113563 to 26.5: Do not analyze the shared row policy AST in place in `Merge`
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
Backport #113563 to 26.3: Do not analyze the shared row policy AST in place in `Merge`
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 12, 2026
Backport #113563 to 26.7: Do not analyze the shared row policy AST in place in `Merge`
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
Backport #113563 to 25.8: Do not analyze the shared row policy AST in place in `Merge`
alexey-milovidov added a commit that referenced this pull request Aug 16, 2026
… `Merge`

Backport #113563 to 26.6: Do not analyze the shared row policy AST in place in `Merge`
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
OTHER: row policy with a scalar subquery, read through Merge -> wrong (stale) plus race.
Effect in the production build a394e92: its upstream test(s) 04812_merge_row_policy_shared_ast fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04812_merge_row_policy_shared_ast.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Data race in ActionsVisitor (on unique_column_name) by 00712_prewhere_with_sampling.sql

5 participants