Skip to content

Fix exception when building set from correlated subquery with PLACEHOLDER actions - #100398

Merged
alexey-milovidov merged 44 commits into
masterfrom
fix-placeholder-action-in-correlated-subquery
May 9, 2026
Merged

alexey-milovidov merged 44 commits into
masterfrom
fix-placeholder-action-in-correlated-subquery

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 22, 2026 •

Copy link
Copy Markdown
Member

The AST fuzzer produces queries where a correlated subquery (containing PLACEHOLDER action nodes in its ActionsDAG) ends up as an IN clause argument. When KeyCondition::tryPrepareSetIndexForIn calls FutureSetFromSubquery::buildOrderedSetInplace, it attempts to build and execute the query pipeline for the subquery. Since PLACEHOLDER nodes cannot be executed standalone (they require decorrelation first), this causes a "Trying to execute PLACEHOLDER action" logical error.

The fix adds a check in both buildSetInplace and buildOrderedSetInplace to detect correlated expressions in the source plan before attempting to build it. If the plan contains PLACEHOLDER nodes, we skip building the set inplace — the correlated subquery will be decorrelated and executed as part of the outer query instead.

Also changes the default IQueryPlanStep::hasCorrelatedExpressions to return false instead of throwing NOT_IMPLEMENTED, since steps without ActionsDAG cannot contain PLACEHOLDER nodes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100348&sha=f75d6efc8e1be0e658cfc4841e81729659ef3010&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29
#100348

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 "Trying to execute PLACEHOLDER action" exception that could occur during stress testing with the AST fuzzer when a correlated subquery appeared in an IN clause.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.479

…LDER actions

The AST fuzzer can produce queries where a correlated subquery (containing
`PLACEHOLDER` action nodes in its `ActionsDAG`) ends up as an IN clause
argument. When `KeyCondition::tryPrepareSetIndexForIn` calls
`FutureSetFromSubquery::buildOrderedSetInplace`, it attempts to build and
execute the query pipeline for the subquery. Since PLACEHOLDER nodes cannot
be executed standalone (they require decorrelation first), this causes a
"Trying to execute PLACEHOLDER action" logical error.

The fix adds a check in both `buildSetInplace` and `buildOrderedSetInplace`
to detect correlated expressions in the source plan before attempting to
build it. If the plan contains PLACEHOLDER nodes, we skip building the set
inplace — the correlated subquery will be decorrelated and executed as part
of the outer query instead.

Also changes the default `IQueryPlanStep::hasCorrelatedExpressions` to
return `false` instead of throwing `NOT_IMPLEMENTED`, since steps without
`ActionsDAG` cannot contain PLACEHOLDER nodes.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100348&sha=f75d6efc8e1be0e658cfc4841e81729659ef3010&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f47510b]

Summary: ✅


AI Review

Summary

This PR fixes a real planner/runtime exception path for correlated subqueries in IN set-building by skipping standalone set construction when correlated PLACEHOLDER expressions are present, and extends hasCorrelatedExpressions coverage for affected plan steps. Based on the current diff and resolved review history, the fix is coherent and the added regression test now checks the key failure modes without overfitting to one exact error string.

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: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 22, 2026
Comment thread src/Interpreters/PreparedSets.cpp Resolved
Comment thread src/Interpreters/PreparedSets.cpp Resolved
alexey-milovidov and others added 4 commits March 24, 2026 14:27
…gression test

Address review feedback on #100398:

1. `TotalsHavingStep` holds an `std::optional<ActionsDAG>` but did not
   override `hasCorrelatedExpressions`, so with the base class returning
   `false` it would silently miss `PLACEHOLDER` nodes in its expression
   DAG. Add the override to check `actions_dag->hasCorrelatedColumns`.

2. Add a regression test with a correlated subquery in an `IN` clause
   that previously triggered "Trying to execute PLACEHOLDER action".

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Correlated subqueries in IN clauses are not yet supported. The fix
prevents the `PLACEHOLDER` crash, but the query correctly throws
`NOT_IMPLEMENTED` instead. Update the test to expect this error.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The test expects all queries to either produce no output or fail with
`NOT_IMPLEMENTED`, so the reference file should be empty.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 6 commits March 30, 2026 05:41
`ObjectFilterStep` holds an `ActionsDAG` member but was missing
a `hasCorrelatedExpressions` override, falling through to the base
class default of `false`. This meant correlated PLACEHOLDER nodes
in an object filter could bypass the pre-check in `PreparedSets`
and still trigger the "Trying to execute PLACEHOLDER action" exception.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous test used a correlated subquery in an IN clause, but the
analyzer catches this pattern early with a NOT_IMPLEMENTED error
("Correlated subqueries are not supported as IN function arguments yet").
This produces the same error on both master and the fix, so bugfix
validation failed since it couldn't demonstrate a behavioral difference.

The new test uses a correlated scalar subquery with ORDER BY in the
subquery. On master, `buildCorrelatedPlanStepMap` calls
`hasCorrelatedExpressions` on every plan step including `SortingStep`,
which uses the base implementation that throws NOT_IMPLEMENTED. After
the fix, the default `IQueryPlanStep::hasCorrelatedExpressions` returns
false, allowing decorrelation to proceed and the query to succeed.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The `.sql` test with `{ serverError NOT_IMPLEMENTED }` passes on both
master and fix (both produce error code 48), so bugfix validation fails.

Convert to a `.sh` test that checks the error MESSAGE:
- Master: "Cannot check Sorting plan step for correlated expressions"
  (from `hasCorrelatedExpressions` throwing NOT_IMPLEMENTED)
- Fix: "Cannot decorrelate query, because 'Sorting' step is not supported"
  (from the actual decorrelation code, reached after `hasCorrelatedExpressions`
  returns false instead of throwing)

The test checks for the post-fix message, so it fails on master (where
`buildCorrelatedPlanStepMap` throws before reaching decorrelation) and
passes on the fix.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

alexey-milovidov and others added 7 commits April 10, 2026 05:28
…th `PLACEHOLDER` actions

Add a second test case that exercises the `buildSetInplace` / `buildOrderedSetInplace`
guard directly: a correlated subquery in an IN clause creates a plan with PLACEHOLDER
nodes. The test verifies this no longer throws "Trying to execute PLACEHOLDER action".

Also rewords the test comment to remove the incorrect claim that the IN-clause path
"cannot be tested from SQL".

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The PR changed the default `IQueryPlanStep::hasCorrelatedExpressions` to
return `false` instead of throwing `NOT_IMPLEMENTED`. Reviewers pointed
out this weakens the guard: any future subclass that stores an
`ActionsDAG` but forgets to override this method would silently bypass
the check in `FutureSetFromSubquery::buildSetInplace` and
`buildOrderedSetInplace`, reproducing the original "Trying to execute
PLACEHOLDER action" exception.

Add a comment at the base declaration making the contract explicit:
every step carrying an `ActionsDAG` (or any expression container that
may hold `PLACEHOLDER` nodes) MUST override this method.

All currently-existing steps with such members already have overrides
(`FilterStep`, `ExpressionStep`, `ObjectFilterStep`, `TotalsHavingStep`,
`JoinStepLogical`, `SourceStepWithFilterBase`).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov and others added 8 commits May 2, 2026 22:56
Address review on `04056_correlated_subquery_placeholder_action.sh`: the
success branch of test 2 used to accept any `RC=0` output, so a semantic
regression that returned wrong rows would still pass. For this fixture
no `t1.b` matches any `t2.y`, so the result must be empty; assert that
and only allow `NOT_IMPLEMENTED` / `Cannot decorrelate` as the
non-success outcome.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 9, 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.50% -0.10%

Changed lines: 59.09% (26/44) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The fix is perfectly ok.

@alexey-milovidov alexey-milovidov self-assigned this May 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 9, 2026
Merged via the queue into master with commit 9250c75 May 9, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-placeholder-action-in-correlated-subquery branch May 9, 2026 21:49
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 9, 2026
@antaljanosbenjamin

Copy link
Copy Markdown
Member

This PR introduced a regression in 26.5 (still present on current master): queries over a Merge table with a plain IN (subquery) in the WHERE clause lose primary-key/partition pruning on the subquery side. With force_primary_key/force_index_by_date enabled the query fails outright with INDEX_NOT_USED; without those settings the subquery silently full-scans the Merge children.

Repro (works on 26.4.5, fails since 26.5.1):

CREATE TABLE default.t (k String, d Date, v Array(String))
ENGINE = MergeTree PARTITION BY d ORDER BY (k, d);
INSERT INTO default.t VALUES ('a','2026-10-16',['x']),('b','2026-10-16',['y']);
CREATE TABLE default.m (k String, d Date, v Array(String))
ENGINE = Merge('default', '^t$');

SELECT count() FROM default.m
WHERE k = 'a' AND d = '2026-10-16'
  AND v IN (SELECT v FROM default.m WHERE k = 'a' AND d = '2026-10-16')
SETTINGS force_primary_key = 1, force_index_by_date = 1;

Code: 277. DB::Exception: Primary key (k, d) is not used and setting 'force_primary_key' is set: Child table: default.t. (INDEX_NOT_USED)

bool IQueryPlanStep::hasCorrelatedExpressions() const
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Cannot check {} plan step for correlated expressions", getName());
return false;

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.

@alexey-milovidov, this is totally wrong. I think this PR should be reverted.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 22, 2026
…xpressions

Instead of special-casing `ReadFromMerge` in `hasCorrelatedExpressions`, stop
the walk from asking steps for `getChildPlans` at all. That descent (added in
ClickHouse#100398) is what made a `ReadFromMerge` create its child plans before the
subquery's filters were pushed down into it; the children are created only
once, so they kept no primary key or partition condition.

The walk now looks at plan nodes only, the same as the decorrelation itself
(`buildCorrelatedPlanStepMap`), so the check knows nothing about `Merge`.
Correlated subqueries over a `Merge` table behave the same as before, and the
analyzer still rejects a correlated `IN` argument.

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

4 participants