Repository navigation
Avoid server abort on type mismatch during partial result evaluation - #109747
alexey-milovidov merged 27 commits into
Conversation
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-5:20260708-072000 |
|
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. |
|
Workflow [PR], commit [9d47555] Summary: ✅
AI ReviewSummaryThis PR Metadata
Findings
Final VerdictStatus: |
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]>
|
Fixed the Fast test regression the first revision of this PR introduced (d7e8112). The guard compared argument types with an exact Now the guard compares base types only ( Verified locally (debug build): the 7 previously-failing Fast tests pass (01710 requires the CI cluster config, passes for the non-remote part locally); |
…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]>
|
Pushed a842e0f: reworked the type-drift handling in Why: the previous guard threw Fix: there is no generic way to distinguish a strict function that aborts on a mismatched type (arithmetic → internal Validated (debug build, local server, buildId 4B7B5620):
|
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]>
|
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 That routes those callers through their existing "unknown value" handling instead of reading a fabricated default as a definitive fold:
This is the same "cannot fold, treat as unknown" outcome those paths had before this PR (the old strict-type mismatch threw and the Verified locally: EXCHANGE-TABLES race no longer trips |
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]>
|
The runtime Why the runtime path is safe:
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 |
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]>
|
Fixed in dfc81e0. You are right: the wrapper-stripped argument check lets 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:
Test: |
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]>
|
Fixed the Root cause: the flaky check reran 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 ( The abort this test targets is entirely in |
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]>
|
You are right, and this closes a real gap: a wrapper-sensitive value folder like Fixed in 3bf1f4a by skipping folding on ANY exact argument type drift, before execution, rather than only on base-type drift. One pre-execution
On any drift we do-not-fold: header-only evaluation ( Verified on the fixed debug binary (buildId 42D7BB5A): happy path still folds ( |
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]>
|
The current guard (commit 3bf1f4a, You are right that the test did not prove this: Verified locally on the fix binary (buildId 42D7BB5A): the modified test passes 5/5, 0 |
… 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]>
|
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 |
There was a problem hiding this comment.
optional: the function is Exception::handleErrorCode (src/Common/Exception.cpp:101).
| /// assertion failure (`handle_error_code` in `src/Common/Exception.cpp` calls | |
| /// assertion failure (`Exception::handleErrorCode` in `src/Common/Exception.cpp` calls |
| /// 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 |
There was a problem hiding this comment.
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.
| /// 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 |
|
@KochetovNicolai would you please double check? thanks. |
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:
Backport the fix to CC component owner: @alexey-milovidov @KochetovNicolai Analysis metadata
Introducing change: not identified
|
Backport #109747 to 26.6: Avoid server abort on type mismatch during partial result evaluation
Backport #109747 to 26.7: Avoid server abort on type mismatch during partial result evaluation
…ch during partial result evaluation
…ch during partial result evaluation
26.3 is affected by this and sits below the current backport floor@fm4v you applied
Both go through the function this PR guards:
Presence per active branch today, by content marker (
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
So if you agree 26.3 should get this, it takes two edits:
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. |
Related: #110048
Related: #97411
Changelog category (leave one):
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_ERRORwhile 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 recoverableILLEGAL_TYPE_OF_ARGUMENTerror from the normal execution path.Description
ActionsDAG::updateHeadermatches header columns to DAG input nodes by name only, then runsevaluatePartialResultto 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,executeActionForPartialResultused to execute the function anyway. That trips aLOGICAL_ERRORinside the function body (for exampleFunctionUnaryArithmetic: "negate's argument does not match the expected data type"), and becausehandle_error_coderoutesLOGICAL_ERRORtoabortOnFailedAssertion, a debug or sanitizer build aborts the whole server process during planning rather than failing the one query.Fix. Before executing a
FUNCTIONnode in partial evaluation, compare each argument column's type against the type recorded infunction_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.input_rows_count == 0(header computation) an empty column of the declared result type is produced, so header computation proceeds.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
isNullablederives its value from the argument type alone: its result type isUInt8either way, so a wrapper-only difference would produce a definitive but wrong value that no result-type check can catch.ALIASandARRAY_JOINneed 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 whatExpressionActions::executeActionalready does in its ownALIASandARRAY_JOINcases.One result type cannot be instantiated:
DataTypeFunction, the result type of a captured lambda, inheritsIDataTypeDummy::createColumn, which throwsNOT_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 recoverableNOT_FOUND_COLUMN_IN_BLOCK, whereas executing the stale capture raisesCannot capture column N because it has incompatible type, anotherLOGICAL_ERRORabort. (DataTypeNothingandDataTypeSetderive from the same base but do overridecreateColumn, 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 fromjoined_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 what03915_exchange_tables_raceraces 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 asBug Fixbecause the abort was user-visible on released builds before #110048, but I am happy to move it toNot for changelogif 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
updateHeaderbinds 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.cppcovers a strict function (Float64resolved,Int256supplied), a wrapper-only difference throughmaterialize, the same mismatch behind anALIASand behind anARRAY_JOIN, the wrong-value hazard viaisNullableatinput_rows_count == 1, a captured lambda both as a terminal output and consumed byarrayMap, and a non-mismatched constant that must still be folded.Verified in both directions on a debug build. Against master's
executeActionForPartialResultthe first case aborts the test binary withLogical error: 'Unexpected return type from negate. Expected Float64. Got Int256'throughupdateHeader->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_racepasses 10 out of 10 runs.Known residuals, both pre-existing on
masterand deliberately not addressed here. I measured each one against a build with this branch'sActionsDAG.cppreplaced by master's, and the behaviour is identical, so neither is caused or widened by this change:tryFoldFunctionToConstantdoes not perform this check. HandingaddFunctionafunction_baseresolved for one type together with a differently typed constant child raisesUnexpected 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.input_rows_count == 1withallow_unknown_function_arguments, a type-sensitive folder above a node whose column is unknown can still fold from the type alone. Two shapes:identity -> isNullableover aNullable(String)yields0where the real chain would yield1(unchanged frommaster), and anARRAY_JOINwhose argument stopped being an array leaves the declared nested type in place, soisNullableabove it also folds to0. Closing this properly needs an explicit "unknown" marker propagated through descendants, which changes theevaluatePartialResultcontract 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 aColumnWithTypeAndNamebreaks 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_raceverbatim: master rewrote that test after this branch forked it (pinningenable_analyzerand 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
26.8.1.1817(included in26.8and later)26.7.6.57,26.6.4.44