Skip to content

Forbid table references in IN operator in key expressions - #107424

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-not-ready-set-table-in-key-expression
Jun 20, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-not-ready-set-table-in-key-expression

Conversation

@groeneai

@groeneai groeneai commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

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 server crash (Logical error: Not-ready Set is passed as the second argument for function 'in') when a key expression (ORDER BY, PRIMARY KEY, PARTITION BY, or a skip INDEX) contained an IN operator with a table on the right-hand side, e.g. ORDER BY (x IN some_table). Such key expressions are now rejected at table creation time.

Description

Found by the AST fuzzer (AST fuzzer (amd_debug, targeted), STID 0250-424f) on PR #106650.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106650&sha=fbc0e4d4abc1d27e19154633fa7c8ec6accdcd5a&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

This is not a regression of #106650 (the sort PR). It is a pre-existing trunk bug in DDL validation that the fuzzer happened to surface there.

Reproducer (deterministic, plain master, no fuzzer)

CREATE TABLE t (x Int32) ENGINE = Memory;
CREATE TABLE u (a Int32) ENGINE = MergeTree ORDER BY (a IN t) AS SELECT 1;
-- Logical error: Not-ready Set is passed as the second argument for function 'in'

Root cause

ORDER BY (x IN (SELECT ...)) is already rejected at DDL time by checkExpressionDoesntContainSubqueries (the change that forbade subqueries in key expressions, closing #96657). That check only looks for ASTSubquery nodes. The table-reference form x IN some_table parses to an ASTIdentifier / ASTTableIdentifier on the right-hand side, not an ASTSubquery, so it slips past the check. The table is created, and on the first INSERT the MergeTree writer evaluates the sorting key, where the FunctionIn set was never built (set-building plans are only added for SELECT pipelines), so FunctionIn::executeImpl aborts the server.

FunctionIn::executeImpl                       src/Functions/in.cpp:116
ExpressionActions::execute
MergeTreeDataWriter::writeTempPartImpl         src/Storages/MergeTree/MergeTreeDataWriter.cpp:723
MergeTreeSink::consume

Fix

Extend checkExpressionDoesntContainSubqueries to also reject an IN / GLOBAL IN / NOT IN (and the null / global variants) operator whose second argument is an identifier (table reference) in a key expression. This mirrors the existing subquery rejection and covers ORDER BY, PRIMARY KEY, PARTITION BY, skip INDEX, and the ALTER paths through the same chokepoint. Literal sets (x IN (1, 2, 3), x IN [1, 2, 3]) are constants and remain allowed. Test cases for the new behavior are added to 03916_merge_tree_order_by_subquery.

Note on backward compatibility: a table with x IN table in a key can be created by current versions, persists on disk, and re-attaches on restart (every INSERT to it crashes the server). The new rejection runs through getKeyFromAST / getIndexFromAST, the same path the subquery rejection uses, so it fires at CREATE. Since such a table is already non-functional, failing fast at CREATE seems acceptable, but I am happy to gate the new check on LoadingStrictnessLevel::CREATE if maintainers prefer to keep ATTACH of pre-existing broken tables working.

Version info

  • Merged into: 26.6.1.1072

A key expression such as `ORDER BY (x IN some_table)` (or in PRIMARY KEY,
PARTITION BY, or a skip INDEX) builds a FutureSet for the IN operator that is
only filled in a SELECT pipeline. During INSERT the key is evaluated by the
MergeTree writer, where the set is never built, so FunctionIn aborts the server
with `Logical error: Not-ready Set is passed as the second argument for function
'in'`.

The subquery form `x IN (SELECT ...)` is already rejected at DDL time by
checkExpressionDoesntContainSubqueries (added to forbid subqueries in key
expressions). The table-identifier form `x IN table` produces an ASTIdentifier /
ASTTableIdentifier on the right-hand side instead of an ASTSubquery, so it slips
past that check and then crashes on the first INSERT. It has the same defect and
no practical use case, so reject it at DDL time as well.

Literal sets (`x IN (1, 2, 3)`, `x IN [1, 2, 3]`) are constants and remain
allowed in key expressions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (x Int32) ENGINE=Memory; CREATE TABLE u (a Int32) ENGINE=MergeTree ORDER BY (a IN t) AS SELECT 1; aborts the server every time with Logical error: Not-ready Set is passed as the second argument for function 'in'. No fuzzer, no randomization, no timing needed.
b Root cause explained? Yes. A key expression with x IN <table> builds a FutureSet for the IN operator that is only filled in a SELECT pipeline. During INSERT the MergeTree writer evaluates the sorting/primary/partition key (MergeTreeDataWriter::writeTempPartImpl), where the set was never built, so FunctionIn::executeImpl (in.cpp:116) hits the not-ready-set assertion and aborts. The DDL check checkExpressionDoesntContainSubqueries already rejects x IN (SELECT ...) but only matches ASTSubquery; the table-identifier RHS is an ASTIdentifier/ASTTableIdentifier, so it slips through and crashes at INSERT.
c Fix matches root cause? Yes. The fix closes the exact DDL-validation hole at its source: it extends the same checkExpressionDoesntContainSubqueries chokepoint to also reject an IN-family operator with a table-identifier RHS, so the invalid key is rejected at CREATE instead of crashing the server on INSERT. Not a symptom guard at the crash site.
d Test intent preserved / new tests added? Yes. Added cases to 03916_merge_tree_order_by_subquery covering the table-identifier form across ORDER BY / GLOBAL IN / NOT IN / PARTITION BY / PRIMARY KEY / skip INDEX (all serverError BAD_ARGUMENTS), plus a positive case proving literal-set keys (x IN (1,2,3)) still work. Existing subquery cases unchanged.
e Both directions demonstrated? Yes. Without the fix the reproducer (and all 11 buggy forms, incl. the original fuzzer query) aborts with SIGABRT; with the fix all are rejected at DDL with BAD_ARGUMENTS and all 7 legitimate forms (literal sets, arrays, range(), plain keys, normal IN in SELECT) still succeed. 03916 passes 10/10 with randomization via clickhouse-test.
f Fix is general, not a narrow patch? Yes. The single chokepoint checkExpressionDoesntContainSubqueries is shared by KeyDescription (ORDER BY / PRIMARY KEY / PARTITION BY), IndicesDescription (skip indexes), and TTLDescription, and runs on both CREATE and ALTER. Verified all of these paths (and dotted db.table, nested expressions, ALTER ADD INDEX) are now rejected, while literal-set RHS is preserved. The detection matches both ASTIdentifier and ASTTableIdentifier (the canonical pattern used in ActionsVisitor).

Session id: cron:clickhouse-worker-slot-0:20260613-220500

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4bee9a0]

Summary: ✅


AI Review

Summary

This PR rejects IN operators whose right-hand side is parsed as a table reference inside key-like expressions, turning the Not-ready Set LOGICAL_ERROR into DDL validation. The direct table-reference bug is covered, but the current structural check still rejects alias-backed literal sets before normal alias resolution can prove they are not tables, and it intentionally keeps the older metadata-loading compatibility break. I am requesting changes.

Findings

⚠️ Majors

  • [src/Storages/extractKeyExpressionList.cpp:34] The new guard treats every RHS ASTIdentifier as a table before TreeRewriter::normalize can resolve aliases. A key like ORDER BY (c0 IN ((1, 2, 3) AS s), c0 IN s) uses only literal sets: MarkTableIdentifiersVisitor skips RHS identifiers present in aliases, and QueryNormalizer expands s. This PR rejects that valid form at CREATE and rejects existing metadata at ATTACH/startup. Suggested fix: make this validation alias-aware, or run it after table identifiers are marked, and add a regression for an alias to a literal set.
  • [src/Storages/extractKeyExpressionList.cpp:34] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/107424#discussion_r3408813611] The new validation also runs while loading existing metadata, so an upgraded server can fail to load a table that an older version created with ORDER BY (x IN table). Even if inserts into that table were already broken, blocking startup prevents normal repair or drop workflows. Suggested fix: gate only this new table-RHS rejection for fresh CREATE/ALTER validation, or provide an upgrade-safe repair path.
Tests
  • ⚠️ Please add a focused stateless regression for an IN key expression whose RHS is an alias to a literal set, e.g. ORDER BY (c0 IN ((1, 2, 3) AS s), c0 IN s), so the fix keeps the table-RHS rejection without rejecting alias-expanded constants.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: make the new table-RHS validation preserve alias-expanded literal sets, and either address or explicitly document the upgrade/startup behavior for existing metadata that now fails validation.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 14, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jun 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on 06ae981ad7cd. No PR-caused failures.

  • All AST fuzzer variants (incl. amd_debug/targeted, the check from the directive) and Stateless/Integration: success. The Not-ready Set crash (STID 0250-424f) does not recur on this HEAD.
  • Bugfix validation (functional tests): the "Lost forever for SharedMergeTree" / "Lost s3 keys" / "S3_ERROR No such key" / "OOM in dmesg" / "Exception in test runner" rows are CI-harness server-log-scan pseudo-tests, the same set surfacing on multiple unrelated PRs in jobs that pass; unrelated to this change (it touches only key-expression DDL validation).
  • CH Inc sync: non-gating internal mirror check.

alexey-milovidov and others added 2 commits June 20, 2026 02:15
Address review feedback (@alexey-milovidov): a bare identifier on the
right-hand side of `IN`, such as `c0 IN c1`, is always interpreted as a
table reference, never as a column. `MarkTableIdentifiersVisitor` rewrites
it to a table identifier, so `a IN b` resolves to `a IN (SELECT * FROM b)`.

There is therefore no legitimate "column on the right of IN" key expression
to preserve: on previous versions such a key failed with `UNKNOWN_TABLE`
when the name did not resolve to a table, or with the "Not-ready Set"
`LOGICAL_ERROR` on the first INSERT when it did. Rejecting it at DDL time is
not an over-rejection of a valid case.

Add the column form (`c0 IN c1`) and the qualified-table form
(`c0 IN default.tref`) to `03916_merge_tree_order_by_subquery`.

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

Copy link
Copy Markdown
Member

Picked this up (/continue-pr). Re-merged master (clean — master had not touched any of the PR's files since the merge-base) and pushed 06ae981ad7c..4bee9a0a190.

Disposition of the two open threads:

  • a IN <column> over-rejection (resolved): not a real concern. The right-hand side of IN is always rewritten to a table reference by MarkTableIdentifiersVisitor, so a IN b resolves to a IN (SELECT * FROM b) and never to the column b. On master ORDER BY (c0 IN c1) already fails with UNKNOWN_TABLE, and the existing-table form aborts with the Not-ready Set LOGICAL_ERROR. So the structural reject does not over-reject any valid case; it just turns those into a clean BAD_ARGUMENTS at CREATE. Added the column form (c0 IN c1) and qualified-table form (c0 IN default.tref) to 03916_merge_tree_order_by_subquery to lock this in. The C++ check is unchanged from the already-green commit 06ae981a.

  • ATTACH / startup compatibility (resolved): overruled by the maintainer — these key expressions are rejected unconditionally on purpose, as such a table is already non-functional (every INSERT aborts the server). No LoadingStrictnessLevel gating added.

CI was green on 06ae981a (162 jobs, 0 failures); a fresh run will follow this push. The new test lines exercise the same rhs->as<ASTIdentifier>() branch as the already-green table-reference cases.

if (args && args->children.size() == 2)
{
const auto & rhs = args->children[1];
if (rhs->as<ASTIdentifier>() || rhs->as<ASTTableIdentifier>())

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 rejects more than table references because the check runs before the alias pass that normally disambiguates IN RHS identifiers. TreeRewriter::normalize first collects aliases, MarkTableIdentifiersVisitor deliberately skips an IN RHS when aliases.contains(identifier->name()), and then QueryNormalizer expands the alias. So a key such as:

ORDER BY (c0 IN ((1, 2, 3) AS s), c0 IN s)

uses only literal sets and should not build a table FutureSet, but this pre-analysis ASTIdentifier check rejects the second expression and will also reject existing metadata on ATTACH/startup. Please make this validation alias-aware, or perform the table-RHS rejection after table identifiers have been marked, and add a regression for an alias to a literal set.

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.

I tested the exact example on master (before this PR): the alias-to-literal-set form is not a working key.

ORDER BY (c0 IN ((1, 2, 3) AS s), c0 IN s) -- CREATE succeeds, but the first INSERT aborts with
Code: 10. NOT_FOUND_COLUMN_IN_BLOCK: Not found column in(c0, s) in block. There are only columns: c0, in(c0, (1, 2, 3)).

The alias s is not expanded inside the stored key: SHOW CREATE keeps it as ORDER BY (c0 IN ((1, 2, 3) AS s), c0 IN (s)), so at INSERT time the key wants a column in(c0, s) that the block does not have. Unlike a SELECT projection, the key expression is not normalized through the alias pass, so c0 IN s does not become a literal set. Reversed order fails even earlier with UNKNOWN_TABLE (s taken as a table).

So c0 IN s is the same bug class as c0 IN <table> / c0 IN <column>: a non-functional key that fails on first use. The structural reject is not over-rejecting a valid case; it converts the first-INSERT abort into a clean BAD_ARGUMENTS at CREATE.

The alias-DEFINE occurrence c0 IN ((1, 2, 3) AS s) is unaffected: its RHS is a Literal Tuple (alias s), not a bare identifier, so the check does not fire and it still works. The ATTACH/startup point is the compatibility concern already resolved on this PR (these non-functional keys are rejected unconditionally on purpose).

@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.50% 92.60% +0.10%
Branches 77.40% 77.50% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 10/10 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 20, 2026
Merged via the queue into ClickHouse:master with commit 4c2016f Jun 20, 2026
166 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 20, 2026
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.

3 participants