Skip to content

Keep the empty IN set early stop of a filter when its AND is JIT-compiled - #131211

Merged
Manerone merged 5 commits into
ClickHouse:masterfrom
groeneai:jit-compiled-and-empty-in-early-stop
Nov 17, 2026
Merged

Manerone merged 5 commits into
ClickHouse:masterfrom
groeneai:jit-compiled-and-empty-in-early-stop

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #131133
Related: #116538

Changelog category (leave one):

  • Performance Improvement

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

A query that combines x IN (subquery) with other conditions by AND now stops reading as soon as the subquery returns an empty set also when compile_expressions has compiled the AND (by default once the same expression has been seen min_count_to_compile_expression times). Before, such a query, for example with FINAL, read the whole key range and only then filtered every row out.

Description

Reported by @ fm4v: 14 ms -> 203 ms on the synthetic repro, 29.7 s -> 214.6 s and twice the peak memory on the original query.

FilterTransform::prepare ends the read when a conjunct of the filter is in/globalIn over an empty set (isAlwaysFalseByEmptySet, #116538). That walk follows and nodes by name. When the JIT compiles the AND, ActionsDAG::compileFunctions replaces the node's function with an LLVMFunction whose children are the inputs of the compiled DAG, so the walk never reaches the in. The header dry run cannot fold it either: the compiled function folds only when all its arguments are constant, and a 0-row in over a Nullable column is not constant.

This PR adds ActionsDAG::getCompiledConjuncts, next to getCompiledFunctions: for a compiled node whose root is an and chain, it returns the children that are conjuncts of that chain, and the walk recurses into them. The AND stays compiled. The walk also accepts nullIn/globalNullIn (IN with transform_null_in = 1), and, like index analysis, it no longer trusts the emptiness of a set that can grow while the query runs (FutureSet::isMutableDuringQuery, an ENGINE = Set table), so such a filter now reads with the JIT off too.

Validation: the new test asserts read_rows = 0 for six filter shapes (non-Nullable and Nullable IN, FINAL, a nested and inside the compiled function, query_plan_merge_filters = 0, transform_null_in = 1); master reads 90112 or 100000 rows for each. An empty ENGINE = Set table still reads. On the issue's schema with 4M rows and JIT on, SelectedRows is 4,061,765 on master and 5,010 with this PR, the same as with JIT off. 50 randomized runs of the new test and 05045_empty_in_set_short_circuit: no failures.

collectConstantColumnsAfterFilter also matches and by name, but it does not change how much is read.


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

Version info

  • Merged into: 26.11.1.2498-master (included in 26.11 and later)
  • Backported to: 26.10.8.37

groeneai and others added 3 commits November 13, 2026 06:16
…iled

FilterTransform::prepare ends the read when the filter is false for every
row once the sets are built. isAlwaysFalseByEmptySet (ClickHouse#116538) finds an
`in`/`globalIn` over an empty set by following `and` nodes by name. With
compile_expressions, ActionsDAG::compileFunctions replaces a compilable
`and` with an LLVMFunction whose name is the CompileDAG dump and whose
children are the INPUT nodes of the compiled DAG. The `in` (not
compilable) becomes one of those children, but the walk stops at the
compiled node because it is not named `and`. The updateHeader dry run
does not fold it either: a 0-row `in` over a Nullable column is not
constant, and LLVMExecutableFunction folds only when all arguments are
constant. So the source is read to the end of the key range and every
row is filtered out afterwards (ClickHouse#131133: 14 ms -> 203 ms on the
synthetic repro, 29.7 s -> 214.6 s on the original query).

ActionsDAG::getCompiledConjuncts, next to getCompiledFunctions, maps the
i-th INPUT of the compiled DAG to the i-th child of the node (the order
getCompilableDAG appends them in and compileFunctions swaps them in) and
returns the children reached from the root through `and` FUNCTION nodes
only. isAlwaysFalseByEmptySet recurses into them for a compiled node.
Any other shape (non-LLVM function, a root that is not `and`, an input
count mismatch) returns nothing, which is the previous behaviour.

With query_plan_merge_filters (default), FilterStep splits AND atoms
into separate filters, so a flat `a > 10 AND x IN (...)` leaves
`and(<input>, in)` with no compilable child and is never compiled. The
`and` is compiled when the remainder keeps a nested `and` (the issue's
shape) or with query_plan_merge_filters = 0; the test covers both.

Closes ClickHouse#131133

Co-Authored-By: Claude Opus 5.5 <[email protected]>
isAlwaysFalseByEmptySet ends the read at prepare time when a conjunct is
an IN over an empty set. It did not check FutureSet::isMutableDuringQuery:
the set of an ENGINE = Set table is the very Set object that
StorageSet::insertBlock fills, so a concurrent INSERT can make it
non-empty while the query runs. Index analysis already refuses such sets
(05078); with the previous commit every JIT-compiled AND reaches this
walk, so a compiled filter over an empty Set table would now stop
reading. Refuse mutable sets, for the uncompiled walk as well, so both
paths agree.

With transform_null_in = 1 the analyzer rewrites IN to nullIn. Without
the JIT the header dry run folds it (05045), but under a compiled AND it
cannot fold (LLVMExecutableFunction folds only all-constant arguments)
and the walk rejected the name, so the slowdown from ClickHouse#131133 remained
for the same query under that setting. nullIn(x, empty set) is 0 for
every x, NULL included, so accept nullIn and globalNullIn.

The test gains a transform_null_in = 1 assert and an empty ENGINE = Set
table that must still be read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword the empty-set fold comment: the negative variants never make the filter always false (NULL NOT IN () is NULL, not true).

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
Finding Verdict
❌ A compiled AND over an empty ENGINE = Set table would now stop early, though that set can grow during the query AGREE: the walk skips sets with isMutableDuringQuery, test asserts the read (r1)
⚠️ nullIn/globalNullIn (transform_null_in = 1) still missed under a compiled AND AGREE: accepted by the walk, test added (r1)
⚠️ Test does not assert that the JIT compiled the expression DISAGREE: the test fails on master and with the FilterTransform.cpp change reverted; the asserted queries never execute a block, so a compile counter would need a second query per shape
❌ A constant left operand (1 IN <empty Set table>) still ends the read through the header dry run DISAGREE: not this change; while the header is computed, in evaluates a constant argument against the set and returns a constant for any contents of the Set table, empty or not. This PR changes neither in.cpp nor the header check (r2)
💡 The comment says notIn over an empty set is always true, but NULL NOT IN () is NULL AGREE: comment wording only; the point is that the negative variants never make the filter always false (r2)

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Manerone, could you review this? The empty IN set early stop of a filter matched and nodes by name, so a JIT-compiled AND hid the empty IN and the read went to the end; the walk now sees through the compiled node via ActionsDAG::getCompiledConjuncts.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test with --no-random-settings fails on master (read_rows 90112 x5 and 100000 instead of 0). The issue's query at 4M rows with JIT on: SelectedRows 4,061,765 on master.
b Root cause explained? isAlwaysFalseByEmptySet follows and nodes by name. compileFunctions replaces a compiled and with an LLVMFunction named after the compiled expression, whose children are the compiled DAG's inputs, so the in over the empty set is never reached. The header dry run cannot fold a 0-row Nullable in.
c Fix matches root cause? Yes. The walk sees through the compiled node to the same conjuncts as in the uncompiled DAG. No setting or tag, and the AND is still compiled (CompileFunction = 1).
d Test intent preserved / new tests added? New test 05628_empty_in_set_short_circuit_compiled: a read_rows oracle for six shapes, a NOT IN control, and an empty ENGINE = Set table that must still be read. 05045, 05038 and 05078 are unchanged and pass.
e Both directions demonstrated? Master: FAIL on all six asserts. First commit only: FAIL on exactly the transform_null_in = 1 assert and the ENGINE = Set line. Full PR: OK. First commit with only the FilterTransform.cpp see-through reverted: FAIL like master.
f Fix is general across code paths? Nested and inside one compiled function, a compiled conjunct under another compiled node (recursion), ALIAS, globalIn/globalNullIn, builds without the JIT (#if USE_EMBEDDED_COMPILER). The uncompiled and compiled walks apply the same set checks.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable and non-Nullable IN, transform_null_in = 1 (nullIn), FINAL and plain reads, comparisons compiled into the function (query_plan_merge_filters = 0) or not. NOT IN over an empty set still reads everything.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or result change.
i Invariants and contracts preserved? Only children reached from the root through and nodes are returned, so they are conjuncts and an empty in/nullIn among them makes every row 0 or NULL. The walk never stops early on a set that can grow during the query (FutureSet::isMutableDuringQuery). Any shape mismatch returns nothing, which keeps today's behaviour.

Session id: cron:clickhouse-impl-slot-7:20261113-064700

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b843736]

Summary: ✅


AI Review

Summary

Restores early read termination for empty immutable IN sets beneath a JIT-compiled AND, includes nullIn and globalNullIn, and excludes mutable Set tables. No actionable findings remain after reviewing the current diff, surrounding code, and all prior discussion. The focused regression passed all 50 repetitions in the parent commit's binary CI job; the current head adds only the explanatory comment requested in the existing review.

Missing context / blind spots
  • ⚠️ Full CI for b843736ab034a2ea5d166b1f23f03e03d936f21d is still running. The parent commit's workflow, including performance comparisons, passed; completed current-head CI will close this validation gap. No local build or tests were run during this review.
Final Verdict

✅ Approve — no code changes requested; normal CI gates still apply.

@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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b843736ab with master 6bb1c909d (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

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

Job report

@Manerone Manerone self-assigned this Nov 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 82f9e95

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 8/8) / limit_by_misc #3 perf: client_time +20.0% (+22.9% after restart) on a LIMIT BY over numbers_mt with no WHERE; this PR changes only the empty-set check in FilterTransform::prepare and the JIT helper it calls, which such a query never reaches a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the same one)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261113-133009

# Conflicts:
#	src/Interpreters/ExpressionJIT.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

Update on the limit_by_misc #3 row of my CI finish ledger (Performance Comparison, arm 8/8): this PR's arm binary is slower there because of where it places unchanged code. The code this PR changes does not run in that query.

  • The extra CPU samples are in LimitByTransform::consumeImpl for the two-key UInt64 hash method (417 -> 487 in the job's profile). Its machine code is identical in this binary and in the reference (same address-normalized disassembly). It sits 0x600 bytes later, behind the code this PR adds to ExpressionJIT.cpp and FilterTransform.cpp.
  • 8 other PR builds on the same reference run it at 0.98-1.01x. The slowdown reproduced in all 6 confirmation reruns, so it belongs to the binary. On the slower server the extra cycles are backend stalls; frontend stalls and branch misses stay about the same.
  • The amd shards' coverage selection did not pick limit_by_misc: per the coverage data, none of its queries executes a line this PR changes.
  • Builds with no related change hit the same slow mode too: the master builds of 2b6c3dd (1.37x) and d0647b1 (1.32x). I found no address property of this function that predicts it, and a build-level layout fix was declined in Experiment: fix the hot code layout with a linker symbol ordering file #124574.

So the only fix I see is in the gate, and that is your call, @egor-click. Should the perf job:

  • (a) downgrade a confirmed slowdown when the functions the query spends its time in have identical machine code in both binaries? It would miss a slowdown that comes only from a data-layout change elsewhere. I can send this PR.
  • (b) keep blocking such rows and leave them to the reviewer?

@nickitat

Copy link
Copy Markdown
Member

🕵 Merged master into this branch and resolved the conflicts caused by #129617 (the switch to the -WithMemoryTracking containers). This update was made automatically.

Comment thread src/Interpreters/ExpressionJIT.cpp Resolved
The walk returns only the INPUTs of the compiled `and` chain. That finds
every `in` conjunct because `FunctionIn` does not override
`isCompilableImpl` and a `Set` argument fails `canBeNativeType`, so an
`in` always stays a child of the compiled node. Make that dependency
visible where it lives.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Manerone
Manerone added this pull request to the merge queue Nov 16, 2026
Merged via the queue into ClickHouse:master with commit 5221e52 Nov 17, 2026
194 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 17, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the limit_by_misc #3 Performance Comparison red: #132328. It fixes the loop itself (LIMIT BY prefetches its hash table once it outgrows L2), so the gate question above no longer needs an answer for this row.

Manerone pushed a commit that referenced this pull request Nov 20, 2026
Resolve the conflict in src/Interpreters/ExpressionJIT.cpp: the new
ActionsDAG::getCompiledConjuncts sits right above compileFunctions, whose
parameter type differs on 26.10 (std::unordered_set; master switched it to
UnorderedSetWithMemoryTracking in #129617, which is not on 26.10). Keep the
26.10 signature and add only the lines of #131211.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll4 added a commit that referenced this pull request Nov 20, 2026
Cherry pick #131211 to 26.10: Keep the empty `IN` set early stop of a filter when its `AND` is JIT-compiled
robot-clickhouse added a commit that referenced this pull request Nov 20, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 20, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 20, 2026
Backport #131211 to 26.10: Keep the empty `IN` set early stop of a filter when its `AND` is JIT-compiled
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

compile_expressions=1 stops an AND with an empty IN-set from ending a FINAL read early (7x-14x slower)

7 participants