Skip to content

Do not JIT-compile a lambda body in a plan that is shipped to another node - #119332

Merged
alexey-milovidov merged 7 commits into
masterfrom
fix-serialize-plan-compiled-lambda-115310
Oct 4, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
fix-serialize-plan-compiled-lambda-115310

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Fix UNKNOWN_FUNCTION on a shard or a replica for a higher-order function whose lambda body is an AND of comparisons when serialize_query_plan = 1 or parallel_replicas_plan_based = 1: a JIT-compiled lambda body was serialized into the plan.

Documentation entry for user-facing changes

...

With serialize_query_plan = 1, a higher-order function whose lambda body is an AND of comparisons failed on the shard with

Code: 46. Unknown function and(UInt8, less(UInt64, 1000 : UInt16)). (UNKNOWN_FUNCTION)

for example

SELECT mapExists((k, v) -> k LIKE '%2' AND v < 1000, col) FROM dist
SETTINGS prefer_localhost_replica = 0, serialize_query_plan = 1;

That "function name" is CompileDAG::dump of a JIT-compiled expression. Unlike an ordinary expression, which travels as an ActionsDAG and becomes ExpressionActions only when the receiving node builds its pipeline, a lambda's ExpressionActions is built while the plan is built, so its DAG — already compiled, because JIT happens in the ExpressionActions constructor — is the one that gets serialized. ActionsDAG::serialize writes function_base->getName(), and for a compiled node that name is not something FunctionFactory knows. The extra conditions in the report follow from what the JIT accepts: an AND of comparisons over native types large enough to be worth compiling, which is also why an all-UInt8 variant, a single comparison or an OR slipped through.

Keep the lambda body uncompiled when the plan being built may be serialized and shipped: a logical plan for a shard under serialize_query_plan, or the local plan from which plan-based parallel replicas (parallel_replicas_plan_based) later cut a fragment for the replicas. Nothing is lost: that plan is never executed here, and the receiving node rebuilds the lambda's ExpressionActions — with compilation enabled — from the serialized DAG.

New tests: 05199_serialize_query_plan_lambda_and and 05321_parallel_replicas_plan_based_lambda_and (the latter fails on the replicas with UNKNOWN_FUNCTION without the change). Verified in both directions, and a differential run of the lambda/arrayMap/arrayExists/mapExists/serialize_query_plan/compile_expressions/distributed_plan stateless tests shows no new failures.

Closes: #115310


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

Version info

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

… node

With `serialize_query_plan = 1`, a higher-order function whose lambda body is an `AND` of comparisons
failed on the shard with

    Code: 46. Unknown function and(UInt8, less(UInt64, 1000 : UInt16)). (UNKNOWN_FUNCTION)

for example

    SELECT mapExists((k, v) -> k LIKE '%2' AND v < 1000, col) FROM dist
    SETTINGS prefer_localhost_replica = 0, serialize_query_plan = 1;

That "function name" is `CompileDAG::dump` of a JIT-compiled expression. Unlike an ordinary expression,
which travels as an `ActionsDAG` and becomes `ExpressionActions` only when the receiving node builds
its pipeline, a lambda's `ExpressionActions` is built while the plan is built, so its DAG - already
compiled, because JIT happens in the `ExpressionActions` constructor - is the one that gets serialized.
`ActionsDAG::serialize` writes `function_base->getName()`, and for a compiled node that name is not
something `FunctionFactory` knows. The extra conditions in the report follow from what the JIT accepts:
an `AND` of comparisons over native types large enough to be worth compiling, which is also why an
all-`UInt8` variant, a single comparison or an `OR` slipped through.

Keep the lambda body uncompiled when the planner is building a logical plan, which is exactly the plan
that gets serialized and shipped (a shard under `serialize_query_plan`, or a replica in the plan-based
parallel replicas mode). Nothing is lost: that plan is never executed here, and the receiving node
rebuilds the lambda's `ExpressionActions` - with compilation enabled - from the serialized DAG.

Closes: #115310
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cdd93f8]

Summary: ✅


AI Review

Summary

This PR fixes the UNKNOWN_FUNCTION failure that appears when a higher-order lambda body is serialized to another node under serialize_query_plan or plan-based parallel replicas, and the added regression coverage exercises both shipped-plan paths. I found one remaining regression risk, though: the new may_be_serialized_for_remote_execution flag is cached before later planner checks can turn parallel replicas off, so some queries that ultimately execute as pure local plans will still lose lambda JIT compilation.

Findings
  • ⚠️ Majors
    • [src/Planner/PlannerContext.cpp:95] may_be_serialized_for_remote_execution is decided once at PlannerContext construction time, but Planner::buildQueryPlanIfNeeded can still disable parallel replicas later for unsupported cases such as multiple-table queries, IN subqueries, additional_table_filters, and FINAL / STREAM. After one of those fallbacks the plan is no longer shipped anywhere, yet PlannerActionsVisitor::visitLambda still sees the cached true and leaves every lambda body uncompiled; the copy constructor at src/Planner/PlannerContext.cpp:102 then preserves the stale bit into wrapped contexts too. This introduces a local-only performance regression whenever parallel_replicas_plan_based = 1 is enabled but the query is later deemed ineligible for parallel replicas.
    • Suggested fix: keep only the immutable build_logical_plan carrier latched / copy-propagated, and recompute the plan-based-parallel-replicas half from the current Context when mayBeSerializedForRemoteExecution is queried.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required action: make the remote-serialization decision follow the current parallel-replicas state instead of the constructor-time state, so local fallbacks do not disable lambda JIT permanently.

LLVM Coverage Report

Measured on commit cdd93f8.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.20% +0.10%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 20/20 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Sep 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The red stateless jobs are all the same unrelated test: 05141_time_series_select_join_settings fails with join_algorithm = 'grace_hash' is external from the first block and needs a spill threshold, but neither max_bytes_before_external_join nor max_bytes_ratio_before_external_join resolved to a non-zero value, and the test sets both of those to 0 on purpose. That check came from the spilling-hash-join unification, which is already reverted on master (12981f21057), so it only affects merge commits built before the revert. Nothing here touches joins.

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cdd93f880 with master 2493c465d (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

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

Job report

Comment thread src/Planner/PlannerContext.cpp Resolved
alexey-milovidov and others added 2 commits September 24, 2026 05:05
Add the same lambda shape read through a trivial view and a `Merge` table
over the `Distributed` table with `serialize_query_plan = 1`, the two paths
that wrap the `PlannerContext` into a new `Context`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
Comment thread src/Planner/PlannerActionsVisitor.cpp Resolved
alexey-milovidov and others added 2 commits October 4, 2026 13:59
…allel replicas

`parallel_replicas_plan_based = 1` builds an ordinary local plan (not a logical one), and
`QueryPlanOptimizations::applyParallelReplicas` later serializes a fragment of it for the replicas.
A lambda body compiled while that plan was built reached the replicas as a `CompileDAG::dump` name
and failed there with `UNKNOWN_FUNCTION`. `PlannerContext::isLogicalPlan` is replaced by
`mayBeSerializedForRemoteExecution`, which also holds when plan-based parallel replicas can be used
on the initiator.

New test `05321_parallel_replicas_plan_based_lambda_and` fails without the change and passes with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
: query_context(std::move(query_context_))
, global_planner_context(std::move(global_planner_context_))
, is_ast_level_optimization_allowed(!(query_context->getClientInfo().query_kind == ClientInfo::QueryKind::SECONDARY_QUERY || select_query_options_.ignore_ast_optimizations))
, may_be_serialized_for_remote_execution(select_query_options_.build_logical_plan || mayShipPlanFragmentToParallelReplicas(query_context))

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.

may_be_serialized_for_remote_execution is latched too early. Planner::buildQueryPlanIfNeeded can still disable parallel replicas afterwards for several unsupported cases (disableParallelReplicasForMultipleTablesQueryIfNeeded, parallel_replicas_allow_in_with_subquery = 0, additional_table_filters, FINAL / STREAM), but visitLambda will keep seeing true here and turn off JIT for every lambda body even though the query has already fallen back to a pure local plan. The copy constructor at line 102 then preserves the stale bit into wrapped PlannerContexts for trivial views / Merge as well.

That means enabling parallel_replicas_plan_based = 1 can now regress local-only queries that happen to become ineligible for parallel replicas. Please keep only the immutable build_logical_plan carrier latched/copy-propagated, and derive the plan-based-parallel-replicas half from the current Context at use time so a local fallback re-enables lambda compilation.

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

Alright.

@alexey-milovidov alexey-milovidov self-assigned this Oct 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 4, 2026
Merged via the queue into master with commit 93c82e4 Oct 4, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-serialize-plan-compiled-lambda-115310 branch October 4, 2026 20:14
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
alexey-milovidov pushed a commit to hinata34/ClickHouse that referenced this pull request Nov 5, 2026
…tion

Since ClickHouse#125615, ReadFromCluster::applyFilters serializes the filter conjuncts
that isSerializableFilterNode accepts into cluster_table_function_pushed_down_filter,
and each replica rebuilds them with ActionsDAG::deserialize. The gatekeeper
also accepted lambda carriers: a constant-folded lambda
(ColumnConst(ColumnFunction)) and a capturing lambda (FunctionCapture). A
lambda body is an ExpressionActions built while the initiator plans the query,
and its constructor JIT-compiles the DAG in place, replacing the nodes with an
LLVMFunction named after CompileDAG::dump(). The serialized filter then carries
that name, and the replica's FunctionFactory::get throws UNKNOWN_FUNCTION once
the body has been compiled (after min_count_to_compile_expression runs).

The planner keeps lambda bodies uncompiled only for plans that are shipped as
a whole (ClickHouse#119332, mayBeSerializedForRemoteExecution). This plan is executed on
the initiator, so refuse Function-typed nodes in the gatekeeper instead. The
check runs before the recursion, so the whole atom stays on the initiator and
the other conjuncts are still sent. The initiator applies the full filter, so
results do not change; the replicas only stop pre-filtering by lambda
conjuncts, as before ClickHouse#125615.

Extend 05394_cluster_function_filter_pushdown_to_replicas with a folded and a
capturing lambda case.

Closes ClickHouse#128422

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

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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

2 participants