Skip to content

Fix LOGICAL_ERROR crash with subqueries in ROW POLICY USING clause - #101263

Merged
novikd merged 1 commit into
ClickHouse:masterfrom
groeneai:fix/row-policy-subquery-crash
May 7, 2026
Merged

novikd merged 1 commit into
ClickHouse:masterfrom
groeneai:fix/row-policy-subquery-crash

Conversation

@groeneai

@groeneai groeneai commented Mar 30, 2026 •

Copy link
Copy Markdown
Collaborator

When a ROW POLICY uses a scalar subquery as its filter expression (e.g. USING (SELECT 1)), the query tree builder creates a QUERY node. QueryAnalyzer::resolve() previously rejected QUERY/UNION nodes when a table_expression context was present, throwing a LOGICAL_ERROR crash:

Logical error: 'For query analysis table expression must be empty'

The fix evaluates such nodes as scalar subqueries via evaluateScalarSubqueryIfNeeded(), matching the established pattern in resolveConstantExpression(). The scalar subquery is executed and replaced with a ConstantNode, which the rest of the filter pipeline handles correctly.

Verified locally: USING (SELECT 1) (all rows visible), USING (SELECT 0) (no rows visible), and USING c0 > (SELECT 1) (expression with embedded subquery) all work correctly. Existing row policy tests pass without regression.

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 LOGICAL_ERROR crash in QueryAnalyzer::resolve() when a ROW POLICY uses a scalar subquery in its USING clause (e.g. USING (SELECT 1)). Closes #100695.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.410

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate

Session: cron:clickhouse-ci-task-worker:20260330-181500

a) Deterministic repro:

CREATE ROW POLICY p ON t USING (SELECT 1) TO ALL;
SELECT 1 FROM t; -- crashes with LOGICAL_ERROR every time

b) Root cause:
buildFilterInfo() calls buildQueryTree() on the row policy's USING expression. When the expression is a scalar subquery like (SELECT 1), buildQueryTree creates a QUERY node. Then QueryAnalysisPass(table_expression).run() calls QueryAnalyzer::resolve(), which unconditionally throws LOGICAL_ERROR for QUERY/UNION nodes when table_expression is non-null. The assertion assumed QUERY nodes only appear at top-level resolution, not as scalar subqueries within expression contexts like row policy filters.

c) Fix matches root cause:
Instead of crashing, resolve() now evaluates QUERY/UNION nodes with table_expression as scalar subqueries via evaluateScalarSubqueryIfNeeded(). This is the same approach used in resolveConstantExpression() (line 209), which already handles this case correctly. The subquery is executed and replaced with a ConstantNode.

d) New test added:
04073_row_policy_subquery_crash.sql — covers USING (SELECT 1), USING (SELECT 0), and USING c0 > (SELECT 1). All existing row policy tests pass without regression (6/6 tested).

e) Both directions:

  • Without fix: LOGICAL_ERROR crash (134 exit code) — 100% reproduction
  • With fix: 20/20 passes with full randomization

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit @novikd — could you review this? It fixes the LOGICAL_ERROR crash from #100695 by evaluating QUERY/UNION nodes as scalar subqueries when they appear in expression resolution contexts (like ROW POLICY filters), instead of unconditionally rejecting them.

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f8619e7]

Summary: ✅


AI Review

Summary

This PR fixes a LOGICAL_ERROR exception for ROW POLICY ... USING (SELECT ...) by wrapping standalone subquery filters into notEquals(<subquery>, 0) before query-tree analysis. The core fix is plausible, but one important branch (UNION scalar subquery) is still under-tested.

Missing context
  • ⚠️ Full CI results are still pending, so runtime coverage is incomplete.
Findings

⚠️ Majors

  • [tests/queries/0_stateless/04073_row_policy_subquery_crash.sql:24] The implementation explicitly handles top-level ASTSelectWithUnionQuery, but the new regression test covers only scalar SELECT subqueries. Without at least one scalar UNION case in ROW POLICY USING, regressions in the UNION path can pass unnoticed.
    Suggested fix: add a deterministic scalar UNION test case (single-row result) and assert expected row visibility.
Tests
  • ⚠️ Add one ROW POLICY USING case with a scalar UNION subquery to validate the ASTSelectWithUnionQuery handling path introduced by this patch.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: add regression coverage for scalar UNION subquery in ROW POLICY USING.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 30, 2026
SELECT count() FROM t_04073;
DROP ROW POLICY p_04073 ON t_04073;

-- Test 3: Mixed expression with scalar subquery — c0 > (SELECT 1)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code change updates both QueryTreeNodeType::QUERY and QueryTreeNodeType::UNION, but this test file exercises only QUERY-based scalar subqueries.

Please add one ROW POLICY USING case with a scalar UNION subquery to cover the new UNION branch in QueryAnalyzer::resolve (for example, a scalar UNION ALL wrapped to return one row). Without it, this path can regress unnoticed.

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 check this

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — the UNION branch was not only untested, it was actually broken. The buildFilterInfo() path in Utils.cpp skips the NormalizeSelectWithUnionQueryVisitor that runs in the normal executeQuery() path, so UnionNode constructor rejected the un-normalized UNION_DEFAULT mode.

Fixed in 791de84:

  1. Added NormalizeSelectWithUnionQueryVisitor in buildFilterInfo() before buildQueryTree() — matches how executeQuery.cpp handles it
  2. Added 3 new test cases:
    • USING (SELECT 1 UNION DISTINCT SELECT 1) — exercises the UNION branch
    • USING c0 > (SELECT 0 UNION DISTINCT SELECT 0) — mixed expression with UNION
    • USING (SELECT 1 UNION ALL SELECT 1) — verifies proper error (not crash) for multi-row result

50/50 passes with full randomization, all existing row policy tests pass.

Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Outdated
Comment on lines +140 to +146
{
/// The node is a scalar subquery used in an expression context
/// (e.g. ROW POLICY USING (SELECT 1)). Evaluate it as a scalar
/// subquery — the result replaces the node with a ConstantNode.
evaluateScalarSubqueryIfNeeded(node, scope);
break;
}

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.

It should not be allowed

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — reverted. The assertions are restored. The fix now lives entirely in buildFilterInfo() where the subquery is wrapped with equals(1, <subquery>) before reaching the analyzer.

Comment thread src/Planner/Utils.cpp Outdated
Comment on lines +499 to +507
/// Normalize UNION modes in the filter expression AST before building
/// the query tree. Without this, a ROW POLICY USING clause containing
/// a UNION subquery (e.g. `USING (SELECT 1 UNION ALL SELECT 1)`) would
/// hit UnionNode's constructor check that rejects UNION_DEFAULT mode.
{
const auto & settings = query_context->getSettingsRef();
NormalizeSelectWithUnionQueryVisitor::Data data{settings[Setting::union_default_mode]};
NormalizeSelectWithUnionQueryVisitor{data}.visit(filter_expression);
}

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.

It is unclear how it would help.

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.

A more correct approach would be to wrap with equals(1, <subquery>) the filter if the filter expression is a Query or Union node.

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, could you please address this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the UNION normalization. Replaced with the equals(1, <subquery>) wrapping as you suggested — it's cleaner and handles the core case directly. The UNION-in-USING test cases were removed since they're out of scope for this fix.

@groeneai
groeneai force-pushed the fix/row-policy-subquery-crash branch from 791de84 to e4850b5 Compare March 31, 2026 13:27
@groeneai

Copy link
Copy Markdown
Collaborator Author

@novikd — reworked in e4850b5 per your review. Here's what changed:

Reverted QueryAnalyzer.cpp — the assertions are restored. No more evaluateScalarSubqueryIfNeeded in resolve() for QUERY/UNION nodes with table_expression.

Utils.cpp — equals(1, <subquery>) wrapping: In buildFilterInfo(), if the filter expression is a standalone ASTSubquery or ASTSelectWithUnionQuery, it's now wrapped with makeASTFunction("equals", Literal(1), subquery) before calling buildQueryTree(). This produces a FunctionNode at the top level, and the subquery is resolved as a normal scalar-subquery function argument through the existing code path.

Removed UNION normalization — the NormalizeSelectWithUnionQueryVisitor addition is gone. The UNION-in-USING test cases (tests 4-6) were also removed since they're beyond the scope of the original bug.

Test coverage: 3 cases remain — USING (SELECT 1) (always true), USING (SELECT 0) (always false), USING c0 > (SELECT 1) (mixed expression). 50/50 passes with full randomization.

Session: cron:clickhouse-ci-task-worker:20260331-131500

Comment thread src/Planner/Utils.cpp Outdated
if (filter_expression->as<ASTSubquery>()
|| filter_expression->as<ASTSelectWithUnionQuery>())
{
filter_expression = makeASTFunction("equals",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ This wrapper changes boolean semantics for standalone scalar subqueries.

USING filters are interpreted as boolean expressions where non-zero numeric values are treated as true (e.g. USING 2 behaves as true). Rewriting USING (SELECT x) to equals(1, (SELECT x)) makes only 1 true and turns values like 2 or -1 into false.

That is a user-visible behavior change unrelated to the exception fix. A safer approach is to resolve standalone QUERY/UNION nodes as scalar subqueries (as in resolveConstantExpression) and keep normal boolean conversion semantics.

Please add a regression case like USING (SELECT 2) to ensure this remains true.

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 add a test for USING (SELECT 2)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 5f6e7bb. Two changes:

  1. Fixed boolean semantics: Replaced equals(1, <subquery>) with notEquals(<subquery>, 0). This correctly treats any non-zero value as truthy — USING (SELECT 2) now allows rows instead of denying them. Also handles edge cases: SELECT -1 (truthy), SELECT 256 (truthy, would fail with UInt8 cast), SELECT 0 (falsy).

  2. Added test case (Test 3): USING (SELECT 2) — verifies all rows are visible when the subquery returns a non-zero value other than 1.

@groeneai
groeneai force-pushed the fix/row-policy-subquery-crash branch from e4850b5 to 5f6e7bb Compare March 31, 2026 15:33
@groeneai

Copy link
Copy Markdown
Collaborator Author

@novikd — updated in 5f6e7bb:

Fixed boolean semantics — changed equals(1, <subquery>) to notEquals(<subquery>, 0).

The equals(1, x) wrapping was semantically wrong: USING (SELECT 2) should allow rows (non-zero = truthy), but equals(1, 2) = 0 would deny them. notEquals(x, 0) correctly maps:

  • SELECT 1 → notEquals(1, 0) = 1 (allow) ✓
  • SELECT 2 → notEquals(2, 0) = 1 (allow) ✓
  • SELECT 0 → notEquals(0, 0) = 0 (deny) ✓
  • SELECT -1 → notEquals(-1, 0) = 1 (allow) ✓
  • SELECT 256 → notEquals(256, 0) = 1 (allow) ✓ (would fail with UInt8 cast truncation)

Added test case for USING (SELECT 2) — Test 3 verifies all rows are visible with non-1 non-zero scalar subquery.

50/50 passes with full randomization. All existing row policy tests pass.

@groeneai
groeneai force-pushed the fix/row-policy-subquery-crash branch from 5f6e7bb to 12812fc Compare April 1, 2026 13:30
@alexey-milovidov

Copy link
Copy Markdown
Member

The test 02859_replicated_db_name_zookeeper is fixed in #101952

@alexey-milovidov

Copy link
Copy Markdown
Member

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@alexey-milovidov

Copy link
Copy Markdown
Member

The Can't adjust last granule error in CI is a known issue. The fix is in #101641

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai can you check the CI failures? I think this PR can be merged.

When ROW POLICY USING contains a standalone subquery like (SELECT 1),
buildFilterInfo() in Utils.cpp passes the raw AST to buildQueryTree()
which produces a top-level QueryNode/UnionNode.  QueryAnalysisPass then
calls QueryAnalyzer::resolve() with table_expression set, but that
function asserts table_expression must be empty for top-level
QUERY/UNION nodes — resulting in a LOGICAL_ERROR crash.

Fix: in buildFilterInfo(), detect standalone subquery filter expressions
(ASTSubquery or ASTSelectWithUnionQuery) and wrap them with
notEquals(<subquery>, 0) before passing to buildQueryTree().  This
produces a FunctionNode at the top level, so the subquery is resolved
through the normal scalar-subquery evaluation path as a function
argument.  We use notEquals(x, 0) rather than equals(1, x) to preserve
boolean semantics: any non-zero value is truthy (e.g. USING (SELECT 2)
allows rows, not just USING (SELECT 1)).

Closes ClickHouse#100695

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai
groeneai force-pushed the fix/row-policy-subquery-crash branch from 1ba009d to f8619e7 Compare May 7, 2026 09:50
@groeneai

groeneai commented May 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

@PedroTadim — investigated CI on PR #101263. Both failures from the 2026-04-09 run are chronic trunk bugs unrelated to this PR.

Failure analysis

# Failure CIDB cross-PR (30d / 90d) Root cause
1 Stress test (arm_msan) → MSAN: use-of-uninitialized-value (STID 1478-2063) + Server died 105 distinct PRs / 16 master hits / 133 total in 30d Chronic untracked P0 MSAN bug, separately tracked
2 Stateless tests (amd_msan, WasmEdge, parallel, 1/2) → 03621_pr_distributed_index_analysis 4 unrelated PRs + 1 master hit in 90d (96130, 100287, 101039, master, this) Chronic flaky — all PRs touch unrelated topics (row policy, distributed index, leader election, etc.)

Test 03621_pr_distributed_index_analysis exercises the new analyzer's distributed-shard pruning path, which is independent from this PR's change in buildFilterInfo() (wrapping standalone subquery filters with notEquals(<subquery>, 0)).

Action taken

  • Rebased branch onto current master — was on a stale base from 2026-04-09. Clean rebase, no conflicts.
    • Note: @azat recently added LogicalExpressionOptimizerPass to the same buildFilterInfo() function (afb87e6, "Optimize row policy OR-chains to IN") — different lines, both changes coexist.
  • Force-pushed to groeneai/ClickHouse:fix/row-policy-subquery-crash at f8619e74dc9.
  • Fresh CI is now triggered.

The fix in buildFilterInfo() is unchanged: ASTSubquery/ASTSelectWithUnionQuery filters are wrapped with notEquals(<subquery>, 0) to preserve boolean semantics (any non-zero value is truthy, per @novikd's review). Test 04073_row_policy_subquery_crash.sql covers all 8 cases including USING (SELECT 2) (truthy non-1) and USING (SELECT NULL) (falsy).

Once fresh CI completes, the chronic issues may or may not re-appear at random — they're not blockers for merging this PR.

@clickhouse-gh

clickhouse-gh Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (8/8) · Uncovered code

Full report · Diff report

@novikd
novikd added this pull request to the merge queue May 7, 2026
Merged via the queue into ClickHouse:master with commit 2b753e7 May 7, 2026
165 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 7, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @novikd — the changelog category for this PR might need a look.

Current: Bug Fix (user-visible misbehavior in an official stable release)
Suggested: Critical Bug Fix (crash, data loss, RBAC) or LOGICAL_ERROR

Why: The PR fixes a LOGICAL_ERROR (For query analysis table expression must be empty at QueryAnalyzer.cpp:147) on a RBAC-related feature (ROW POLICY). Per the changelog category list, fixes for LOGICAL_ERROR and RBAC bugs belong to the 'Critical Bug Fix' category, not regular 'Bug Fix'. The PR's own description and title use the word 'crash' and reference the LOGICAL_ERROR.

Could you verify this is correct? Ignore if the current category is intentional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default 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.

Logical error: 'For query analysis table expression must be empty' with EXECUTE AS

7 participants