Skip to content

Build the source AST of a literal IN set only when a remote filter reads it - #132247

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:lazy-in-literal-set-source-ast-132161
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:lazy-in-literal-set-source-ast-132161

Conversation

@groeneai

@groeneai groeneai commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #132161
Related: #132227

Changelog category (leave one):

  • Performance Improvement

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

A query with a large literal IN list no longer converts the list back to an AST during planning unless a filter is sent to remote servers: lookups with 10000 literal values are 11-18% faster. Closes #132161.

Description

Not a Bug Fix: no result changes, the work was only wasted.

CollectSetsVisitor called ConstantNode::toAST for every IN with a constant right side, to give the FutureSetFromTuple its source AST. For a Tuple constant that materializes the value as a Field twice, infers a type per element, hashes and copies it: O(N) allocations, comparable to building the set. Only the filters ReadFromRemote sends to remote servers and distributed index analysis read that AST, so a local query built and dropped it.

The set now keeps a clone of the constant node (O(1): no children, shared column) and converts it on the first getSourceAST call under callOnce, as it already does for getKeyColumns and getContentHash. The new test checks that a literal IN list still reaches the remote query; it fails when getSourceAST returns no AST.

Measured (RelWithDebInfo, 201 paired runs, Latin-square crossover, 95% bootstrap CI), PR / master: 10000 UInt64 keys in a primary key window 0.887 (0.870-0.905), 10000 String keys 0.884 (0.867-0.902), with use_statistics = 0 0.845, set_index.xml #4 0.845 and #8 0.823; a full scan without IN 1.020 (0.990-1.050); a remote() query that pushes the list 0.981 (0.968-0.995). PR+#132227 / #132227: 0.882, 0.880, 0.851. remote() secondary queries (19 shapes, incl. distributed index analysis) and 45 local IN statements are byte-identical.

Cost: the set holds the constant's column until the query ends instead of until planning ends. With #132227 that is a few hundred bytes per value: peak memory +3.4 to +7.5 MiB for a 10000-value NOT IN before a GROUP BY, +2.5 MiB (9.1 to 11.6 MiB) for a one-row 10000-value lookup over HTTP. Without it, +39 MiB (one 4 KiB PODArray chunk per element column), so this PR should be merged after #132227.

Thanks to @ snelheidai for the analysis and the patch in #132161.


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

groeneai and others added 2 commits November 17, 2026 04:39
…ads it

For `x IN (v1, ..., vN)` with a constant right side, `CollectSetsVisitor`
converted the constant back to an AST (`ConstantNode::toAST`) for every
query, to give the `FutureSetFromTuple` its source AST. For a `Tuple`
constant that conversion materializes the whole value as a `Field` twice,
infers a type per element, hashes the column, deep-copies the literal and
builds the `Tuple(...)` type name: O(N) allocations per list, comparable
to building the set itself. The only readers of that AST are the filters
`ReadFromRemote` sends to remote servers (`tryBuildAdditionalFilterAST`,
under `allow_push_predicate_ast_for_distributed_subqueries`) and
distributed index analysis, so a local query built it and dropped it.

`FutureSetFromTuple` now takes an optional clone of the constant node and
converts it on the first `getSourceAST` call under `callOnce`, then
releases the node, the same idiom it already uses for `getKeyColumns` and
`getContentHash`. The clone is O(1) (a `ConstantNode` has no children and
shares its column, type and source expression), fixes the AST to the
node's state at `CollectSets` time and does not share the original node's
unsynchronized `cached_ast`. Remote filters get the same AST as before,
built once. Every other caller keeps passing an AST (or none) through the
defaulted trailing parameter.

Measured (RelWithDebInfo, 201 paired runs per query in a Latin-square
crossover, server-side time): 10000 UInt64 keys in a primary key window
-11% (28.4 -> 25.2 ms), 10000 String keys -12%, with use_statistics = 0
-14% to -16%, `set_index.xml` queries ClickHouse#4 and ClickHouse#8 -15% and -18%; queries without a
literal list unchanged; the secondary query sent by `remote()` is
byte-identical. With the `createColumnConst` change of ClickHouse#132144 applied the
gains are the same (-12%, -12%, -15%).

Cost: the set now keeps the constant's column until the query ends
instead of until planning ends. With one 4 KiB `PODArray` chunk per
element column on current master that is +39 MiB of peak memory for a
10000-value `NOT IN` before a `GROUP BY`; after ClickHouse#132144 it is +3.4 to +7.5 MiB
(300 to 800 bytes per value), so this should be merged after ClickHouse#132144.

The new test checks that a literal `IN` list still reaches the remote
server's query; it fails when `getSourceAST` returns no AST.

Closes ClickHouse#132161

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the CollectSets call-site comment; the FutureSetFromTuple constructor comment already states that only remote filters read the source AST.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review (1 residual).

# Sev Finding Verdict Evidence / action
1 ⚠️ Must not merge before #132227: on current master the kept constant retains one 4 KiB chunk per list value until the query ends DISAGREE (no change to the code) The description states the order with both numbers (+39 MiB without #132227, +3.4 to +7.5 MiB with it, 10000 values). Merge order is not something the diff can enforce.
2 ⚠️ The new test does not notice a revert to eager AST building, and its counts are not bound to each log_comment DISAGREE Building the AST eagerly or lazily is not observable from SQL without adding instrumentation; the speed-up is covered by tests/performance/set_index.xml (#4 0.845, #8 0.823 locally). The test covers the functional risk of the change, a set that returns no AST and drops the pushed filter: it fails 5/5 then, while 0 of 314 existing pushdown tests notice. Each log_comment is a separate query with its own sets, so another query's list cannot satisfy its count.
3 💡 For a list folded from an expression with a scalar subquery, e.g. k IN (1, (SELECT max(id) FROM t)), the kept clone shares the source expression, so the subquery's table lock and snapshot are held until the query ends instead of until planning ends noted, not blocking Narrow shape; the AST itself is unchanged.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261117-044601

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The cost is deterministic: with use_statistics = 0, a 10000-key IN lookup spends 15% of its server time converting the list back to an AST (fix/base 0.845, CI 0.826-0.864, 201 paired runs). The behaviour this PR must keep, the filter pushed to a remote() server, is checked by the new test 05814_in_literal_set_pushed_down_to_remote.
b Root cause explained? CollectSetsVisitor called ConstantNode::toAST for every IN with a constant right side. For a Tuple constant that is O(N) allocations (two Field materializations, a type per element, a hash, a deep copy, the type name). Only tryBuildAdditionalFilterAST (remote filter pushdown, distributed index analysis) reads that AST.
c Fix matches root cause? Yes. The AST is built on the first getSourceAST call under callOnce from a clone of the constant node, so local queries never build it and remote filters get the same AST, once.
d Test intent preserved / new tests added? A mutation census (a getSourceAST that returns no AST) failed none of the 314 existing pushdown / predicate / distributed index analysis tests, so a new test was added: it checks the remote() secondary query of IN (...), NOT IN tuple(...) and IN [...] carries the list.
e Both directions demonstrated? New test: 50/50 OK with randomized settings on the PR build, 10/10 OK on master, 5/5 FAIL under the mutation (oracle 1 -> 0). Timing: PR / master below the A/A band on all pre-registered queries.
f Fix is general across code paths? All readers of a FutureSetFromTuple AST go through getSourceAST; the other getSourceAST readers take subquery sets only. The other FutureSetFromTuple callers (SetsSerialization, IcebergMetadata, DirectJoinMergeTreeEntity, RuntimeFilterLookup, const IN const folding, ActionsVisitor) pass an AST or none and are unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? 45 local statements (numeric, String, FixedString, LowCardinality, Date/DateTime/DateTime64, Decimal, Enum, Nullable, NULL with transform_null_in 0/1, tuple keys, NOT IN, IN tuple(), IN [], scalar, alias, Map, JSON, Variant, Dynamic, errors) and 19 remote() / distributed index analysis / parallel replicas shapes: byte-identical results, errors and secondary query texts on master and the PR.
h Backward compatible? Yes: no setting, format, protocol or serialization change.
i Invariants and contracts preserved? The AST is fixed to the constant at CollectSets time (clone), built at most once under std::call_once (concurrent readers see the published AST; a throwing conversion leaves the flag unset and is retried), and the clone does not share the original node's unsynchronized cached_ast. Cost: the constant's column lives until the query ends (+3.4 to +7.5 MiB per 10000 values with #132144).

Session id: cron:clickhouse-impl-slot-41:20261117-015900

@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0c924b0]

Summary: ✅


AI Review

Summary

The PR defers conversion of literal IN sets to an AST until remote filter pushdown or distributed index analysis requests it. Reviewed head 0c924b0033c40c10f21e417182050e1c62bca43b, including all prior discussion and the fix for the earlier SharedSet finding. No unresolved review findings remain. The reported paired benchmarks support the performance claim, and the new remote pushdown regression test passed all 50 reported ASan runs.

Performance & Safety

Preserve the documented merge order: #132227 remains open and should land first. Retaining the constant column otherwise adds approximately 39 MiB per 10000 literal values until the query ends; the PR reports substantially lower overhead with that prerequisite. This is an acknowledged merge prerequisite, with no additional code change requested here.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 17, 2026
Comment thread src/Planner/CollectSets.cpp Resolved
The `#if CLICKHOUSE_CLOUD` SharedSet dispatch sat in the constant-input
branch, which is the `else` of `if (storage_set)`, so `storage_set` is
always null there and `storage_set->getName()` dereferenced it for every
literal `IN` list in a Cloud build. Move it, unchanged, into the branch
that handles a Set table, as `ActionsMatcher::makeSet` does; the literal
branch now only calls `addFromTuple`.

Public builds compile the block out (`CLICKHOUSE_CLOUD` is 0), so their
preprocessed translation unit is identical. The block was compiled with
`-fsyntax-only` in its new place against stub `StorageSharedSet` types.

Reported by the automated review on ClickHouse#132247 (r4596124036).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0c924b003 with master 5c48ad1cc (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

218 translation units recompiled, 2651 s compile time in total, 218 of them have a recent master baseline.

Job report

This branch has not been deployed

No deployments
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The planner converts every literal IN list back to an AST that only filters sent to remote servers use

1 participant