Skip to content

Avoid server abort on type mismatch during partial result evaluation - #109747

Merged
alexey-milovidov merged 27 commits into
ClickHouse:masterfrom
groeneai:fix-partial-result-type-mismatch-abort
Aug 21, 2026
Merged

alexey-milovidov merged 27 commits into
ClickHouse:masterfrom
groeneai:fix-partial-result-type-mismatch-abort

Conversation

@groeneai

@groeneai groeneai commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110048
Related: #97411

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):

Constant folding during query planning no longer executes a function whose argument type differs from the type the function was resolved for during analysis. Such a mismatch used to raise a LOGICAL_ERROR while the output header was being computed, which is an assertion failure in debug and sanitizer builds. Folding is now skipped instead, and a genuinely invalid query still reports a recoverable ILLEGAL_TYPE_OF_ARGUMENT error from the normal execution path.

Description

ActionsDAG::updateHeader matches header columns to DAG input nodes by name only, then runs evaluatePartialResult to compute the output header. A function node, by contrast, is resolved once during analysis: the overload is picked and the return type computed for a fixed set of argument types. If partial evaluation is handed an input column whose type differs from the one the function was resolved for, executeActionForPartialResult used to execute the function anyway. That trips a LOGICAL_ERROR inside the function body (for example FunctionUnaryArithmetic: "negate's argument does not match the expected data type"), and because handle_error_code routes LOGICAL_ERROR to abortOnFailedAssertion, a debug or sanitizer build aborts the whole server process during planning rather than failing the one query.

Fix. Before executing a FUNCTION node in partial evaluation, compare each argument column's type against the type recorded in function_base->getArgumentTypes(). If any of them differs, skip the fold: it is only an optimization, and the node's declared result type is already known from analysis.

  • With input_rows_count == 0 (header computation) an empty column of the declared result type is produced, so header computation proceeds.
  • With input_rows_count == 1 (the callers reached from JOIN rewrites, shard skipping and virtual-column path extraction) the column is left null. Those callers treat any non-null output as a definitive folded value, so a fabricated one could silently change a JOIN rewrite or skip the wrong shards; a null routes them through their existing "unknown value" path.

The comparison is exact rather than wrapper-stripped, because isNullable derives its value from the argument type alone: its result type is UInt8 either way, so a wrapper-only difference would produce a definitive but wrong value that no result-type check can catch.

ALIAS and ARRAY_JOIN need the same treatment, because both used to pass a value through while keeping the declared type computed during analysis. That hid the mismatch from the check above and let a downstream function execute on an incompatible column anyway. Both now carry the argument's actual type, which is what ExpressionActions::executeAction already does in its own ALIAS and ARRAY_JOIN cases.

One result type cannot be instantiated: DataTypeFunction, the result type of a captured lambda, inherits IDataTypeDummy::createColumn, which throws NOT_IMPLEMENTED. The column is left null in that one case. Since a capture is normally a child of the higher-order function consuming it, that function then reports a recoverable NOT_FOUND_COLUMN_IN_BLOCK, whereas executing the stale capture raises Cannot capture column N because it has incompatible type, another LOGICAL_ERROR abort. (DataTypeNothing and DataTypeSet derive from the same base but do override createColumn, so they are built normally.)

Scope. In production the mismatch was produced by a concurrent EXCHANGE TABLES. The query does hold its table object, lock and metadata snapshot for its whole lifetime (InterpreterSelectQuery.cpp:635-656), so the held storage is never swapped. What drifts is that the old analyzer resolves the table name a second time for the analyzed column types (getTableExpressions.cpp:118, reached from joined_tables.resolveTables()), and an exchange changes what that second resolution returns. The per-query storage cache from #97411 is what keeps those two resolutions consistent; #108728 defeated it and #110048 restored it, which is what 03915_exchange_tables_race races for. This change is therefore no longer the fix for that race; it hardens the planning path itself so that any argument-type mismatch degrades to "do not fold" instead of aborting the server. I left the changelog category as Bug Fix because the abort was user-visible on released builds before #110048, but I am happy to move it to Not for changelog if you prefer, given that the root cause is now fixed upstream.

Testing. Coverage is a unit test rather than a functional one, because the race is an inherent TOCTOU and cannot be reproduced deterministically. Since updateHeader binds header columns by name only, the mismatch can be injected directly, single-threaded, with no race at all. src/Interpreters/tests/gtest_actions_dag_partial_result_type_drift.cpp covers a strict function (Float64 resolved, Int256 supplied), a wrapper-only difference through materialize, the same mismatch behind an ALIAS and behind an ARRAY_JOIN, the wrong-value hazard via isNullable at input_rows_count == 1, a captured lambda both as a terminal output and consumed by arrayMap, and a non-mismatched constant that must still be folded.

Verified in both directions on a debug build. Against master's executeActionForPartialResult the first case aborts the test binary with Logical error: 'Unexpected return type from negate. Expected Float64. Got Int256' through updateHeader -> evaluatePartialResult -> executeActionForPartialResult; with the fix all eight cases pass. Each hunk was also reverted individually and fails only its own case, and forcing the guard to fire unconditionally fails only the still-folds-a-constant case. Full unit suite: 22357 tests pass. 03915_exchange_tables_race passes 10 out of 10 runs.

Known residuals, both pre-existing on master and deliberately not addressed here. I measured each one against a build with this branch's ActionsDAG.cpp replaced by master's, and the behaviour is identical, so neither is caused or widened by this change:

  • The add-time fold in tryFoldFunctionToConstant does not perform this check. Handing addFunction a function_base resolved for one type together with a differently typed constant child raises Unexpected return type from negate. Expected Float64. Got Const(Int256). This diff does not touch that path, and adding the check there would alter DAG construction for every query on a scenario I could not reach from SQL.
  • At input_rows_count == 1 with allow_unknown_function_arguments, a type-sensitive folder above a node whose column is unknown can still fold from the type alone. Two shapes: identity -> isNullable over a Nullable(String) yields 0 where the real chain would yield 1 (unchanged from master), and an ARRAY_JOIN whose argument stopped being an array leaves the declared nested type in place, so isNullable above it also folds to 0. Closing this properly needs an explicit "unknown" marker propagated through descendants, which changes the evaluatePartialResult contract for every caller. I tried the two local shortcuts and neither works: clearing the type outright makes the unit-test binary abort and then segfault, because a null type in a ColumnWithTypeAndName breaks downstream consumers; handing up the argument's own type does not help, because the parent compares against the type it was itself resolved for. So this is a separate design decision rather than part of an abort-avoidance fix. Happy to follow up on any of these if you would like them in scope.

This branch also takes master's version of 03915_exchange_tables_race verbatim: master rewrote that test after this branch forked it (pinning enable_analyzer and capping concurrent clients so the flaky check does not run out of memory), and those changes belong with #110048's coverage rather than here.

Version info

  • Merged into: 26.8.1.1817 (included in 26.8 and later)
  • Backported to: 26.7.6.57, 26.6.4.44

When a concurrent EXCHANGE TABLES swaps a table with a different column
type between query analysis and header computation, partial evaluation in
ActionsDAG::updateHeader can hand a function an argument column whose type
no longer matches the type the function was resolved for. Executing the
function then trips an internal LOGICAL_ERROR (e.g. in
FunctionBinaryArithmetic::executeImpl2), which aborts the server in
debug/sanitizer builds.

Detect the argument type mismatch in executeActionForPartialResult before
executing the function and raise a recoverable TYPE_MISMATCH instead. The
normal execution path already throws ILLEGAL_TYPE_OF_ARGUMENT for the same
query, so legitimate queries are unaffected.

This is the abort targeted by the existing regression test
03915_exchange_tables_race.sh (added in ClickHouse#97411).

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The organic EXCHANGE TABLES race is too tight to hit on demand, so I widened it with two temporary env-gated hooks (an executeImpl sleep and a updateHeader header-type-swap that deterministically injects the exact post-EXCHANGE state). With the swap active, SELECT n * 0.123 FROM (SELECT * FROM t) (t: n Float64) aborts the server every time. Both hooks were removed before commit; the shipped diff is the fix only.
b Root cause explained? ActionsDAG::updateHeader binds header columns to DAG INPUT nodes by NAME only. A function node was resolved for its analysis-time argument types. When EXCHANGE TABLES swaps Float64->Int256 between analysis and header build, evaluatePartialResult feeds the Int256 column into the multiply function resolved for Float64; FunctionBinaryArithmetic::executeImpl2 finds no valid numeric case and throws LOGICAL_ERROR, which aborts in debug/sanitizer builds.
c Fix matches root cause? Yes. Guard executeActionForPartialResult's FUNCTION case: compare each argument's type against function_base->getArgumentTypes() and throw a recoverable TYPE_MISMATCH before executing, pre-empting the fatal LOGICAL_ERROR.
d Test intent preserved / new tests? The existing regression test 03915_exchange_tables_race.sh (added in #97411) targets exactly this abort and asserts no LOGICAL_ERROR; it now passes with the fix. No test weakened. A deterministic SQL test is not possible for a TOCTOU race; the internal type-mismatch state is not reachable from SQL without the race.
e Demonstrated both directions? Yes. Same query + widened window: without the guard -> signal 6 abort with the exact CI stack (updateHeader -> evaluatePartialResult -> FunctionBinaryArithmetic<MultiplyImpl>::executeImpl2); with the guard -> clean Code 53 TYPE_MISMATCH, server stays alive, 0 Logical error in log.
f Fix general, not a narrow patch? Yes. The guard is at the shared executeActionForPartialResult FUNCTION site, so it covers every function (not just multiply) and every argument type. During validation it also correctly intercepted the materialize variant of the same mismatch.
g Generalizes across inputs/types? Yes. The check uses IDataType::equals over all resolved argument types, so it applies to any type wrapper / any function / any argument position, not the single reported multiply(Int256, Float64) case.
h Backward compatible? Yes. No setting, format, or default changed. Legitimate queries take an identical path (verified: arithmetic, constant folding, materialize, arrayMap, subquery-header cases all unchanged). Only the fatal-abort path becomes a recoverable exception.
i Invariants/contracts preserved? Yes. evaluatePartialResult's contract (compute headers/constants, propagate exceptions to callers) is upheld; the new throw is inside the existing try and re-thrown like the sibling TYPE_MISMATCH/NOT_FOUND_COLUMN_IN_BLOCK cases. No data-structure or concurrency invariant is touched.

Session id: cron:clickhouse-worker-slot-5:20260708-072000

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd — could you review this? It stops a server abort during query planning: when a concurrent EXCHANGE TABLES swaps a column type between analysis and header build, ActionsDAG partial-result evaluation runs a function on a mismatched argument type and trips a fatal LOGICAL_ERROR in the function body. The fix checks argument types against the resolved function's types in executeActionForPartialResult and raises a recoverable TYPE_MISMATCH instead. This is the abort targeted by the existing 03915_exchange_tables_race.sh test.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9d47555]

Summary: ✅


AI Review

Summary

This PR hardens ActionsDAG partial evaluation against argument-type drift and adds deterministic unit coverage for the header-path aborts that used to show up as LOGICAL_ERROR assertions in debug / sanitizer builds. The header-path fixes look solid, but the one-row partial-evaluation path still lets a drifted child hand its stale analysis-time type to an ancestor, so a type-only folder can still produce a definitive value where the new contract says the result should stay unknown.

PR Metadata
  • 💡 Bug Fix no longer looks like the right Changelog category for the current scope. The PR body itself says the production EXCHANGE TABLES root cause was already fixed separately and that this branch now hardens evaluatePartialResult plus adds deterministic unit coverage, so I would switch the category to Not for changelog and remove the Changelog entry.
Findings
  • ⚠️ [src/Interpreters/ActionsDAG.cpp:1306-1316] [dismissed by author -- https://github.com/Avoid server abort on type mismatch during partial result evaluation #109747#discussion_r3611848389] The do-not-fold signal still stops at the first drifted node. executeActionForPartialResult clears only the child's column and keeps res_column.type at the stale resolved type, and evaluatePartialResult still feeds that type to parent folders when allow_unknown_function_arguments is enabled ([src/Interpreters/ActionsDAG.cpp:1589-1620]). A concrete current-head trace is isNullable(materialize(s)) with s drifted from String to Nullable(String): the child becomes {column = nullptr, type = String}, skip_materialize does not actually short-circuit because the normal execution path still runs right afterward at [src/Interpreters/ActionsDAG.cpp:1612-1618], and isNullable folds from elem.type alone at [src/Functions/isNullable.cpp:37-47], returning a definitive 0 instead of UNKNOWN. That still gives the one-row optimizer path a real folded boolean from drifted input rather than the intended unknown state. Suggested fix: propagate an explicit unknown marker (or otherwise invalidate the child's type for parent folding) and add a focused input_rows_count == 1 regression such as isNullable(materialize(s)) or isNullable(identity(s)).
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 8, 2026
The guard added in executeActionForPartialResult compared argument column
types against the resolved argument types with an exact equals(). That is too
strict: JOIN use_nulls and group_by_use_nulls legitimately widen a header
column to Nullable (or LowCardinality) while the function was resolved for the
inner type. The prepared function applies its default Nullable/LowCardinality
implementations for those wrappers, so such a wrapper-only difference executes
correctly, yet the exact comparison rejected it with a spurious TYPE_MISMATCH
(e.g. toNullable resolved for String but handed Nullable(String) after a JOIN).

Compare base types only (strip Nullable/LowCardinality) so the guard still
catches the genuine base-type mismatch it targets (the Int256-vs-Float64 swap
from a concurrent EXCHANGE TABLES that aborts the server), without rejecting
benign wrapper differences.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the Fast test regression the first revision of this PR introduced (d7e8112).

The guard compared argument types with an exact equals(), which was too strict: JOIN use_nulls / group_by_use_nulls legitimately widen a header column to Nullable/LowCardinality while the function was resolved for the inner type (e.g. toNullable resolved for String, handed Nullable(String) after a JOIN). The prepared function applies its default Nullable/LowCardinality implementations for those wrappers, so the query is valid — but the exact comparison rejected it with a spurious TYPE_MISMATCH, failing 01051_all_join_engine, 02531_storage_join_null_44940, 03059_analyzer_join_engine_missing_column, 03208_multiple_joins_with_storage_join, 03573_join_storage_not_change_kind, 04335_grouping_function_group_by_use_nulls, 01710_aggregate_projection_with_normalized_states.

Now the guard compares base types only (removeLowCardinalityAndNullable), so it still catches the genuine base-type mismatch it targets (the Int256-vs-Float64 swap from a concurrent EXCHANGE TABLES) while allowing benign wrapper differences.

Verified locally (debug build): the 7 previously-failing Fast tests pass (01710 requires the CI cluster config, passes for the non-remote part locally); 03915_exchange_tables_race (the abort this PR fixes) still passes; and a JOIN / plan-optimization / nullsafe sanity sweep shows no new TYPE_MISMATCH false positives.

…f throwing

The type-drift guard threw TYPE_MISMATCH whenever an argument column type
no longer matched the type the function was resolved for. That wrongly
rejected polymorphic functions (_CAST between AggregateFunction states with
different aggregate parameters, toNullable over a JOIN-widened Nullable
column) that handle the drift fine, breaking valid queries during header
computation.

There is no generic way to tell a strict function that aborts on a
mismatched type (e.g. arithmetic) from a polymorphic one that tolerates it,
so on a mismatch we no longer execute the function at all: constant folding
is only an optimization for header/constant evaluation, and the node's
declared result type is already known. Yield a non-const empty column of
that type and skip folding. Strict functions no longer abort the server in
debug/sanitizer builds, and polymorphic functions are no longer wrongly
rejected. The real execution path re-resolves the function and reports a
clean, recoverable error if the drift is genuinely illegal.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed a842e0f: reworked the type-drift handling in executeActionForPartialResult.

Why: the previous guard threw TYPE_MISMATCH on any argument-type drift (after narrowing to base types). That was still too broad: it wrongly rejected polymorphic functions that legitimately tolerate the drift during header computation. The Fast test caught one such case (01710_aggregate_projection_with_normalized_states): _CAST between two AggregateFunction states whose aggregate parameters differ (quantilesTimingMerge(0.5,0.95,0.99) vs the projection-normalized quantilesTimingMerge(0.95)) is valid, but the base-type comparison saw different AggregateFunction(...) types and threw. Narrowing the predicate again would just move the whack-a-mole to the next polymorphic function.

Fix: there is no generic way to distinguish a strict function that aborts on a mismatched type (arithmetic → internal LOGICAL_ERROR) from a polymorphic one that handles it (_CAST, toNullable). So on a mismatch we no longer execute the function at all. Constant folding here is only an optimization for header/constant evaluation, and the node's declared result type is already known — we yield a non-const empty column of that type and skip folding. Strict functions no longer abort the server; polymorphic functions are no longer wrongly rejected. If the drift is genuinely illegal, the real execution path re-resolves the function and reports a clean, recoverable error.

Validated (debug build, local server, buildId 4B7B5620):

  • 01710_aggregate_projection_with_normalized_states PASS (was TYPE_MISMATCH).
  • All previously-failing Fast tests PASS: 01051_all_join_engine, 02531_storage_join_null_44940, 03059_analyzer_join_engine_missing_column, 03208_multiple_joins_with_storage_join, 03573_join_storage_not_change_kind, 04335_grouping_function_group_by_use_nulls.
  • 03915_exchange_tables_race (the abort this PR fixes) still fixed: 0 LOGICAL_ERROR, server alive across the EXCHANGE/SELECT race.
  • Normal arithmetic, _CAST, toNullable, and constant folding unchanged (no false rejections).

Comment thread src/Interpreters/ActionsDAG.cpp Resolved
The type-drift fallback manufactured a one-row default column for
input_rows_count == 1 too. The shared partial-evaluation callers
(getFilterResult, createSelector, extractPathValuesFromFilter, reached via
filterResultForNotMatchedRows/MatchedRows, JOIN rewrites, shard skipping and
virtual-column path extraction) treat any non-null output as a definitive
folded value, so a tolerated drift would silently become false / 0 / '' rather
than "unknown", changing JOIN rewrites or skipping the wrong shards.

Only produce the placeholder column for header-only evaluation
(input_rows_count == 0). For the one-row callers leave the column null so they
route the node through their existing "unknown value" path, restoring the
pre-PR "cannot fold, treat as unknown" semantics on those paths while keeping
the abort avoidance for header computation.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch, addressed in 3ef351f.

The placeholder-column path is now restricted to header-only evaluation. On a type drift I only manufacture the default column when input_rows_count == 0; for the input_rows_count == 1 callers the result column is left null.

That routes those callers through their existing "unknown value" handling instead of reading a fabricated default as a definitive fold:

  • getFilterResult (Utils.cpp) returns UNKNOWN on a null column, so filterResultForNotMatchedRows / filterResultForMatchedRows and the JOIN-conversion rewrites bail to UNKNOWN (JOIN left unchanged).
  • evaluateConjunction returns {} on any null column, so evaluateExpressionOverConstantCondition yields no variants; StorageDistributed::skipUnusedShards then returns nullptr (no shards skipped) and extractPathValuesFromFilter returns {} (no path pruning).

This is the same "cannot fold, treat as unknown" outcome those paths had before this PR (the old strict-type mismatch threw and the try/catch around evaluatePartialResult turned it into UNKNOWN). The abort avoidance for header computation is unchanged.

Verified locally: EXCHANGE-TABLES race no longer trips LOGICAL_ERROR, and the JOIN-conversion optimizer and shard-skip constant folding still fire and produce correct results on the non-drift (happy) path.

Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Insert rows so the racing SELECT reads non-empty chunks, exercising the
runtime ExpressionActions execution path (function->execute on real data)
in addition to the header/partial-result path. A running SELECT keeps the
storage snapshot resolved at analysis time, so a concurrent EXCHANGE TABLES
cannot feed the resolved function a drifted argument type at runtime.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

The runtime ExpressionActions::executeAction path cannot hit this LOGICAL_ERROR after the EXCHANGE race, and I have added rows-inserting coverage to prove the runtime path is exercised.

Why the runtime path is safe:

  • The only place a post-EXCHANGE header type gets mapped onto a DAG resolved for a different type is ActionsDAG::updateHeader (ActionsDAG.cpp:1419), which matches header columns to DAG inputs by name only and then calls evaluatePartialResult(..., input_rows_count = 0). That function asserts chassert(input_rows_count <= 1) (ActionsDAG.cpp:1531): it exists solely for header/constant evaluation and never sees real chunks. That is the sole drift vector, and it is exactly what this PR guards.
  • Runtime execution is positional, not by-name. A running SELECT holds the StoragePtr and storage snapshot it resolved at analysis time; EXCHANGE TABLES swaps the catalog entry but the in-flight read continues from the originally-resolved storage, so the chunks fed to ExpressionActions::execute -> executeAction (ExpressionActions.cpp:693) carry the type the DAG was resolved for. The function never receives a drifted argument type at runtime.
  • Once the exchange settles, a fresh query re-resolves the overload against the new type and returns a clean, recoverable ILLEGAL_TYPE_OF_ARGUMENT (Code 43), never a LOGICAL_ERROR. Verified locally: after EXCHANGE TABLES a AND b, SELECT n * 0.123 FROM a returns Code: 43 ... Illegal types Int256 and Float64 of arguments of function multiply.

Empirical check on the PR binary (debug, buildId 210D6730...): the previous test only exercised the header path because it inserts no rows. I added an INSERT of 100k rows to both tables before the race, so the racing SELECT n * 0.123 now reads non-empty chunks and runs the function on real data. Ran the race with rows at high concurrency (700+ rounds across several query shapes: subquery, direct table, sum(n*0.123), n*0.123, n+n): zero LOGICAL_ERROR / "Unexpected return type" at runtime, server stayed up. Pushed as d25cec0.

Comment thread src/Interpreters/ActionsDAG.cpp Resolved
The argument type check strips Nullable/LowCardinality before comparing, so a
wrapper-only EXCHANGE TABLES drift (String -> Nullable(String) /
LowCardinality(String)) lets a wrapper-preserving function execute: materialize
returns its argument type and toNullable returns Nullable(arg), producing a
column whose type differs from the result type resolved before the exchange.
The post-execution columnMatchesType check then threw LOGICAL_ERROR, the exact
abort this guard avoids in debug/sanitizer builds.

Handle that mismatch the same way as argument drift when the arguments did
drift: skip folding and leave the column null so the input_rows_count == 1
callers route the node through their existing "unknown value" path, and only
manufacture a header placeholder for input_rows_count == 0. When arguments did
not drift, a result-type mismatch is a genuine function contract violation, so
the assertion is preserved.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in dfc81e0. You are right: the wrapper-stripped argument check lets materialize / toNullable execute on the current wrapper and return a type that no longer matches the pre-EXCHANGE node->result_type, so the post-execution columnMatchesType check at ActionsDAG.cpp threw Unexpected return type and aborted debug/sanitizer builds.

The guard now treats that post-execution mismatch as "do not fold", the same as an argument type drift, but only when the arguments actually drifted:

  • Arguments drifted (only by a wrapper, since the base-type check passed) and result type mismatches -> skip folding, leave the column null for input_rows_count == 1 callers (so they take the "unknown value" path), manufacture a placeholder only for input_rows_count == 0.
  • Arguments did not drift but result type still mismatches -> genuine function contract violation, keep raising the assertion.

Test: 03915_exchange_tables_race.sh now also races materialize(s) / toNullable(s) against an EXCHANGE TABLES that swaps String with Nullable(String), in addition to the existing Float64 <-> Int256 base-type race. Verified locally on the PR binary that the wrapper drift no longer trips LOGICAL_ERROR / Unexpected return type and that legitimate wrapper widening (JOIN join_use_nulls handing toNullable / materialize a Nullable argument) still folds correctly.

The abort targeted by 03915_exchange_tables_race fires in
ActionsDAG::updateHeader -> evaluatePartialResult during query planning,
so it needs no rows: a concurrent EXCHANGE TABLES swapping the column type
between analysis and header computation is enough. The runtime
ExpressionActions path was verified safe (drifted types raise a clean
recoverable ILLEGAL_TYPE_OF_ARGUMENT, not LOGICAL_ERROR), so the added
100k-row inserts provided no extra regression coverage while making the
flaky check (which reruns the test many times under sanitizers) exhaust
memory/time and time out. Drop them.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the Stateless tests (amd_asan_ubsan, flaky check) failure on the previous commit.

Root cause: the flaky check reran 03915_exchange_tables_race many times under sanitizers, and the 100k-row inserts I added (to exercise the runtime execution path) multiplied by that repetition exhausted the job's memory/time, so the server stopped responding and the job hit its 9000s timeout.

Those inserts were not buying regression coverage. I re-ran the race under ASan with 400 concurrent SELECT/EXCHANGE pairs across both the base-type (Float64<->Int256) and wrapper-only (String<->Nullable(String)) drifts: 181 drifted queries all returned a clean recoverable ILLEGAL_TYPE_OF_ARGUMENT (Code 43), zero LOGICAL_ERROR/Unexpected return type, server stayed up. The runtime ExpressionActions::executeAction path re-resolves against the live storage snapshot, so a drifted column never reaches function->execute there.

The abort this test targets is entirely in ActionsDAG::updateHeader -> evaluatePartialResult (planning time, input_rows_count 0/1), which is data-independent. So I dropped the inserts and kept the tables empty (the form this test has on master). Both drift races still fire during header computation; the test stays fast and no longer times out the flaky check.

Comment thread src/Interpreters/ActionsDAG.cpp Resolved
The previous guard only skipped folding when the wrapper-stripped base types
differed, and caught wrapper-preserving drift after execution via the result
type. That still lets a wrapper-sensitive value folder fold a wrong value: a
concurrent EXCHANGE TABLES that widens String to Nullable(String) leaves
isNullable resolved for String but handed Nullable(String); its
getConstantResultForNonConstArguments reads the argument type directly and
returns a definitive UInt8(1) instead of unknown, and because the result type
stays UInt8 no columnMatchesType check fires. The input_rows_count == 1 callers
(getFilterResult, evaluateExpressionOverConstantCondition) then consume that as
a real fold, so a wrapper-only race can silently change JOIN rewrites or skip
the wrong shards.

Skip folding on any exact argument type drift instead of only base-type drift.
Folding is only an optimization and is unsafe under drift in three ways (strict
function abort, wrapper-preserving result-type mismatch, wrapper-sensitive wrong
value); a single pre-execution exact comparison covers all three. Do-not-fold
does not throw, so the JOIN use_nulls / group_by_use_nulls wrapper widening this
guard previously rejected with a spurious TYPE_MISMATCH is still handled: the
node keeps its declared result type and the caller takes its existing unknown
path. When arguments did not drift, a result-type mismatch remains a genuine
function contract violation and keeps raising.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

You are right, and this closes a real gap: a wrapper-sensitive value folder like isNullable folds straight from the argument type (getConstantResultForNonConstArguments, isNullable.cpp:37-47) and its result type stays UInt8, so neither the wrapper-stripped argument check nor the post-execution columnMatchesType check fires, and the input_rows_count == 1 callers consume the wrong definitive value.

Fixed in 3bf1f4a by skipping folding on ANY exact argument type drift, before execution, rather than only on base-type drift. One pre-execution equals() comparison now subsumes all three failure modes:

  • strict function (arithmetic) on a drifted base type: LOGICAL_ERROR abort;
  • wrapper-preserving function (materialize/toNullable): mismatching result type;
  • wrapper-sensitive value folder (isNullable): wrong value with unchanged result type.

On any drift we do-not-fold: header-only evaluation (input_rows_count == 0) gets an empty placeholder column of the declared result type, and the input_rows_count == 1 callers get a null column and take their existing unknown path. This does not reintroduce the earlier spurious TYPE_MISMATCH on JOIN use_nulls / group_by_use_nulls wrapper widening, because do-not-fold no longer throws: the node keeps its declared result type and the caller re-resolves at real execution. When arguments did not drift, a result-type mismatch remains a genuine contract violation and keeps raising.

Verified on the fixed debug binary (buildId 42D7BB5A): happy path still folds (isNullable(materialize(...)), materialize, toNullable, 1+2, IN-subquery fold); LEFT JOIN with join_use_nulls=1 over toNullable(s)/materialize(s) returns correct results with 0 aborts; 03915_exchange_tables_race passes 5/5 with 0 LOGICAL_ERROR / Unexpected-return-type in the server log. Diff is 1 file (ActionsDAG.cpp), net -29 lines.

Replace the toNullable(s) probe (not wrapper-sensitive: makeNullableOrLowCardinalityNullable
returns Nullable(String) for both String and Nullable(String)) with isNullable(s), whose
constant folder reads the argument type directly and returns a UInt8 whose result type is
unchanged under wrapper-only drift. This exercises the one-row partial-evaluation path that
the exact-type-drift guard protects and refreshes the stale comment describing the old
wrapper-stripped comparison.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

The current guard (commit 3bf1f4a, src/Interpreters/ActionsDAG.cpp:1308-1327) no longer strips LowCardinality/Nullable: it compares each argument type against node->function_base->getArgumentTypes() by exact IDataType::equals, before any fold. So isNullable(s) is treated as do-not-fold under a String -> Nullable(String) wrapper-only drift exactly like every other function, and never reaches getConstantResultForNonConstArguments. For input_rows_count == 1 the result column is left null, which the one-row callers (getFilterResult / createSelector / extractPathValuesFromFilter) already route to "unknown", so no wrong definitive fold reaches the JOIN-rewrite / shard-skipping paths.

You are right that the test did not prove this: toNullable(s) is not a wrapper-sensitive probe (makeNullableOrLowCardinalityNullable returns Nullable(String) for both String and Nullable(String)), and nothing exercised the wrapper-sensitive value folder. Replaced it with isNullable(s) racing a String <-> Nullable(String) EXCHANGE TABLES (commit 2e22b0d), and refreshed the stale comment that described the old wrapper-stripped comparison.

Verified locally on the fix binary (buildId 42D7BB5A): the modified test passes 5/5, 0 LOGICAL_ERROR / Unexpected return type in the server log, server stays up; isNullable(materialize(...)) still folds correctly on non-drifted inputs (1 for Nullable(String), 0 for String).

… test

Add a JOIN-rewrite case: an ANY LEFT JOIN with a post-join isNullable(r.w)
filter triggers convertAnyJoinToSemiOrAntiJoin, which evaluates the filter via
evaluatePartialResult(input_rows_count = 1). Racing an EXCHANGE TABLES swapping
String with Nullable(String) drifts r.w between analysis and that evaluation,
exercising the input_rows_count == 1 do-not-fold path (getFilterResult -> UNKNOWN)
rather than only the updateHeader input_rows_count == 0 path the prior cases hit.

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

groeneai commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Added a focused case reaching the input_rows_count == 1 path (ceab83d).

The new block races an ANY LEFT JOIN whose post-join filter is `isNullable(r.w)` against an EXCHANGE swapping `String` with `Nullable(String)`. The filter triggers `convertAnyJoinToSemiOrAntiJoin`, which calls `filterResultForMatchedRows` -> `evaluatePartialResult(..., input_rows_count = 1)` to decide the rewrite, so the drifted `isNullable` argument now goes through the one-row do-not-fold path, not `updateHeader`.

Verified on the PR debug binary (buildId 42D7BB5A): 5 runs, server log shows `Converting ANY JOIN to SEMI JOIN` fired 18 times (the rewrite path is genuinely exercised), 0 LOGICAL_ERROR / Unexpected-return-type, server stayed up, empty output. Under the guard the drifted argument is do-not-fold, the filter column stays null, and `getFilterResult` returns UNKNOWN so the JOIN is left unchanged rather than folded on a wrong definitive value.

/// A strict function (arithmetic-like) resolved for one base type and then handed a header column
/// of another base type used to execute anyway during partial evaluation, tripping a
/// `LOGICAL_ERROR` inside the function body. In debug and sanitizer builds `LOGICAL_ERROR` is an
/// assertion failure (`handle_error_code` in `src/Common/Exception.cpp` calls

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.

optional: the function is Exception::handleErrorCode (src/Common/Exception.cpp:101).

Suggested change
/// assertion failure (`handle_error_code` in `src/Common/Exception.cpp` calls
/// assertion failure (`Exception::handleErrorCode` in `src/Common/Exception.cpp` calls

Comment on lines +240 to +242
/// A captured lambda consumed by a higher-order function is the case that matters in practice: the
/// capture is a CHILD of `arrayMap`, not a terminal output. Its column stays null (see above), so the
/// consuming function reports a recoverable `NOT_FOUND_COLUMN_IN_BLOCK`. That is the improvement being

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.

optional: arrayMap never runs here — evaluatePartialResult throws first, while collecting arguments, as soon as it sees the null child column under throw_on_error (ActionsDAG.cpp:1598-1601). Same error code, different source. The PR description carries the same sentence.

Suggested change
/// A captured lambda consumed by a higher-order function is the case that matters in practice: the
/// capture is a CHILD of `arrayMap`, not a terminal output. Its column stays null (see above), so the
/// consuming function reports a recoverable `NOT_FOUND_COLUMN_IN_BLOCK`. That is the improvement being
/// A captured lambda consumed by a higher-order function is the case that matters in practice: the
/// capture is a CHILD of `arrayMap`, not a terminal output. Its column stays null (see above), and
/// `evaluatePartialResult` raises a recoverable `NOT_FOUND_COLUMN_IN_BLOCK` while collecting the
/// arguments, before `arrayMap` runs at all. That is the improvement being

@tiandiwonder
tiandiwonder self-requested a review August 21, 2026 01:05
@tiandiwonder tiandiwonder removed their assignment Aug 21, 2026
@tiandiwonder

Copy link
Copy Markdown
Contributor

@KochetovNicolai would you please double check? thanks.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit f4143cf Aug 21, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
# Server from a 26.7 build (verified on 26.7.5.10); old analyzer on the SELECT side.
clickhouse-client -q "CREATE TABLE t1 (n Float64) ENGINE=Memory"
clickhouse-client -q "CREATE TABLE t2 (n Int256) ENGINE=Memory"
yes "EXCHANGE TABLES t1 AND t2;" | head -400 > ex.sql
yes "SELECT negate(n) FROM (SELECT * FROM t1) FORMAT Null;" | head -400 > sel.sql
clickhouse-client --queries-file ex.sql &
clickhouse-client --enable_analyzer=0 --queries-file sel.sql

# Observed on 26.7.5.10 within ~1s (3/3 runs):
#   Code: 49. DB::Exception: Unexpected return type from negate. Expected Int256.
#   Got Float64: while executing function negate on arguments n Float64 Float64(size = 0). (LOGICAL_ERROR)
# size = 0 => the fold happens during header computation (ActionsDAG::updateHeader ->
# evaluatePartialResult); on a debug/sanitizer build LOGICAL_ERROR aborts the server.
# Clean on master, 26.6.3.62, 26.5.7.64, 26.3.20.7, 25.8.32.4, 26.2.19.43.

Results:

  • Reproduces on: 26.7
  • Does not reproduce on: master, 26.6, 26.5, 26.3, 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 clean
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7.

CC component owner: @alexey-milovidov @KochetovNicolai

Analysis metadata

comp-query-execution · Severity P2 · Finding phase_d_pr109747

  • Verified against master build d8bf9a01b85b (aarch64)
Introducing change: not identified
  • Secondary components: comp-testing

@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 Aug 29, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 29, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #109747 to 26.6: Avoid server abort on type mismatch during partial result evaluation
clickhouse-gh Bot added a commit that referenced this pull request Sep 1, 2026
Backport #109747 to 26.7: Avoid server abort on type mismatch during partial result evaluation
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

26.3 is affected by this and sits below the current backport floor

@fm4v you applied v26.4-must-backport here on 2026-08-29. That floor expands to the active branches at or above 26.4, so 26.3 was excluded by construction. 26.3 is affected, and it aborted again after the label went on:

When (UTC) 26.3 sha Check
2026-09-08 14:25:00 9c66aa353fbf Stress test (amd_tsan)
2026-08-21 14:02:11 c883c70ec0eb Stress test (amd_tsan)

Both go through the function this PR guards:

Logical error: 'Arguments of 'multiply' have incorrect data types: 'n' of type 'Int256', '0.123' of type 'Float64''.

DB::abortOnFailedAssertion
DB::FunctionBinaryArithmetic<MultiplyImpl, NameMultiply>::executeImpl2   FunctionBinaryArithmetic.h:2787
DB::IFunction::executeImplDryRun                                        IFunction.h:472
DB::executeActionForPartialResult                                       ActionsDAG.cpp:949
DB::ActionsDAG::evaluatePartialResult                                   ActionsDAG.cpp:1168
DB::ActionsDAG::updateHeader                                            ActionsDAG.cpp:1057
DB::InterpreterSelectQuery::executeImpl

executeActionForPartialResult is present on 26.3, so the path is reachable there.

Presence per active branch today, by content marker (argument_types_drifted in src/Interpreters/ActionsDAG.cpp, plus the gtest this PR adds as a second marker):

Branch this PR #110048 2735-47bf aborts, 30d
master yes yes 0
26.8 yes (inherited) yes 0
26.7 yes (#117050) no 0
26.6 yes (#117049) no 0
26.3 no no 2

26.6 and 26.7 are the useful control. They lack @ alexey-milovidov's #110048, so the type drift still happens there, and they still record zero aborts, because this PR turns the drift into ordinary header computation instead. 26.3 lacks both and aborts. So this PR on its own is enough for 26.3.

The label alone would be a no-op

receive_prs_for_backport searches type:pr repo:... -label:pr-backports-created (tests/ci/cherry_pick.py:1074), and this PR has carried pr-backports-created since 2026-08-29. reconcile_backport_branches puts it the same way in its docstring: the original is dropped from that search "for good" once the label is set. The two paths that clear the label both need an artifact that does not exist for 26.3, since no 26.3 cherry-pick was ever opened: _remove_backported_label needs a reopened cherrypick/26.3/109747, and the stranded-branch path needs a backport/26.3/109747 carrying changes.

So if you agree 26.3 should get this, it takes two edits:

  1. add v26.3-must-backport
  2. remove pr-backports-created

The floor then expands to {26.3, 26.6, 26.7, 26.8}, and only 26.3 produces new work: 26.6 and 26.7 bind to their merged cherry-picks and 26.8 already carries the fix.

I have not touched 26.3, per @ pufit's rule that backports go through the label route rather than hand-authored PRs.

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 groeneai-origin-unknown PR origin: unclassified (legacy task) pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants