Skip to content

Fix a crash when an IN subquery of a standalone expression reads a Distributed table - #121639

Merged
alexey-milovidov merged 25 commits into
masterfrom
old-interpreter-subqueries-via-analyzer
Oct 8, 2026
Merged

alexey-milovidov merged 25 commits into
masterfrom
old-interpreter-subqueries-via-analyzer

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Related: #121464
Related: #121418
Related: #120311
Closes: #121956

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

Stress test (arm_tsan) on master, Segmentation fault (STID: 1635-49b2):
report.

src/Storages/StorageDistributed.cpp:636: DB::StorageDistributed::getOptimizedQueryProcessingStageAnalyzer(...)
src/Storages/StorageDistributed.cpp:555: DB::StorageDistributed::getQueryProcessingStage(...)
src/Interpreters/InterpreterSelectQuery.cpp:1354: DB::InterpreterSelectQuery::getSampleBlockImpl()
src/Interpreters/interpretSubquery.cpp:127: DB::interpretSubquery(...)
src/Interpreters/ActionsVisitor.cpp:1875: DB::ActionsMatcher::makeSet(...)
src/Interpreters/ExpressionAnalyzer.cpp:2004: DB::ExpressionAnalyzer::getActionsDAG(bool, bool)
src/Storages/StorageMerge.cpp:1909: DB::ReadFromMerge::RowPolicyData::RowPolicyData(...)

This is the second producer of the null dereference reported in #121464. #121418 fixes the one that
reaches it through ExecuteScalarSubqueriesVisitor - 27 of the 29 occurrences of the two sibling STIDs
in the CI database over the last five days. The two remaining ones, including the report above, come
through interpretSubquery instead, which that PR does not touch: the STID is computed from the top of
the stack, which both producers share, so the two are not distinguishable by it.

An IN subquery of a standalone expression - a row policy, a CHECK constraint - is compiled by
ExpressionAnalyzer, whose ActionsMatcher::makeSet built the subquery's plan with the interpreter that
preceded the analyzer. StorageDistributed resolves its read through a query tree and a planner context
that interpreter never builds, and dereferences them unconditionally.

Until #120311 this was hidden rather than absent: IInterpreterUnionOrSelectQuery's constructor set
allow_experimental_analyzer = 0 on the interpreter's own context, and the storages read under it took
their AST arm. That PR removed the assignment together with the arms it protected. The defect is
therefore master-only: the statement in the test below reaches the shard read on 26.8 and 26.9 and
segfaults on master, which is why there is no changelog entry.

makeSet now builds the plan with InterpreterSelectQueryAnalyzer. What interpretSubquery does around
that - a table name or a table function becomes SELECT <columns> FROM it, the subquery gets its own
context with the whole-query result limits lifted - is shared rather than duplicated, as prepareSubquery.
makeSet already built a query tree of the same subquery for its set key, so the analyzer was on this
path before this change.

With this and #121418, nothing hands the interpreter that preceded the analyzer a nested SELECT of a
user's query anymore. interpretSubquery's two other callers - buildJoinedPlan and
GlobalSubqueriesVisitor - are reached from InterpreterSelectQuery only, and the one construction site
of that interpreter left outside its own recursion is ProjectionsDescription, which is exactly what
#120311 kept it for: a synthetic SELECT over a source built in place.

The CHECK constraint half of the new test segfaults the build of this commit without the change
(clickhouse local, exit 139); the row-policy half is the stack of the report above. 425 tests of
the local stateless families that reach makeSet - row policies, constraints, GLOBAL IN, prepared
sets, mutations, Merge tables - pass with the change; the 13 that fail on my machine all reach the
neighbouring server on this host through a port or a path the test hardcodes, or need object storage.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1795-master (included in 26.10 and later)

…e analyzer

A standalone expression - a row policy, a `CHECK` constraint, a `TTL` expression - is
compiled by `ExpressionAnalyzer`, and `ActionsMatcher::makeSet` built the plan of an `IN`
subquery in it with the interpreter that preceded the analyzer. `StorageDistributed`
resolves its read through a query tree and a planner context that interpreter never
builds, and dereferences them unconditionally, so reading a `Distributed` table from such
a subquery crashed the server.

`IInterpreterUnionOrSelectQuery` used to set `allow_experimental_analyzer = 0` on the
interpreter's own context, and the storages read under it took their AST arm. #120311
removed the assignment together with the arms it protected, which is what uncovered the
dereference. It is the same defect as
#121464, reached through a second producer:
#121418 replaces the one in
`ExecuteScalarSubqueriesVisitor`, which accounts for 27 of the 29 occurrences of the two
sibling STIDs in the CI database over the last five days; the other two come through
`interpretSubquery`, and the STID does not tell them apart because it is computed from the
top of the stack, which both share.

`makeSet` now builds the plan with `InterpreterSelectQueryAnalyzer`. What `interpretSubquery`
does around it - a table name or a table function becomes `SELECT <columns> FROM it`, and
the subquery gets its own context with the whole-query result limits lifted - is shared as
`prepareSubquery` rather than duplicated. `makeSet` already built a query tree of the same
subquery for its set key, so the analyzer was on this path before this change.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=e96f004b984ced9a97237e99b3e744599a917870&name_0=MasterCI&name_1=Stress%20test%20%28arm_tsan%29

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

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2a710f7]

Summary: ✅


AI Review

Summary

This PR correctly moves standalone-expression IN subqueries onto the analyzer and adds good coverage for Distributed, TTL, MATERIALIZED CTE, insertion-table, and materialized-view cases. The remaining gap is that the bare table-function shorthand (x IN format(...) / x IN s3(...)) still resolves its metadata before the analyzer-only context pinning happens, so the fix is incomplete for one RHS carrier and can still produce a wrong projection or an Unknown columns exception inside INSERT ... SELECT.

Findings

⚠️ Majors

  • [src/Interpreters/interpretSubquery.cpp:109] prepareSubquery executes bare RHS table functions against context->getQueryContext() before interpretSubqueryWithAnalyzer clears use_structure_from_insertion_table_in_table_functions. For standalone expressions evaluated during INSERT ... SELECT, x IN format(CSV, '1\n2') can therefore still borrow the insertion table schema and synthesize the wrong SELECT <columns> FROM ... wrapper, even though x IN (SELECT * FROM format(...)) is covered and fixed.
    Suggested fix: pin use_structure_from_insertion_table_in_table_functions = 0 before the metadata probe for bare table functions too, ideally by making the analyzer path call prepareSubquery with the already-pinned subquery context. Add one focused stateless test for the shorthand carrier alongside tests/queries/0_stateless/05290_in_subquery_of_standalone_expression_cte_and_insertion_table.sql.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: fix the bare-table-function RHS path so metadata discovery runs under the pinned subquery context, and add one regression test for x IN format(...) (or equivalent shorthand table-function syntax) under INSERT ... SELECT.

LLVM Coverage Report

Measured on commit 2a710f7.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 30/34 (88.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 22, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 22, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 2a710f72d3841cf97ca630c54894eb4ea0e133ea was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

alexey-milovidov and others added 2 commits September 23, 2026 00:12
…constraint

`ActionsMatcher::makeSet` reroutes both an explicit subquery and a bare table
name (`x IN in_subquery_dist`, which stands for `SELECT * FROM` it) through the
analyzer; the test covered only the former.

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

Copy link
Copy Markdown
Member Author

🕵 Both AST fuzzer (amd_debug, targeted) reds on f5b1808 (Segmentation fault (STID: 1635-49b2)) are the other producer of this null dereference, not the path this PR changes: the stack goes InterpreterCreateQuery::getConstraintsDescription → TreeRewriter::analyze → executeScalarSubqueries → ExecuteScalarSubqueriesVisitor.cpp:124 getQueryInterpreter → InterpreterSelectQuery::getSampleBlockImpl → StorageDistributed::getOptimizedQueryProcessingStageAnalyzer - i.e. the targeted fuzzer turned the new test's CHECK x IN (SELECT x FROM in_subquery_dist) into a scalar subquery. That is exactly what #121418 ("Fix a crash when a CHECK constraint's scalar subquery reads a Distributed table") fixes; it is still open. Master merged in and the review thread addressed (bare-table IN case added to the test).

alexey-milovidov and others added 2 commits September 23, 2026 04:50
…tributed` table

The `TTL` builder is another standalone-expression caller that builds `IN`
sets through `ExpressionAnalyzer`; add a smoke case that applies such a
`TTL` in a merge. The subquery of a `TTL` is resolved outside of the current
database (same on 26.7), so the table is qualified.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…queries-via-analyzer

Brings in #121418, which fixes the `AST fuzzer (amd_debug, targeted)` red
`Segmentation fault (STID: 3422-39ed)` on 983463d (the scalar-subquery producer through `ExecuteScalarSubqueriesVisitor`):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121639&sha=983463d6ae29e47625c100c134e9f40c822a41e8&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
PR: #121639

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

Copy link
Copy Markdown
Member Author

🕵 The only red on 983463d, AST fuzzer (amd_debug, targeted) Segmentation fault (STID: 3422-39ed), comes from the scalar-subquery producer (InterpreterCreateQuery::getConstraintsDescription → executeScalarSubqueries → ExecuteScalarSubqueriesVisitor), not from the interpretSubquery path this PR changes. #121418 fixes that path and has now merged, so I merged master in (e6477cf).

alexey-milovidov and others added 2 commits September 27, 2026 22:05
…on with parallel replicas

`makeSet` now plans the subquery with `InterpreterSelectQueryAnalyzer`, which treats it as a query of
its own and applies parallel replicas when the default profile enables them. A background merge that
evaluates `TTL ... WHERE x IN (SELECT ...)` then read the set's subquery through parallel replicas, so
the set was no longer built on the merge's own thread and `05215_ttl_delete_vertical_merge_set_built_once`
read `SetsBuiltFromSubquery = 0` in the `ParallelReplicas` stateless job. The interpreter never used
parallel replicas for such a subquery; disable them, as `ExecuteScalarSubqueriesVisitor` already does.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121639&sha=e6477cfc10015c7076122c316fa9890ef911ac81&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
#121639

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Interpreters/interpretSubquery.cpp Resolved
…yzer-built `IN` subquery

`InterpreterSelectQueryAnalyzer` re-applies a subquery's own `SETTINGS` clause over the context
it is handed, so a persisted `TTL ... WHERE x IN (SELECT ... SETTINGS enable_parallel_replicas = 1)`
turned parallel replicas back on and built the set off the merge thread. Strip both setting names
from a clone of the subquery AST, as `ExecuteScalarSubqueriesVisitor::getQueryInterpreter` does.

Addresses review feedback on #121639

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Interpreters/interpretSubquery.cpp Resolved
Comment thread src/Interpreters/interpretSubquery.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

No performance change can be attributed to this PR. The only server code it changes is how the older expression machinery builds the set for an IN subquery: it now uses the analyzer, which matters for CHECK constraints, TTL expressions and row policies that read Distributed or Merge tables. ClickBench Q30 (+30.8%) and Q31 (+27.8%) are GROUP BY aggregations with no IN subquery, so they never run that code. Their CPU time is flat and both medians fall inside master's recent range, so marking them as within the normal range is correct and they should not be treated as regressions.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 221 289 +30.8% <0.0001 aggregation: This GROUP BY aggregation has no IN subquery and runs through the analyzer, so it never reaches the changed makeSet path. CPU time is flat and the 289 ms median sits inside master's recent range.
⚠️ 31 not_sure 264 338 +27.8% <0.0001 aggregation: This high-cardinality GROUP BY has no IN subquery and does not run the changed code. CPU time is flat and the 337.5 ms median sits inside master's recent range.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: cc697db6-67fc-45e0-bcaf-5a6eac988267
  • MIRAI run: c873690e-de92-4793-8b2a-0674d3a5d93f
  • PR check IDs:
    • clickbench_3360617_1791207737
    • clickbench_3360623_1791207737
    • clickbench_3360634_1791207738
    • tpch_adapted_1_official_3360641_1791207737
    • tpch_adapted_1_official_3360651_1791207737
    • tpch_adapted_1_official_3360687_1791207737

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (88e4e48) to clear the CH Inc sync reds on a7fb3d3. The new Stress test (amd_msan, meta in keeper) failure (Async database load failed after restart, table t_check_nested__fuzz_1 with a fuzzed scalar-subquery CHECK constraint) comes from the AST fuzzer replaying DDL of 05292_standalone_expression_scalar_subquery_with_join, which 24f7525 on master fixes by pinning ast_fuzzer_any_query = 0. The other reds are known flaky tests unrelated to this change: 01168_mutations_isolation (https://github.com/ClickHouse/clickhouse-private/issues/13092), 04238_alter_rename_column_merge_race (https://github.com/ClickHouse/clickhouse-private/issues/63469), and runner timeouts. The PR diff is unchanged and the build is clean.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red on 88e4e48, Build (amd_fuzzers), was a link failure of clickhouse_fuzzer (relocation R_X86_64_PC32 out of range in libclang_rt_asan.a), not caused by this change. #123738 fixed it on master, so I merged master in (05097dd). There were no conflicts, the changed translation units build, and the PR diff is unchanged.

Comment thread src/Interpreters/interpretSubquery.cpp Resolved
… subquery

`interpretSubqueryWithAnalyzer` now passes `getViewSource` to `InterpreterSelectQueryAnalyzer`,
so under a materialized view the subquery reads the inserted block instead of the catalog table,
as `ExecuteScalarSubqueriesVisitor` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/interpretSubquery.cpp Resolved
alexey-milovidov and others added 3 commits October 4, 2026 06:08
…er a materialized view

A row policy with `x IN (SELECT x FROM src)` is applied while a `Merge` table reads its child
inside the query of a materialized view over `src`. The source is a `Null` table, so the set
contains the inserted rows only if the subquery reads the view source rather than the catalog table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flush context of an asynchronous insert has no current database, so the
unqualified table in the row policy was resolved in the default database and the
test failed in `Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel)`:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121639&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_llvm_coverage%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel)
#121639

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

Copy link
Copy Markdown
Member Author

🕵 The only red on 164b97c was the new test 05321_in_subquery_of_standalone_expression_under_materialized_view in Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel). The flush context of an asynchronous insert has no current database, so the unqualified in_sub_mv_src in the row policy was looked up in the default database (UNKNOWN_TABLE). The old interpreter resolves an unqualified name through the context's current database in the same way, so this does not come from this change. The test now runs its INSERT with async_insert = 0 (b6bd3c8). I also merged master (2a710f7). Locally, 05321 now passes with and without async_insert=1.

Comment thread src/Interpreters/interpretSubquery.cpp Resolved

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit 756552d Oct 8, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the old-interpreter-subqueries-via-analyzer branch October 8, 2026 00:39
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
kute1654 pushed a commit to kute1654/ClickHouse that referenced this pull request Oct 10, 2026
…te in PREWHERE

`EXPLAIN AST optimize = 1` analyses the query with the interpreter that preceded the
analyzer, and `appendPrewhere` builds the set of an `IN` subquery in `PREWHERE`. Before
ClickHouse#121639 that set was planned without a query tree, so reading `remote` through
`StorageDistributed::read` dereferenced a null `PlannerContext`. None of ClickHouse#121639's tests
goes through `EXPLAIN`, so this adds the minimal case from ClickHouse#117253.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117253&sha=546cd65f39602b759209f1649d527c047d1bc250&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29

Related: ClickHouse#121639
Related: ClickHouse#117253

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kute1654 pushed a commit to kute1654/ClickHouse that referenced this pull request Oct 10, 2026
…t table

The sharding key is compiled once in the StorageDistributed constructor.
An IN over a subquery or over a non-Set table registers a
FutureSetFromSubquery there, and nothing ever builds it for table
metadata, so every consumer of the key sees an unready set: an INSERT
fails in DistributedSink::createSelector with "Not-ready Set is passed as
the second argument for function 'in'" (LOGICAL_ERROR), and the
optimize_skip_unused_shards path folds the key to a wrong constant and
prunes to the wrong shard (26.8 and 26.3 return 0 instead of 1 for a
point query on such a table).

Reject such a key with BAD_ARGUMENTS right after it is built. A tuple or
Set-table IN is a ready set and keeps working. As for arrayJoin
(be38893), only a definition stated now is checked
(is_fresh_definition): stored tables still load and ALTER does not
revalidate. The check runs after the build so a missing table in the key
still reports UNKNOWN_TABLE (02111_global_context_temporary_tables).

Found by BuzzHouse (amd_tsan) on ClickHouse#117004, where the INSERT into remote()
with c0 GLOBAL NOT IN <Alias of a Remote table> segfaulted before ClickHouse#121639
and fails with this LOGICAL_ERROR after it.

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

blocker This issue / pr blocks a new release comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-not-for-changelog This PR should not be mentioned in the changelog 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.

Segfault on INSERT when CHECK constraint uses IN (SELECT ... FROM remote())

3 participants